Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually set value of HttpContext.User.Identity.IsAuthenticated

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.

like image 341
emumcu Avatar asked Mar 12 '19 12:03

emumcu


1 Answers

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;
like image 83
Johnny Oshika Avatar answered Sep 25 '22 02:09

Johnny Oshika