User authentication Failed - c#

I have created a Website in ASP.Net MVC5 and used a login function in it, it works fine on localhost but when I uploaded the site server,
Server redirects me to the login page on each click.
Below is login Function
public ActionResult DoLogin(string username, string password)
{
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
var user = new UserRepository().GetAll()
.Where(u => u.UserName.ToUpper() == username.Trim().ToUpper()
&& u.Password == password).SingleOrDefault();
if (user != null)
{
FormsAuthentication.SetAuthCookie(user.UserName,true);
var authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddHours(24), true, user.Roles);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Response.Cookies.Add(authCookie);
Session["Name"] = user.Name;
return RedirectToAction("Index", "Student");
}
}
ViewBag.ErrorMessage = "User Name or Password is incorrect";
return View("Login");
}
then I added the below function in Global.asax.cs File.
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
var roles = authTicket.UserData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
}
}
}
After that I have added [Authorize(Roles = "Admin")] before each Controller (Not before methods in Controller) I want to Restrict access to.
Now, whenever I login, It redirects me to Index Method of Student controller, after that I click on some other link it again takes me to the Login page. Sometimes it takes me to clicked link without taking me to Login Page. Whats the Problem with my code? it works fine on localhost.

You are assigning the auth ticket twice;
if (user != null)
{
//FormsAuthentication.SetAuthCookie(user.UserName,true); Remove it
var authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddHours(24), true, user.Roles);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Response.Cookies.Add(authCookie);
Session["Name"] = user.Name;
return RedirectToAction("Index", "Student");
}
Also, I suggest you to don't store the roles in cookie because if the user role has been removed or added new one, you can't update them. So,
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
var roles = authTicket.UserData.Split(',');//fill it from database and it could be better to use cache mechanism for performance concern
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
}
}
}

Related

Can't check user role. User.IsInRole returning false

I'm trying to check a user role in View:
#if (User.IsInRole("User"))
but getting all time false, although
User.Identity.IsAuthenticated
User.Identity.Name
returns true and name.
My forms authentication service:
public static void SignIn(string userName, string role, bool createPersistentCookie)
{
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(30),
createPersistentCookie,
role);
string encTicket = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
Expires = authTicket.Expiration,
Path = FormsAuthentication.FormsCookiePath
};
if (HttpContext.Current != null)
{
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
and calling
FormsAuthenticationService.SignIn(model.UserName, "User", true);
Fixed by adding to Global.asax :
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
return;
FormsAuthenticationTicket authTicket;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
string[] roles = authTicket.UserData.Split(';');
if (Context.User != null)
Context.User = new GenericPrincipal(Context.User.Identity, roles);
}

How to retrieve a stored cookie in mvc4?

This is the code I use to store a cookie after user is authenticated.
var authTicket = new FormsAuthenticationTicket(
1,
Session["UserID"].ToString(), //user id
DateTime.Now,
DateTime.Now.AddDays(1), // expiry
true, //true to remember
"", //roles
"/"
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
if (authTicket.IsPersistent) { cookie.Expires = authTicket.Expiration; }
Response.Cookies.Add(cookie);
What should I do next to retrieve this cookie when the user visits the site again ?
To get the cookie:
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
To get the ticket inside the cookie:
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
Typical way of doing it-- implement AuthenticateRequest in global.asax.cs...something like this....
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
// Get the forms authentication ticket.
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new MyPrincipal(identity);
// Get the custom user data encrypted in the ticket.
string userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;
// Deserialize the json data and set it on the custom principal.
var serializer = new JavaScriptSerializer();
principal.User = (User)serializer.Deserialize(userData, typeof(User));
// Set the context user.
Context.User = principal;
}
}
...then, whenever any of your code needs to access the current user, just get the context user:
var user = HttpContext.Current.User;
Link

Authentication via FormsAuthentication in asp mvc 4

I have simple web App (asp mvc 4) that take username and password and authenticate user via custom user provider.
In account controller i write this code:
public ActionResult Login(LoginViewModel model, string returnUrl = "")
{
if (ModelState.IsValid)
{
ImasUser user=null;
var x = ImasUserManagment.ImasMembershipProvider.GetImasUser(model.Username, model.Password);
if(x!=null)
user =new ImasUser(x);
if (user != null)
{
var roles = user.ImasRoles.Select(m => m.RoleName).ToArray();
ImasPrincipalSerializeModel serializeModel = new ImasPrincipalSerializeModel();
serializeModel.UserId = user.UserID;
serializeModel.FirstName = user.FirstName;
serializeModel.LastName = user.LastName;
serializeModel.UserName = user.UserName;
serializeModel.roles = roles;
string userData = JsonConvert.SerializeObject(serializeModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
user.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(15),
false,
userData, FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
faCookie.Expires = authTicket.Expiration;
Response.Cookies.Clear();
System.Web.HttpContext.Current.Response.Cookies.Add(faCookie);
System.Web.HttpContext.Current.Session.Add("UserInfo", userData);
if (roles.Contains("Admin"))
{
return RedirectToAction("Index", "Admin");
}
else if (roles.Contains("User"))
{
return RedirectToAction("Index", "User");
}
else
{
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "xxx");
}
And in global asax :
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie =System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
ImasPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject<ImasPrincipalSerializeModel>(authTicket.UserData);
ImasPrincipal newUser = new ImasPrincipal(authTicket.Name);
newUser.UserId = serializeModel.UserId;
newUser.FirstName = serializeModel.FirstName;
newUser.LastName = serializeModel.LastName;
newUser.roles = serializeModel.roles;
HttpContext.Current.User = newUser;
}
}
But "authCookie" is null in global.asax.
1) Better Use Session
2) Try:
FormsAuthentication.SetAuthCookie
and:
FormsAuthentication.GetAuthCookie

