How to set some user data when token generate using web api bearer token base authenticationHow to secure an ASP.NET Web APISignalR authentication failed when passing “Bearer” through query stringHow is the User property generated when authenticating with bearer tokens in Web Api?Return user roles from bearer token of Web APIHow do you generate a Bearer token to call a remote Web APIClaimsAuthorizationManager's CheckAccess() method invoked 3 timesSignalR + Web Api 2 Bearer Token AuthenticationForward Bearer Token IdentityServer Web-APIUnable to authenticate web api with Bearer TokenC#/OWIN/ASP.NET: can I *manually* generate and get a valid bearer token string in my API code?

Are Captain Marvel's powers affected by Thanos breaking the Tesseract and claiming the stone?

Why does this expression simplify as such?

15% tax on $7.5k earnings. Is that right?

How to preserve electronics (computers, iPads and phones) for hundreds of years

Does Doodling or Improvising on the Piano Have Any Benefits?

Do we have to expect a queue for the shuttle from Watford Junction to Harry Potter Studio?

It grows, but water kills it

Why is the "ls" command showing permissions of files in a FAT32 partition?

How do I fix the group tension caused by my character stealing and possibly killing without provocation?

Can a stoichiometric mixture of oxygen and methane exist as a liquid at standard pressure and some (low) temperature?

When were female captains banned from Starfleet?

How does electrical safety system work on ISS?

The IT department bottlenecks progress, how should I handle this?

What fields between the rationals and the reals allow a good notion of 2D distance?

Why is the Sun approximated as a black body at ~ 5800 K?

Why is so much work done on numerical verification of the Riemann Hypothesis?

Stack Interview Code methods made from class Node and Smart Pointers

Which was the first story featuring espers?

How much theory knowledge is actually used while playing?

Creating two special characters

Taxes on Dividends in a Roth IRA

What kind of floor tile is this?

Can you use Vicious Mockery to win an argument or gain favours?

Mimic lecturing on blackboard, facing audience



How to set some user data when token generate using web api bearer token base authentication


How to secure an ASP.NET Web APISignalR authentication failed when passing “Bearer” through query stringHow is the User property generated when authenticating with bearer tokens in Web Api?Return user roles from bearer token of Web APIHow do you generate a Bearer token to call a remote Web APIClaimsAuthorizationManager's CheckAccess() method invoked 3 timesSignalR + Web Api 2 Bearer Token AuthenticationForward Bearer Token IdentityServer Web-APIUnable to authenticate web api with Bearer TokenC#/OWIN/ASP.NET: can I *manually* generate and get a valid bearer token string in my API code?













0















When token generate with flowing my own condition at that time I want to fetch some data of login user.



I'm already done access token generate



Here is my Startup class:



 public class Startup

public void Configuration(IAppBuilder app)

// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
app.UseCors(CorsOptions.AllowAll);
var myProvider = new MyAuthorizationServerProvider();
OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions

AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = myProvider
;
app.UseOAuthAuthorizationServer(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);






MyAuthorizationServerProvider class



public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider

private readonly ReviewDbContext db;
public MyAuthorizationServerProvider()

db = new ReviewDbContext();

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)

context.Validated();

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

var user = db.Reviewers.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
var admin = db.Admins.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
if (admin != null && user == null)

identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
identity.AddClaim(new Claim("UserName", admin.Name));
identity.AddClaim(new Claim(ClaimTypes.Name, "Admin Ahasanul Banna"));
context.Validated(identity);

else if (user != null)

identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
identity.AddClaim(new Claim("UserName", user.Name));
identity.AddClaim(new Claim(ClaimTypes.Name, "User Ahasanul Banna"));
context.Validated(identity);

else

context.SetError("Invalid_grant", "Provided username & password is incorrect");
return;





AuthorizeAttribute class



public class AuthorizeAttribute :System.Web.Http.AuthorizeAttribute

protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)

if (!HttpContext.Current.User.Identity.IsAuthenticated)

base.HandleUnauthorizedRequest(actionContext);

else

actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);






Postmanenter image description here
My expected output like as: enter image description here
Where I set user data which I want with user generate token.
How to achieve this?










