I am creating an Asp.NET MVC 5 application. For this project, I am trying to implement a custom authentication mechanism (i don't want to use Forms Authentication / OWIN etc. external providers)
I created a custom authorize attribute as follows:
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class myAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!HttpContext.Current.Request.IsAuthenticated)
{
httpContext.Response.Redirect("~/Account/Login");
}
return base.AuthorizeCore(httpContext);
}
}
And in my Login action, I am trying to change the value of
HttpContext.User.Identity.IsAuthenticated
But it is read only and I am unable to change the value. Can I change its value manually or am I making a logical mistake.
You can achieve this by manually settings HttpContext.User:
var identity = new ClaimsIdentity("Custom");
HttpContext.User = new ClaimsPrincipal(identity);
It's important to set a custom authenticationType
. In the example above, I just used the string "Custom", but it can be anything you want.
With that, HttpContext.User.Identity.IsAuthenticated
will be true
.
For something more complicated, you can add claims like this:
var identity = new ClaimsIdentity(new List<Claim>
{
new Claim("UserId", "123", ClaimValueTypes.Integer32)
}, "Custom");
HttpContext.User = new ClaimsPrincipal(identity);
This results in:
HttpContext.User.Identity.IsAuthenticated == true;
int.Parse(((ClaimsIdentity)HttpContext.User.Identity).ValueFromType("UserId")) == 123;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With