Is there a way to add claims in an ASP.NET Core middleware after Authentication?











up vote
2
down vote

favorite












I have this in my startup:



public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSwaggerWithUi();

app.UseAuthentication();
app.UseMiddleware<SomeMiddleware>();

app.UseMvc();
}


I need to add some additional claims AFTER the user is authenticated, but the middleware Invoke function always fires before Auth (HttpContext.User.Identity.IsAuthenticated is false). But when it hits the controller the user is authenticated fine.



Any idea what to do here? I've tried to put "app.UseAuthentication()" after calling app.UseMiddleware but it has no affect.



I'm currently using multiple Authentication schemes. I'm not sure if that has an affect.










share|improve this question




























    up vote
    2
    down vote

    favorite












    I have this in my startup:



    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    else
    {
    app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSwaggerWithUi();

    app.UseAuthentication();
    app.UseMiddleware<SomeMiddleware>();

    app.UseMvc();
    }


    I need to add some additional claims AFTER the user is authenticated, but the middleware Invoke function always fires before Auth (HttpContext.User.Identity.IsAuthenticated is false). But when it hits the controller the user is authenticated fine.



    Any idea what to do here? I've tried to put "app.UseAuthentication()" after calling app.UseMiddleware but it has no affect.



    I'm currently using multiple Authentication schemes. I'm not sure if that has an affect.










    share|improve this question


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I have this in my startup:



      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
      if (env.IsDevelopment())
      {
      app.UseDeveloperExceptionPage();
      }
      else
      {
      app.UseHsts();
      }

      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseSwaggerWithUi();

      app.UseAuthentication();
      app.UseMiddleware<SomeMiddleware>();

      app.UseMvc();
      }


      I need to add some additional claims AFTER the user is authenticated, but the middleware Invoke function always fires before Auth (HttpContext.User.Identity.IsAuthenticated is false). But when it hits the controller the user is authenticated fine.



      Any idea what to do here? I've tried to put "app.UseAuthentication()" after calling app.UseMiddleware but it has no affect.



      I'm currently using multiple Authentication schemes. I'm not sure if that has an affect.










      share|improve this question















      I have this in my startup:



      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
      if (env.IsDevelopment())
      {
      app.UseDeveloperExceptionPage();
      }
      else
      {
      app.UseHsts();
      }

      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseSwaggerWithUi();

      app.UseAuthentication();
      app.UseMiddleware<SomeMiddleware>();

      app.UseMvc();
      }


      I need to add some additional claims AFTER the user is authenticated, but the middleware Invoke function always fires before Auth (HttpContext.User.Identity.IsAuthenticated is false). But when it hits the controller the user is authenticated fine.



      Any idea what to do here? I've tried to put "app.UseAuthentication()" after calling app.UseMiddleware but it has no affect.



      I'm currently using multiple Authentication schemes. I'm not sure if that has an affect.







      c# asp.net-core






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 at 8:20









      Panagiotis Kanavos

      52.7k479107




      52.7k479107










      asked Nov 14 at 2:21









      Yodacheese

      2,4271932




      2,4271932
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote













          You can add another middleware immediately after the UseAuthentication() to add claims :



          app.UseAuthentication();
          app.Use(async(context, next)=>{
          if(context.User !=null && context.User.Identity.IsAuthenticated){
          // add claims here
          context.User.Claims.Append(new Claim("type-x","value-x"));
          }
          await next();
          });

          // call other middlewares
          app.UseMiddleware<SomeMiddleware>();





          share|improve this answer





















          • Tried this, no good. This works only if I have a default auth scheme.
            – Yodacheese
            Nov 18 at 21:15












          • @Yodacheese As far as I know, the AuthenticationMiddleware is invoked for every request. And the claims will be added just after the authentication and before any other middlewares . It doesn't care whether there's a default scheme or not. Could you please elaborate on This works only if I have a default auth scheme ?
            – itminus
            Nov 19 at 4:25




















          up vote
          0
          down vote













          It depends on what do you want to do and which scheme you use.



          For example, if you use JwtBearer then you could utilize JwtBearerOptions.Events to handle particular events raised by the middleware. You need to set that in your ConfigureServices method of Startup class.



          That would give you more granular control of what precise case you want to have your Claims added to, for example, OnTokenValidated.






          share|improve this answer





















          • This is fine but a bit tedious. I have multiple schemes so JWT is just one, then I need to add the even on the custom auth scheme, at the same time I still want to use dependency injection so I have to resolve it.
            – Yodacheese
            Nov 18 at 21:17











          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',
          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%2f53292286%2fis-there-a-way-to-add-claims-in-an-asp-net-core-middleware-after-authentication%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote













          You can add another middleware immediately after the UseAuthentication() to add claims :



          app.UseAuthentication();
          app.Use(async(context, next)=>{
          if(context.User !=null && context.User.Identity.IsAuthenticated){
          // add claims here
          context.User.Claims.Append(new Claim("type-x","value-x"));
          }
          await next();
          });

          // call other middlewares
          app.UseMiddleware<SomeMiddleware>();





          share|improve this answer





















          • Tried this, no good. This works only if I have a default auth scheme.
            – Yodacheese
            Nov 18 at 21:15












          • @Yodacheese As far as I know, the AuthenticationMiddleware is invoked for every request. And the claims will be added just after the authentication and before any other middlewares . It doesn't care whether there's a default scheme or not. Could you please elaborate on This works only if I have a default auth scheme ?
            – itminus
            Nov 19 at 4:25

















          up vote
          0
          down vote













          You can add another middleware immediately after the UseAuthentication() to add claims :



          app.UseAuthentication();
          app.Use(async(context, next)=>{
          if(context.User !=null && context.User.Identity.IsAuthenticated){
          // add claims here
          context.User.Claims.Append(new Claim("type-x","value-x"));
          }
          await next();
          });

          // call other middlewares
          app.UseMiddleware<SomeMiddleware>();





          share|improve this answer





















          • Tried this, no good. This works only if I have a default auth scheme.
            – Yodacheese
            Nov 18 at 21:15












          • @Yodacheese As far as I know, the AuthenticationMiddleware is invoked for every request. And the claims will be added just after the authentication and before any other middlewares . It doesn't care whether there's a default scheme or not. Could you please elaborate on This works only if I have a default auth scheme ?
            – itminus
            Nov 19 at 4:25















          up vote
          0
          down vote










          up vote
          0
          down vote









          You can add another middleware immediately after the UseAuthentication() to add claims :



          app.UseAuthentication();
          app.Use(async(context, next)=>{
          if(context.User !=null && context.User.Identity.IsAuthenticated){
          // add claims here
          context.User.Claims.Append(new Claim("type-x","value-x"));
          }
          await next();
          });

          // call other middlewares
          app.UseMiddleware<SomeMiddleware>();





          share|improve this answer












          You can add another middleware immediately after the UseAuthentication() to add claims :



          app.UseAuthentication();
          app.Use(async(context, next)=>{
          if(context.User !=null && context.User.Identity.IsAuthenticated){
          // add claims here
          context.User.Claims.Append(new Claim("type-x","value-x"));
          }
          await next();
          });

          // call other middlewares
          app.UseMiddleware<SomeMiddleware>();






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 14 at 4:52









          itminus

          2,5261319




          2,5261319












          • Tried this, no good. This works only if I have a default auth scheme.
            – Yodacheese
            Nov 18 at 21:15












          • @Yodacheese As far as I know, the AuthenticationMiddleware is invoked for every request. And the claims will be added just after the authentication and before any other middlewares . It doesn't care whether there's a default scheme or not. Could you please elaborate on This works only if I have a default auth scheme ?
            – itminus
            Nov 19 at 4:25




















          • Tried this, no good. This works only if I have a default auth scheme.
            – Yodacheese
            Nov 18 at 21:15












          • @Yodacheese As far as I know, the AuthenticationMiddleware is invoked for every request. And the claims will be added just after the authentication and before any other middlewares . It doesn't care whether there's a default scheme or not. Could you please elaborate on This works only if I have a default auth scheme ?
            – itminus
            Nov 19 at 4:25


















          Tried this, no good. This works only if I have a default auth scheme.
          – Yodacheese
          Nov 18 at 21:15






          Tried this, no good. This works only if I have a default auth scheme.
          – Yodacheese
          Nov 18 at 21:15














          @Yodacheese As far as I know, the AuthenticationMiddleware is invoked for every request. And the claims will be added just after the authentication and before any other middlewares . It doesn't care whether there's a default scheme or not. Could you please elaborate on This works only if I have a default auth scheme ?
          – itminus
          Nov 19 at 4:25






          @Yodacheese As far as I know, the AuthenticationMiddleware is invoked for every request. And the claims will be added just after the authentication and before any other middlewares . It doesn't care whether there's a default scheme or not. Could you please elaborate on This works only if I have a default auth scheme ?
          – itminus
          Nov 19 at 4:25














          up vote
          0
          down vote













          It depends on what do you want to do and which scheme you use.



          For example, if you use JwtBearer then you could utilize JwtBearerOptions.Events to handle particular events raised by the middleware. You need to set that in your ConfigureServices method of Startup class.



          That would give you more granular control of what precise case you want to have your Claims added to, for example, OnTokenValidated.






          share|improve this answer





















          • This is fine but a bit tedious. I have multiple schemes so JWT is just one, then I need to add the even on the custom auth scheme, at the same time I still want to use dependency injection so I have to resolve it.
            – Yodacheese
            Nov 18 at 21:17















          up vote
          0
          down vote













          It depends on what do you want to do and which scheme you use.



          For example, if you use JwtBearer then you could utilize JwtBearerOptions.Events to handle particular events raised by the middleware. You need to set that in your ConfigureServices method of Startup class.



          That would give you more granular control of what precise case you want to have your Claims added to, for example, OnTokenValidated.






          share|improve this answer





















          • This is fine but a bit tedious. I have multiple schemes so JWT is just one, then I need to add the even on the custom auth scheme, at the same time I still want to use dependency injection so I have to resolve it.
            – Yodacheese
            Nov 18 at 21:17













          up vote
          0
          down vote










          up vote
          0
          down vote









          It depends on what do you want to do and which scheme you use.



          For example, if you use JwtBearer then you could utilize JwtBearerOptions.Events to handle particular events raised by the middleware. You need to set that in your ConfigureServices method of Startup class.



          That would give you more granular control of what precise case you want to have your Claims added to, for example, OnTokenValidated.






          share|improve this answer












          It depends on what do you want to do and which scheme you use.



          For example, if you use JwtBearer then you could utilize JwtBearerOptions.Events to handle particular events raised by the middleware. You need to set that in your ConfigureServices method of Startup class.



          That would give you more granular control of what precise case you want to have your Claims added to, for example, OnTokenValidated.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 14 at 5:27









          dee zg

          4,30831329




          4,30831329












          • This is fine but a bit tedious. I have multiple schemes so JWT is just one, then I need to add the even on the custom auth scheme, at the same time I still want to use dependency injection so I have to resolve it.
            – Yodacheese
            Nov 18 at 21:17


















          • This is fine but a bit tedious. I have multiple schemes so JWT is just one, then I need to add the even on the custom auth scheme, at the same time I still want to use dependency injection so I have to resolve it.
            – Yodacheese
            Nov 18 at 21:17
















          This is fine but a bit tedious. I have multiple schemes so JWT is just one, then I need to add the even on the custom auth scheme, at the same time I still want to use dependency injection so I have to resolve it.
          – Yodacheese
          Nov 18 at 21:17




          This is fine but a bit tedious. I have multiple schemes so JWT is just one, then I need to add the even on the custom auth scheme, at the same time I still want to use dependency injection so I have to resolve it.
          – Yodacheese
          Nov 18 at 21:17


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53292286%2fis-there-a-way-to-add-claims-in-an-asp-net-core-middleware-after-authentication%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

          How to send String Array data to Server using php in android

          Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

          Is anime1.com a legal site for watching anime?