ASP.NET Core 2.1 Jwt setting custom claims

2019-08-25 02:45发布

问题:

I have this code that is supposed to set claims for a user. It works fine when I use identity and the default login. However, when I use jwt as authentication in another application, I don't have ApplicationUser as my ApplicationUser is stored in the other application that authenticates the user. How can I customize this code so that it works with jwt?

private readonly SignInManager<TIdentityUser> _signInManager;

public CustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager)
{
    _signInManager = signInManager;
}

public async Task SignInUserAsync(TIdentityUser user, bool isPersistent, IEnumerable<Claim> customClaims)
{
    var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
    var identity = claimsPrincipal.Identity as ClaimsIdentity;
    var claims = (from c in claimsPrincipal.Claims select c).ToList();
    var savedClaims = claims;
    if (customClaims != null)
    {
        identity.AddClaims(customClaims);
    }
    await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme,
        claimsPrincipal,
        new AuthenticationProperties { IsPersistent = isPersistent });
}

I guess my main intention is to set my users claims in the httpcontext and not in a cookie and I want to do that without using identity.

EDIT:

My application structure

AuthenticationApp (server)

  • Responsible for authenticating users
  • Generates and Decodes Jwt
  • Checks if the user has the appropriate roles and returns true/false via rest api

MainApp (client)

  • Makes an api call to AuthenticationApp
  • Does not use identity at all
  • Sends Jwt everytime I need to check the role of the user

I understand that I will be able to decode the jwt client side. However, I do not know where I can store the decoded jwt details so that I can use it in the view. My initial idea was to use Httpcontext like normal applications that user Identity. However, I am stuck with the code above.

回答1:

For sharing the Identity information between Controller and View, you could sign the User information by HttpContext.SignInAsync.

Try steps below to achieve your requirement:

  • Controller Action

        public async Task<IActionResult> Index()
    {
        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "edward"));
        identity.AddClaim(new Claim(ClaimTypes.Name, "edward zhou"));
        //add your own claims from jwt token
        var principal = new ClaimsPrincipal(identity);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });            
        return View();
    }
    
  • View

    @foreach (var item in Context.User.Claims)
    {
       <p>@item.Value</p> 
    };
    
  • To make above code work, register Authentication in Startup.cs

    public class Startup
    {
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    
    public IConfiguration Configuration { get; }
    
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {   
         //your rest code     
    
    
         services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
    }
    
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //your rest code
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    

    }