share|improve this question


























    0















    When token generate with flowing my own condition at that time I want to fetch some data of login user.



    I'm already done access token generate



    Here is my Startup class:



     public class Startup

    public void Configuration(IAppBuilder app)

    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
    app.UseCors(CorsOptions.AllowAll);
    var myProvider = new MyAuthorizationServerProvider();
    OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions

    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
    Provider = myProvider
    ;
    app.UseOAuthAuthorizationServer(options);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    HttpConfiguration config = new HttpConfiguration();
    WebApiConfig.Register(config);






    MyAuthorizationServerProvider class



    public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider

    private readonly ReviewDbContext db;
    public MyAuthorizationServerProvider()

    db = new ReviewDbContext();

    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)

    context.Validated();

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

    var user = db.Reviewers.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
    var admin = db.Admins.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    if (admin != null && user == null)

    identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
    identity.AddClaim(new Claim("UserName", admin.Name));
    identity.AddClaim(new Claim(ClaimTypes.Name, "Admin Ahasanul Banna"));
    context.Validated(identity);

    else if (user != null)

    identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
    identity.AddClaim(new Claim("UserName", user.Name));
    identity.AddClaim(new Claim(ClaimTypes.Name, "User Ahasanul Banna"));
    context.Validated(identity);

    else

    context.SetError("Invalid_grant", "Provided username & password is incorrect");
    return;





    AuthorizeAttribute class



    public class AuthorizeAttribute :System.Web.Http.AuthorizeAttribute

    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)

    if (!HttpContext.Current.User.Identity.IsAuthenticated)

    base.HandleUnauthorizedRequest(actionContext);

    else

    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);






    Postmanenter image description here
    My expected output like as: enter image description here
    Where I set user data which I want with user generate token.
    How to achieve this?










    share|improve this question
























      0












      0








      0








      When token generate with flowing my own condition at that time I want to fetch some data of login user.



      I'm already done access token generate



      Here is my Startup class:



       public class Startup

      public void Configuration(IAppBuilder app)

      // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
      app.UseCors(CorsOptions.AllowAll);
      var myProvider = new MyAuthorizationServerProvider();
      OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions

      AllowInsecureHttp = true,
      TokenEndpointPath = new PathString("/token"),
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
      Provider = myProvider
      ;
      app.UseOAuthAuthorizationServer(options);
      app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
      HttpConfiguration config = new HttpConfiguration();
      WebApiConfig.Register(config);






      MyAuthorizationServerProvider class



      public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider

      private readonly ReviewDbContext db;
      public MyAuthorizationServerProvider()

      db = new ReviewDbContext();

      public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)

      context.Validated();

      public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

      var user = db.Reviewers.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
      var admin = db.Admins.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
      var identity = new ClaimsIdentity(context.Options.AuthenticationType);
      if (admin != null && user == null)

      identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
      identity.AddClaim(new Claim("UserName", admin.Name));
      identity.AddClaim(new Claim(ClaimTypes.Name, "Admin Ahasanul Banna"));
      context.Validated(identity);

      else if (user != null)

      identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
      identity.AddClaim(new Claim("UserName", user.Name));
      identity.AddClaim(new Claim(ClaimTypes.Name, "User Ahasanul Banna"));
      context.Validated(identity);

      else

      context.SetError("Invalid_grant", "Provided username & password is incorrect");
      return;





      AuthorizeAttribute class



      public class AuthorizeAttribute :System.Web.Http.AuthorizeAttribute

      protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)

      if (!HttpContext.Current.User.Identity.IsAuthenticated)

      base.HandleUnauthorizedRequest(actionContext);

      else

      actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);






      Postmanenter image description here
      My expected output like as: enter image description here
      Where I set user data which I want with user generate token.
      How to achieve this?










      share|improve this question














      When token generate with flowing my own condition at that time I want to fetch some data of login user.



      I'm already done access token generate



      Here is my Startup class:



       public class Startup

      public void Configuration(IAppBuilder app)

      // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
      app.UseCors(CorsOptions.AllowAll);
      var myProvider = new MyAuthorizationServerProvider();
      OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions

      AllowInsecureHttp = true,
      TokenEndpointPath = new PathString("/token"),
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
      Provider = myProvider
      ;
      app.UseOAuthAuthorizationServer(options);
      app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
      HttpConfiguration config = new HttpConfiguration();
      WebApiConfig.Register(config);






      MyAuthorizationServerProvider class



      public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider

      private readonly ReviewDbContext db;
      public MyAuthorizationServerProvider()

      db = new ReviewDbContext();

      public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)

      context.Validated();

      public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

      var user = db.Reviewers.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
      var admin = db.Admins.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
      var identity = new ClaimsIdentity(context.Options.AuthenticationType);
      if (admin != null && user == null)

      identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
      identity.AddClaim(new Claim("UserName", admin.Name));
      identity.AddClaim(new Claim(ClaimTypes.Name, "Admin Ahasanul Banna"));
      context.Validated(identity);

      else if (user != null)

      identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
      identity.AddClaim(new Claim("UserName", user.Name));
      identity.AddClaim(new Claim(ClaimTypes.Name, "User Ahasanul Banna"));
      context.Validated(identity);

      else

      context.SetError("Invalid_grant", "Provided username & password is incorrect");
      return;





      AuthorizeAttribute class



      public class AuthorizeAttribute :System.Web.Http.AuthorizeAttribute

      protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)

      if (!HttpContext.Current.User.Identity.IsAuthenticated)

      base.HandleUnauthorizedRequest(actionContext);

      else

      actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);






      Postmanenter image description here
      My expected output like as: enter image description here
      Where I set user data which I want with user generate token.
      How to achieve this?







      c# asp.net-web-api2 bearer-token






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 7 at 4:54









      Ahasanul BannaAhasanul Banna

      297




      297






















          1 Answer
          1






          active

          oldest

          votes


















          1














          You are adding claims to your token so in order to access them you need to decode the token. However, if you want your extra data to be outside the token (like the image you have painted), you can add them as different properties to the login response object:



           var props = new AuthenticationProperties(new Dictionary<string, string>


          "UserName", "AA"
          ,

          "UserId" , "1"

          );
          var ticket = new AuthenticationTicket(identity, props);
          context.Validated(ticket);


          Also, you need to add the following method to MyAuthorizationServerProvider :



           public override Task TokenEndpoint(OAuthTokenEndpointContext context)

          foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)

          context.AdditionalResponseParameters.Add(property.Key, property.Value);

          return Task.FromResult<object>(null);






          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%2f55036347%2fhow-to-set-some-user-data-when-token-generate-using-web-api-bearer-token-base-au%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









            1














            You are adding claims to your token so in order to access them you need to decode the token. However, if you want your extra data to be outside the token (like the image you have painted), you can add them as different properties to the login response object:



             var props = new AuthenticationProperties(new Dictionary<string, string>


            "UserName", "AA"
            ,

            "UserId" , "1"

            );
            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);


            Also, you need to add the following method to MyAuthorizationServerProvider :



             public override Task TokenEndpoint(OAuthTokenEndpointContext context)

            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)

            context.AdditionalResponseParameters.Add(property.Key, property.Value);

            return Task.FromResult<object>(null);






            share|improve this answer





























              1














              You are adding claims to your token so in order to access them you need to decode the token. However, if you want your extra data to be outside the token (like the image you have painted), you can add them as different properties to the login response object:



               var props = new AuthenticationProperties(new Dictionary<string, string>


              "UserName", "AA"
              ,

              "UserId" , "1"

              );
              var ticket = new AuthenticationTicket(identity, props);
              context.Validated(ticket);


              Also, you need to add the following method to MyAuthorizationServerProvider :



               public override Task TokenEndpoint(OAuthTokenEndpointContext context)

              foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)

              context.AdditionalResponseParameters.Add(property.Key, property.Value);

              return Task.FromResult<object>(null);






              share|improve this answer



























                1












                1








                1







                You are adding claims to your token so in order to access them you need to decode the token. However, if you want your extra data to be outside the token (like the image you have painted), you can add them as different properties to the login response object:



                 var props = new AuthenticationProperties(new Dictionary<string, string>


                "UserName", "AA"
                ,

                "UserId" , "1"

                );
                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);


                Also, you need to add the following method to MyAuthorizationServerProvider :



                 public override Task TokenEndpoint(OAuthTokenEndpointContext context)

                foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)

                context.AdditionalResponseParameters.Add(property.Key, property.Value);

                return Task.FromResult<object>(null);






                share|improve this answer















                You are adding claims to your token so in order to access them you need to decode the token. However, if you want your extra data to be outside the token (like the image you have painted), you can add them as different properties to the login response object:



                 var props = new AuthenticationProperties(new Dictionary<string, string>


                "UserName", "AA"
                ,

                "UserId" , "1"

                );
                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);


                Also, you need to add the following method to MyAuthorizationServerProvider :



                 public override Task TokenEndpoint(OAuthTokenEndpointContext context)

                foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)

                context.AdditionalResponseParameters.Add(property.Key, property.Value);

                return Task.FromResult<object>(null);







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 7 at 5:38

























                answered Mar 7 at 5:19









                radrad

                1,382814




                1,382814





























                    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%2f55036347%2fhow-to-set-some-user-data-when-token-generate-using-web-api-bearer-token-base-au%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

                    1928 у кіно

                    Захаров Федір Захарович

                    Ель Греко