ASP.NET Core 2.1 Jwt setting custom claims










0















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.










share|improve this question



















  • 1





    Possible duplicate of ASP.NET Core Jwt implement signinmanager claims

    – Tao Zhou
    Nov 13 '18 at 6:37











  • It’s different. I’m trying to see if there’s an alternate way to set httpcontext items

    – JianYA
    Nov 13 '18 at 6:51















0















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.










share|improve this question



















  • 1





    Possible duplicate of ASP.NET Core Jwt implement signinmanager claims

    – Tao Zhou
    Nov 13 '18 at 6:37











  • It’s different. I’m trying to see if there’s an alternate way to set httpcontext items

    – JianYA
    Nov 13 '18 at 6:51













0












0








0








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.










share|improve this question
















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.







asp.net asp.net-mvc asp.net-core jwt






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 13:10







JianYA

















asked Nov 13 '18 at 3:33









JianYAJianYA

6541125




6541125







  • 1





    Possible duplicate of ASP.NET Core Jwt implement signinmanager claims

    – Tao Zhou
    Nov 13 '18 at 6:37











  • It’s different. I’m trying to see if there’s an alternate way to set httpcontext items

    – JianYA
    Nov 13 '18 at 6:51












  • 1





    Possible duplicate of ASP.NET Core Jwt implement signinmanager claims

    – Tao Zhou
    Nov 13 '18 at 6:37











  • It’s different. I’m trying to see if there’s an alternate way to set httpcontext items

    – JianYA
    Nov 13 '18 at 6:51







1




1





Possible duplicate of ASP.NET Core Jwt implement signinmanager claims

– Tao Zhou
Nov 13 '18 at 6:37





Possible duplicate of ASP.NET Core Jwt implement signinmanager claims

– Tao Zhou
Nov 13 '18 at 6:37













It’s different. I’m trying to see if there’s an alternate way to set httpcontext items

– JianYA
Nov 13 '18 at 6:51





It’s different. I’m trying to see if there’s an alternate way to set httpcontext items

– JianYA
Nov 13 '18 at 6:51












1 Answer
1






active

oldest

votes


















0














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?");
    );









share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53273404%2fasp-net-core-2-1-jwt-setting-custom-claims%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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?");
      );









    share|improve this answer



























      0














      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?");
        );









      share|improve this answer

























        0












        0








        0







        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?");
          );









        share|improve this answer













        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?");
          );










        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 5:18









        Tao ZhouTao Zhou

        5,85131230




        5,85131230



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53273404%2fasp-net-core-2-1-jwt-setting-custom-claims%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo