I reading this documentation trying to find where should I replace a connection string or something related to database management to override in my CustomAuthorize
attribute to get the following behavior:
public override bool AuthorizeCore(HttpContextBase httpContext)
{
//Check if the actual user is in the roles provided
if(user.HasRole(Roles))
{
true;
}
else
{
false;
}
}
What I don't know :
Users
and Roles
table to work with? First authenticate the user and create an authenticated cookie for their session, something like this:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.Email, DateTime.Now, DateTime.Now.AddDays(1), false, model.Email);
string hashedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket);
HttpContext.Response.Cookies.Add(cookie);
Next step, when the application tries to authenticate:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var user = this.UserService.GetUserByEmail(authTicket.Name);
var identity = new GenericIdentity(authTicket.Name, "Forms");
// Get the stored user roles
HttpContext.Current.User = new GenericPrincipal(identity, user.Roles);
}
}
Then you should be able to use:
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.User.IsInRole("admin"))
{
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.