Reading a cookie in a different application in Asp.Net - asp.net

I have an application in Asp.Net and at a click of a button it is supposed to launch another mapping application. In that application the credentials of the user like user name and Email are required. So, I was trying to set a cookie and fix the domain of the cookie to that application but I am not able to see the cookie in that application. I am not really sure what is going wrong or if I have made some mistake in the cookie.
MembershipUser usr = Membership.GetUser();
Guid newUserId = (Guid)usr.ProviderUserKey;
HttpCookie SampleCookie = new HttpCookie("UserInfo");
Response.Cookies["UserInfo"]["UserName"] = usr.UserName;
Response.Cookies["UserInfo"]["Email"] = usr.Email;
SampleCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(SampleCookie);
SampleCookie.Domain = "http://157.182.212.204/MAP";
Thank you once again for the help.
Code for MAP application:
function Get_Cookie( check_name ) {
// first we'll split this cookie up into name/value pairs
// note: document.cookie only returns name=value, not the other components
var a_all_cookies = document.cookie.split( ';' );
var a_temp_cookie = '';
var cookie_name = '';
var cookie_value = '';
var b_cookie_found = false; // set boolean t/f default f
for ( i = 0; i < a_all_cookies.length; i++ )
{
// now we'll split apart each name=value pair
a_temp_cookie = a_all_cookies[i].split( '=' );
// and trim left/right whitespace while we're at it
cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
// if the extracted name matches passed check_name
if ( cookie_name == check_name )
{
b_cookie_found = true;
// we need to handle case where cookie has no value but exists (no = sign, that is):
if ( a_temp_cookie.length > 1 )
{
cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
}
// note that in cases where cookie is initialized but no value, null is returned
return cookie_value;
break;
}
a_temp_cookie = null;
cookie_name = '';
}
if ( !b_cookie_found )
{
return null;
}
}
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
alert(Get_Cookie("UserName"));
The code for the WVWRAPICt page RESET.aspx.cs is given below...This is where the cookie is being set
using System;
using System.Collections;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class RESET_RESET : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Menu Nav = Master.FindControl("NavigationMenu1") as Menu;
MenuItemCollection Menu = Nav.Items;
foreach (MenuItem item in Menu)
{
string name = item.Text.ToString();
if (name == "ADMIN")
{
item.Enabled = User.IsInRole("Administrator");
}
if (name == "ICT")
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
MembershipUser usr = Membership.GetUser();
Guid newUserId = (Guid)usr.ProviderUserKey;
HttpCookie SampleCookie = new HttpCookie("UserInfo");
SampleCookie["UserName"] = usr.UserName;
SampleCookie["Email"] = usr.Email;
string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string checkSiteEventIDSQL = "Select * from UserProfiles WHERE UserId='" + newUserId + "'";
using (SqlConnection myConnection1 = new SqlConnection(connectionString))
{
try
{
myConnection1.Open();
SqlCommand myCommand1 = new SqlCommand(checkSiteEventIDSQL, myConnection1);
SqlDataReader myReader = myCommand1.ExecuteReader();
if (myReader.HasRows)
{
while (myReader.Read())
{
string Agency = (myReader.GetValue(2)).ToString();
SampleCookie["Agency"] = Agency;
}
}
}
catch (Exception ex)
{
}
finally
{
myConnection1.Close();
}
}
SampleCookie.Expires = DateTime.Now.AddDays(1);
SampleCookie.Domain = "157.182.212.204/MAP";
// SampleCookie.Path = "/MAP";
Response.Cookies.Add(SampleCookie);
Response.Redirect("http://157.182.212.204/MAP/index.html");
}
}