Roles for GenericPrincipal are being lost

I am attempting to set up roles on my dynamic data website, but am encountering an issue.
Between the time I set up by Generic Principal, and when the default page is hit the roles of my principal are lost. The principal is still listed as the context.user, for when I debug my session and inspect the context.user object the user I set up is the user I set up; but all roles related to that user seem to be lost.
This is how I am going about it.
Login page
public partial class Login : System.Web.UI.Page
{
string[] masterServiceResult;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsAuthenticUser(login_email.Text, login_password.Text))
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, masterServiceResult[0], DateTime.Now, DateTime.Now.AddMinutes(30), false, masterServiceResult[2], FormsAuthentication.FormsCookiePath);
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie);
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(masterServiceResult[0], true));
}
}
private bool IsAuthenticUser(string email, string password)
{
MembershipService membershipService = new MembershipService();
var result = membershipService.GetUserAndRoleFromCredentials(email, password);
//result is an array with userName, userId, error(bool) as string, and error message if any
if (bool.Parse(result[3]) == false)
{
masterServiceResult = result;
return true;
}
return false;
}
}
Then in Global.asax I have attached to the AuthenticateRequest event
void Global_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
SetupRoles();
}
private void SetupRoles()
{
if (Context.User != null)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (authCookie == null)
return;
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new char[] { '|' });
IIdentity fi = Context.User.Identity;
IPrincipal pi = new GenericPrincipal(fi, roles);
Context.User = pi;
//sets the application principal to use the logged on user account
System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;
// sanity check to ensure the role was set up.
if (User.IsInRole("Admin"))
{
int i = 0; // debug line
}
}
}
At this point everything is working as intended; my test account is now set as the context.user, the Current Principal user is set as the current user, and the users role of Admin is causing the "int i=0" debug line to be hit. However once the default page Page_Load is hit this is no longer the case.
Default page. Updated 01/03/12 to show another test case.
protected void Page_Load(object sender, EventArgs e)
{
System.Collections.IList visibleTables = MetaModel.Default.VisibleTables;
// this line comes back as false, though at this point the user name is the same.
if (User.IsInRole("Admin"))
{
int i = 0;
}
// the next 4 lines of code is a work around I can do to retrieve the roles from the ticket.
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
// this line of code will correctly show the users role
string[] roles = authTicket.UserData.Split(new char[] { '|' });
foreach (var table in MetaModel.Default.Tables)
{
var permissions = ((MetaTable)table).GetTablePermissions(roles);
if (permissions.Contains(TablePermissionsAttribute.Permissions.DenyRead))
visibleTables.Remove(table);
}
if (visibleTables.Count == 0)
{
throw new InvalidOperationException("There are no accessible tables. Make sure that at least one data model is registered in Global.asax and scaffolding is enabled or implement custom pages.");
}
Menu1.DataSource = visibleTables;
Menu1.DataBind();
}
*Updated: I am a able to get the roles for the user rom the authentication ticket, and the principal is correct, but I am baffled as to why the User.IsInRole line fails.

How to get the cookie value in asp.net website

I am creating a cookie and storing the value of username after succesfull login. How can I access the cookie when the website is opened. If the cookie exist I want to fill the username text box from the cookie value. And how to decrypt the value to get the username. I am doing server side validation by getting the userdetails from the database. I am using vs 2010 with c#
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddYears(1), chk_Rememberme.Checked, "User Email");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chk_Rememberme.Checked)
{
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
}
cookie is created with name as .YAFNET_Authentication and content is encrypted
Webconfig:
<forms name=".YAFNET_Authentication" loginUrl="Home.aspx"
protection="All" timeout="15000" cookieless="UseCookies"/>
You may use Request.Cookies collection to read the cookies.
if(Request.Cookies["key"]!=null)
{
var value=Request.Cookies["key"].Value;
}
FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
and decrypt that.
add this function to your global.asax
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (authCookie == null)
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
if (authTicket == null)
{
return;
}
string[] roles = authTicket.UserData.Split(new char[] { '|' });
FormsIdentity id = new FormsIdentity(authTicket);
GenericPrincipal principal = new GenericPrincipal(id, roles);
Context.User = principal;
}
then you can use HttpContext.Current.User.Identity.Name to get username. hope it helps
HttpCookie cook = new HttpCookie("testcook");
cook = Request.Cookies["CookName"];
if (cook != null)
{
lbl_cookie_value.Text = cook.Value;
}
else
{
lbl_cookie_value.Text = "Empty value";
}
Reference Click here

Categories