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












2















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





























    2















    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



























      2












      2








      2








      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 '18 at 8:20









      Panagiotis Kanavos

      54.7k481108




      54.7k481108










      asked Nov 14 '18 at 2:21









      YodacheeseYodacheese

      2,4771932




      2,4771932
























          2 Answers
          2






          active

          oldest

          votes


















          0














          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 '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 '18 at 4:25





















          0














          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 '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',
          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%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









          0














          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 '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 '18 at 4:25


















          0














          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 '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 '18 at 4:25
















          0












          0








          0







          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 '18 at 4:52









          itminusitminus

          3,4861321




          3,4861321













          • Tried this, no good. This works only if I have a default auth scheme.

            – Yodacheese
            Nov 18 '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 '18 at 4:25





















          • Tried this, no good. This works only if I have a default auth scheme.

            – Yodacheese
            Nov 18 '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 '18 at 4:25



















          Tried this, no good. This works only if I have a default auth scheme.

          – Yodacheese
          Nov 18 '18 at 21:15







          Tried this, no good. This works only if I have a default auth scheme.

          – Yodacheese
          Nov 18 '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 '18 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 '18 at 4:25















          0














          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 '18 at 21:17
















          0














          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 '18 at 21:17














          0












          0








          0







          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 '18 at 5:27









          dee zgdee zg

          4,60631434




          4,60631434













          • 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 '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 '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 '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 '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.




          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

          The Sandy Post

          Danny Elfman

          Pages that link to "Head v. Amoskeag Manufacturing Co."