Regarding trouble with the way you are setting your cookie... you're not going to find the cookie in the response unless you've added it to the response. (And if you ARE finding it, you're just over-writing that cookie a couple lines later). Just edit the cookie directly then add to the cookie jar. Also I believe the MAP should be in the path property of the cookie (not sure how big of a difference it makes). As far as I know you don't want the http in the domain (again, not sure if the browser is smart enough to handle).
MembershipUser usr = Membership.GetUser();
Guid newUserId = (Guid)usr.ProviderUserKey;
HttpCookie sampleCookie = new HttpCookie("UserInfo");
sampleCookie["UserName"] = usr.UserName;
sampleCookie["Email"] = usr.Email;
sampleCookie.Expires = DateTime.Now.AddDays(1);
sampleCookie.Domain = "157.182.212.204";
sampleCookie.Path = "/MAP";
Response.Cookies.Add(sampleCookie);
Cookies can only be set to a domain which is a 'tail' of the current FQDN. So if your current FQDN is not 157.182.212.204, the cookie will not set in the browser. By tail, for example, I mean http://overflow.acme.com could set a cookie for overflow.acme.com or acme.com, but not for fubar.acme.com or fubar.com.
My guess is if your application is on a different FQDN than the MAP application, you're going to need to figure a different way to pass the user name and e-mail to the map application (maybe post to a page on the map application which can set the cookie and then redirect to the appropriate page?
Update after you've posted some more code:
Try this:
SampleCookie.Domain = "157.182.212.204";
SampleCookie.Path = "/MAP";
Response.Cookies.Add(SampleCookie);
Response.Redirect("http://157.182.212.204/MAP/index.html", false);
Setting false on the response.redirect should cause the set cookie headers to come through. You might need to short circuit other logic in your page if you have anything in the render events
Or just pass the stuff in a query string. You're not using HttpOnly cookies (so a user could inject the cookies).

Related

vulnerability from security team in forget password controller in asp .net

I have a controller form application and the security team they said there is a vulnerability you can put any user_id fom postman inside the controller like this
ForgotPassword/user_id
how I can remove this vulnerability check the code below:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult ForgotPassword(string emailId)
{
var helper = new Helper.Helper();
List<SqlParameter> args = new List<SqlParameter>();
args.Add(new SqlParameter("#Pin_email_id", emailId));
var req_resp = new Dictionary<string, object>();
try
{
using (DataSet dataset = helper.ExecuteSqlQuery("Web_Forgot_Password", args))
{
if (dataset != null && dataset.Tables.Count > 0 && dataset.Tables[0].Rows.Count > 0)
{
if (dataset.Tables[0].Rows[0]["Status"].ToString() == "Success")
{
req_resp["status"] = true;
req_resp["message"] = dataset.Tables[0].Rows[0]["Description"].ToString();
req_resp["code"] = dataset.Tables[0].Rows[0]["Code"].ToString();
string password = dataset.Tables[0].Rows[0]["user_password"].ToString();
SendForgotMail(emailId, dataset.Tables[0].Rows[0]["user_name"].ToString(), helper.Decrypt(password), dataset.Tables[0].Rows[0]["employee"].ToString());
return Json(req_resp);
}
else
{
req_resp["status"] = false;
req_resp["message"] = dataset.Tables[0].Rows[0]["Description"].ToString();
req_resp["code"] = dataset.Tables[0].Rows[0]["Code"].ToString();
return Json(req_resp);
}
}
else
{
req_resp["status"] = false;
req_resp["message"] = "Request Failed";
req_resp["code"] = "1005";
return Json(req_resp);
}
}
}
catch
{
var response = new
{
status = false,
message = "Request failed",
code = "1005"
};
return Json(response);
}
}
Well normally you store only password hashes in your database, which are not decryptable. Watching helper.Decrypt(password) in your code and sending the original password as a plain text in email is something painful. Normally I would just send a password reset link which can be used only once.
I checked the SqlParemater docs, it is added as a String value the way you use it, so it is not SQL injectable. Without the exact SQL I cannot tell much. I think they meant that it is SQL injectable, but then they should send evidence at least.

Login users at the same time problems in signalr

I'm working on a social network with ASP.NET and signalr. I have a simple login page, if it finds the user in the database it creates an Application variable and redirect the user to the profile page and in this page i invoke my Connect method declared in my hub class, this method takes the userid in the session and it give the friend list of this user. That works great when two or many users logged in at different time. The thing is, when two or several users logged in at the same time, the connect method declared in my hub takes the last user id stored in the Application variable and it give the friend list of this last user id and it send it to all user connected.
I can't find the correct approach.
Loggin Page code:
protected void btn_login_Click(object sender, EventArgs e)
{
Tbl_User user = new Tbl_User();
user = FonctionCommun.Login(txt_UserName.Text , txt_PassWord.Text);
if (user != null)
{
Application["UserID"] = user.UserID.ToString();
Response.Redirect("Profile.aspx");
}
else {
Label1.Visible = true;
}
}
My connect method code:
public void connect()
{
UserID = Guid.Parse(HttpContext.Current.Application["UserID"].ToString());
string OutPut = "";
if (ListOnlineUser.Count(x => x.UserID == UserID) == 0)
{
ListOnlineUser.Add(new OnlineUsers { UserID = UserID, ConnetionID = Guid.Parse(Context.ConnectionId) });
objchat.SetOnline(UserID);
ListFriends = objchat.GetFriendLoginStatus(UserID);
}
foreach (Tbl_User item in ListFriends)
{
if (item.Status == "1")
{
OnlineUsers onlineFriend = ListOnlineUser.FirstOrDefault(x => x.UserID == Guid.Parse(item.UserID.ToString()));
if (onlineFriend != null)
{
using (FIESTA_ADVISOREntities BD = new FIESTA_ADVISOREntities())
{
Tbl_User Obj_User = BD.Tbl_User.Where(o => o.UserID == UserID).FirstOrDefault();
if (Obj_User.ProfileImage != null)
{
string ext = BD.Assets.Where(o => o.url == Obj_User.ProfileImage).Select(o => o.MimeType).FirstOrDefault();
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = Obj_User.ProfileImage.ToString(), Ext = ext };
OutPut = JsonConvert.SerializeObject(res);
}
else {
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = "111", Ext = "png" };
OutPut = JsonConvert.SerializeObject(res); }
Clients.Client(onlineFriend.ConnetionID.ToString()).OnNewUserConnect(OutPut);
}
}
}
}
Clients.Caller.ShowFriends(ListFriends);
}
Try session variable instead of application variable. Application variable shared through out application working. So Whenever new user this is override. But if you use session variable that will never override by any other user
Also you can use query string in signalr in which you can pass userid as query string so in each request userid will be in query string
$.connection.hub.qs = 'userid=' + "UserId";

