0
votes

I have an .net core 2.2 api which generates (on a successful login) a JWT token which contains a claims identity that passes along information such as the username, permissions and roles of the authenticated user.

In my .net core 2.2. web app I have a login mechanism which retrieves the JWT token via the user of a controller.

My question is.

How can I expand the token from within my login controller and set up my web app to include the use of the authentication mechanisms like User.Identity.IsAuthenticated, User.IsInRole("Admin") and controller actions like [Authorize] and [Authorize(Roles="Admin")]

I've been directed towards looking at the source code behind external authentication providers such as facebook/google but to no avail.

Thanks in advance.

1
Did you already managed to get your IdentityUser from your JWT in an authentication middleware ? Are you only looking for how to handle authorization in your controllers ?Skrface
This is what i'm after. So would you recommend introducing some authentication middleware in my startup class to create the identity user? In addition to authorizing the user on controllers, I need the User.Identity.IsAuthenticated and User.IsInRole("Admin") variables setup to alter my UI depending on the user. @Skrfacecwiggo
hi..are you using identityserver4 or what kind of technologies?federico scamuzzi
@federicoscamuzzi i'm simply trying to use cookieauthentication, claimsidentity and jwtcwiggo

1 Answers

3
votes

First step is to use cookie authentication in Startup.cs :

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

In the Configure method, use the UseAuthentication method to invoke the Authentication Middleware that sets the HttpContext.User property. Call the UseAuthentication method before calling UseMvcWithDefaultRoute or UseMvc:

app.UseAuthentication();

Then in your auth controller , after getting token and decode to get the claims , you should create new ClaimsIdentity , add your claims and sign-in user :

if (!User.Identity.IsAuthenticated)
{
    var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, YourName));
    identity.AddClaim(new Claim(ClaimTypes.Name, YourName));
    identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

    //Add your custom claims

    var principal = new ClaimsPrincipal(identity);
    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });

}

After that , you can useUser.Identity.IsAuthenticated, User.IsInRole("Admin") and [Authorize(Roles="Admin")]:

[Authorize(Roles = "Admin")]
public IActionResult About()
{
    var result = User.IsInRole("Admin");
    return View();
}