WCF Forms Authentication authorization using ASP.NET roles = Access Denied?

I have a basic WPF application where the client writes to a database. I'm using IIS on a server 2012 machine to host the web service. I'm trying to implement Forms authentication, and I have all that working (passing a username and password in the xaml.cs from the client which authenticates my ASP.NET user which works. I then want to implement ASP.NET roles authorization for different commands (Submit Request, Remove Request, etc). The method we're supposed to use is "[PrincipalPermission(SecurityAction.Demand, Role = "Allowed")]"
In theory this should just use the credentials passed in the client (which I've confirmed works) when I try to hit the buttons and it should check if the user I passed is in the role, and if so it allows and if not it denies. However, whether or not the user is in the role it still says "Access is Denied".
Any thoughts?
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.Security.Permissions;
using RequestRepository;
using System.Threading;
using System.Web;
namespace RequestServiceLibrary
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class RequestService : IRequestService
{
private List<Request> requests = new List<Request>();
private RequestLibraryEntities context = new RequestLibraryEntities();
[PrincipalPermission(SecurityAction.Demand, Role = "Allowed")]
public string SubmitRequest(Request req)
{
Thread.CurrentPrincipal = HttpContext.Current.User;
if (context.Requests.Count() == 0)
populateRequests();
req.Id = Guid.NewGuid().ToString();
req.TimeSubmitted = DateTime.Now;
requests.Add(req);
addRequest(req);
return req.Id;
}
[PrincipalPermission(SecurityAction.Demand, Role = "Allowed")]
public bool UpdateRequest(Request req)
{
Thread.CurrentPrincipal = HttpContext.Current.User;
bool returnval = false;
try
{
var getobject = requests.Find(x => x.Id.Equals(req.Id));
if (getobject != null) //checks to make sure the object isn't empty
{
getobject.Username = req.Username;
getobject.Password = req.Password;
getobject.RequestedResource = req.RequestedResource;
getobject.TimeSubmitted = req.TimeSubmitted;
}
//Find the request object in the database
var Id = Guid.Parse(req.Id);
var rl = context.Requests.Find(Id);
//Update that object with the values from req
rl.Username = req.Username;
rl.Password = req.Password;
rl.RequestedResource = req.RequestedResource;
rl.TimeTransmitted = req.TimeSubmitted;
context.SaveChanges();
returnval = true;
return returnval;
}
catch (Exception) { return returnval; }
}
public List<Request> GetRequests()
{
populateRequests();
return requests;
}
[PrincipalPermission(SecurityAction.Demand, Role = "Disallowed")]
public bool RemoveRequest(string id)
{
bool rval = false;
try
{
Request req = requests.Find(x => x.Id.Equals(id));
requests.Remove(req);
rval = delRequest(req);
return rval;
}
catch (Exception)
{
return false;
}
}
private void populateRequests()
{
requests = new List<Request>();
var rl = context.Requests.ToList();
foreach (var r in rl)
{
requests.Add(new Request()
{
Id = r.Id.ToString(),
Password = r.Password,
RequestedResource = r.RequestedResource,
TimeSubmitted = r.TimeTransmitted,
Username = r.Username
});
}
}
private void addRequest(Request req)
{
try
{
var r = context.Requests.Create();
r.Id = Guid.Parse(req.Id);
r.Username = req.Username;
r.Password = req.Password;
r.RequestedResource = req.RequestedResource;
r.TimeTransmitted = req.TimeSubmitted;
context.Requests.Add(r);
context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Console.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
private bool delRequest(Request req)
{
Guid Id = Guid.Parse(req.Id);
var r = context.Requests.Create();
r.Id = Id;
var rl = context.Requests.Find(Id);
try
{
context.Requests.Remove(rl);
context.SaveChanges();
return true;
}
catch (Exception) { return false; }
}
}
}
In order to be able to use PrincipalPermissionAttribute in this way, you need to first set Thread.CurrentPrincipal to a Principal with the appropriate roles ("Allowed" in this case).
For example you could use ClientRoleProvider to do this, or simply create the Principal manually (possibly using roles you retrieve from the web service).

ProfileCommon could be not found

I got error ProfileCommon could be not found , in my code. I don't know how to fix the error. I put namespace using system.Web.Profile, but error still does here. Could someone help how to do that? Please help me if you know. Thank you
public partial class UserProfile : System.Web.UI.UserControl
{
private string _userName = "";
public string UserName
{
get { return _userName; }
set { _userName = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
this.Page.RegisterRequiresControlState(this);
}
protected override void LoadControlState(object savedState)
{
object[] ctlState = (object[])savedState;
base.LoadControlState(ctlState[0]);
_userName = (string)ctlState[1];
}
protected override object SaveControlState()
{
object[] ctlState = new object[2];
ctlState[0] = base.SaveControlState();
ctlState[1] = _userName;
return ctlState;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// if the UserName property contains an emtpy string, retrieve the profile
// for the current user, otherwise for the specified user
ProfileCommon profile = this.Profile;
if (this.UserName.Length > 0)
profile = this.Profile.GetProfile(this.UserName);
txtFirstName.Text = profile.FirstName;
txtLastName.Text = profile.LastName;
ddlGenders.SelectedValue = profile.Gender;
if (profile.BirthDate != DateTime.MinValue)
txtBirthDate.Text = profile.BirthDate.ToShortDateString();
ddlOccupations.SelectedValue = profile.Occupation;
txtWebsite.Text = profile.Website;
txtStreet.Text = profile.Address.Street;
txtCity.Text = profile.Address.City;
txtPostalCode.Text = profile.Address.PostalCode;
txtState.Text = profile.Address.State;
txtPhone.Text = profile.Contacts.Phone;
txtFax.Text = profile.Contacts.Fax;
}
}
public void Save()
{
// if the UserName property contains an emtpy string, save the current user's
// profile, othwerwise save the profile for the specified user
ProfileCommon profile = this.Profile;
if (this.UserName.Length > 0)
profile = this.Profile.GetProfile(this.UserName);
profile.FirstName = txtFirstName.Text;
profile.LastName = txtLastName.Text;
profile.Gender = ddlGenders.SelectedValue;
if (txtBirthDate.Text.Trim().Length > 0)
profile.BirthDate = DateTime.Parse(txtBirthDate.Text);
profile.Occupation = ddlOccupations.SelectedValue;
profile.Website = txtWebsite.Text;
profile.Address.Street = txtStreet.Text;
profile.Address.City = txtCity.Text;
profile.Address.PostalCode = txtPostalCode.Text;
profile.Address.State = txtState.Text;
profile.Contacts.Phone = txtPhone.Text;
profile.Contacts.Fax = txtFax.Text;
profile.Save();
}
}
As Mark pointed out, profiles only work out-of-the-box with the website template and I have blogged instructions on how to use the plug-in to facilitate the use of profiles for the Web Application project:
http://www.codersbarn.com/post/2008/07/10/ASPNET-PayPal-Subscriptions-IPN.aspx
It is possible to do it yourself, and here's a fully working implementation that you can download:
http://leedumond.com/blog/asp-net-profiles-in-web-application-projects/
According to these links(link1, link2)
Web Applications don't support the auto generation of the ProfileCommon object
The first link then give's a link to a VS Addin and instructions on how to incorporate it into the build process in order to work around the problem
There is a very simple work-around for this, for all coders who just want to hack on with things. You can get the ProfileBase type and load the profile into that, but you lose strong typing. If you are in control of the data in the profile, or you are sure that the data in the profile is of a certain type, you are good to go.
string user = "Steve"; // The username you are trying to get the profile for.
bool isAuthenticated = false;
MembershipUser mu = Membership.GetUser(user);
if (mu != null)
{
// User exists - Try to load profile
ProfileBase pb = ProfileBase.Create(user, isAuthenticated);
if (pb != null)
{
// Profile loaded - Try to access profile data element.
// ProfileBase stores data as objects in (I assume) a Dictionary
// so you have to cast and check that the cast succeeds.
string myData = (string)pb["MyKey"];
if (!string.IsNullOrWhiteSpace(myData))
{
// Woo-hoo - We're in data city, baby!
Console.WriteLine("Is this your card? " + myData + " - Ta Dah!");
}
}
}

access ASP.Net Session variable in Facebook C# SDK

I've my ASP.Net HTML 5 Application, Which have the image byte array in Session,
I'm using the Latest 5.X C# facebook SDK from CodePlex.
But when user is authorized and Coming back to my canvas page at that time I can't access my ASP.Net Session, its give me a null value.
Here is my Code.
CanvasAuthorizer _authorizer = new CanvasAuthorizer { Perms = "publish_stream,offline_access,manage_pages" };
if (!_authorizer.IsAuthorized())
{
_authorizer.HttpContext.Session["ImageByte"] = Session["ImageByte"];
// Go for Login,
_authorizer.HandleUnauthorizedRequest();
}
else
{
//After Login
//Here its give me a null instead of Byte Array(My Image Byte Array).
byte[] imageByte = (byte[])(_authorizer.HttpContext.Session["ImageByte"]);
var mediaObject = new FacebookMediaObject
{
FileName = "sample.png",
ContentType = "image/png"
};
mediaObject.SetValue(imageByte);
dynamic parameters = new ExpandoObject();
parameters.source = mediaObject;
parameters.uid = _authorizer.Session.UserId;
var fb = new FacebookClient(Facebook.FacebookContext.Current.AppId, Facebook.FacebookContext.Current.AppSecret);
parameters.access_token = _authorizer.Session.AccessToken;
string path = "/me/photos";
dynamic param = new ExpandoObject();
param.access_token = _authorizer.Session.AccessToken;
param.uid = _authorizer.Session.UserId;
param.source = mediaObject;
dynamic result = fb.Post(path, param);
Now pls give me some suggestion, Where I'm missing, How can I access my Application Session.
Thanks,
Jigar Shah
Try this:
protected void Page_Load(object sender, EventArgs e)
{
Response.AppendHeader("P3P", "CP=\"CAO PSA OUR\"");
if (!Page.IsPostBack)
{
}
}
I recently found that the following hidden field is required for proper functioning.
Please make shore u have it.
<input type="hidden" name="signed_request" value="<%: Request.Params["signed_request"]%>"/>
Link to my Question

Resources