How can I get a role from IdentityServer4 authorization?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How do I update the GUI from another thread?How can I get the application's path in a .NET console application?Get int value from enum in C#How can I get Id of inserted entity in Entity framework?Getting access token claims in claims principal in IdentityServer4Invalid Signature Key IdentityServer4How can I add AspNetIdentity to my API with IdentityServer4How to do Role-based Web API Authorization using Identity Server 4 (JWT)UnauthorizedAccessException consuming an API that requires access token

What was the point of separating stdout and stderr?

Active wildlife outside the window- Good or Bad for Cat psychology?

What is the meaning of "it" in "as luck would have it"?

How useful would a hydroelectric power plant be in the post-apocalypse world?

"in 60 seconds or less" or "in 60 seconds or fewer"?

Tricolour nonogram

How can this fractal shape perfectly cover a certain platonic solid?

How do I tell my girlfriend she's been buying me books by the wrong author for the last nine months?

Chandra exiles a card, I play it, it gets exiled again

Having to constantly redo everything because I don't know how to do it

How much of a mortgage should I take on to maximize my 5 year financial plan?

Does a lens with a bigger max. aperture focus faster than a lens with a smaller max. aperture?

What happens if a caster is surprised while casting a spell with a long casting time?

Is this house-rule removing the increased effect of cantrips at higher character levels balanced?

What would you need merely the term "collection" for pitches, but not "scale"?

Can I hire several veteran soldiers to accompany me?

How is it possible for tall trees to pull water to heights more than 10m?

Why will we fail creating a self sustaining off world colony?

"nunca" placement after a verb with "no"

What does 'in attendance' mean on an England death certificate?

Does an NPC know when a character has passed the save for Truth Serum?

Why should I allow multiple IP addresses on a website for a single session?

Why doesn't SpaceX land boosters in Africa?

Advantages of using bra-ket notation



How can I get a role from IdentityServer4 authorization?


How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How do I update the GUI from another thread?How can I get the application's path in a .NET console application?Get int value from enum in C#How can I get Id of inserted entity in Entity framework?Getting access token claims in claims principal in IdentityServer4Invalid Signature Key IdentityServer4How can I add AspNetIdentity to my API with IdentityServer4How to do Role-based Web API Authorization using Identity Server 4 (JWT)UnauthorizedAccessException consuming an API that requires access token













1















I am using EF6 with IdentityServer4. Everything is the database - Users, Claims, and Clients.



How do I get User's Roles out of my bearer token to the clients? Currently I have a user with a Role named CustomerAdministrator assigned to my test but I am not able to get this role out.



My CustomerAdministrator role was added in tables:



  • AspNetRoleClaims

  • AspNetRoles

  • AspNetUserRoles

What am i missing?
Token result:




"sid": "20d62652c0504f2b521c8a7c24ee7320",
"sub": "a997a3ad-82bd-430f-9191-5b95408967b1",
"auth_time": 1553518560,
"idp": "local",
"amr": [
"pwd"
],
"name": "Bob Smith",
"given_name": "Bob",
"family_name": "Smith",
"preferred_username": "bob"



The other solutions that I have found on Stack Overflow seem to be based on memory solutions.



Note: this is all based on the Combined_AspId_and_EFStorage example for IdentityServer4.



In Database:



ApsNetRoleClaims
1 | -uudi- | role | CustomerAdministrator

ApsNetRoles
1 | -uudi- | CustomerAdministrator | CustomerAdministrator | -uuid

ApsNetUserRoles
1 | -uuid User- | -uuid RoleId-

ClientScopes
3 | api1 | 1
4 | openid | 4
5 | profile | 4
6 | api | 4
7 | profile | 3
8 | api | 3
10 | role | 1
11 | role | 2
12 | role | 3
13 | role | 4

IdentityResources
1 | 1 | openip | Your user identifier | NULL | 1 | 0 | 1 | ...
2 | 1 | profile| You profile... | ... | 0 | 1 | 1 | ...
3 | 6 | role | User Role | Role | 1 | 1 | 1 | ...









share|improve this question
























  • Did you include the role claim type to your identity resource or protected resource?

    – penleychan
    Mar 25 at 16:42











  • Opdated with what i added in database and what was in those tables what am i missing?

    – user2438077
    Mar 26 at 9:39















1















I am using EF6 with IdentityServer4. Everything is the database - Users, Claims, and Clients.



How do I get User's Roles out of my bearer token to the clients? Currently I have a user with a Role named CustomerAdministrator assigned to my test but I am not able to get this role out.



My CustomerAdministrator role was added in tables:



  • AspNetRoleClaims

  • AspNetRoles

  • AspNetUserRoles

What am i missing?
Token result:




"sid": "20d62652c0504f2b521c8a7c24ee7320",
"sub": "a997a3ad-82bd-430f-9191-5b95408967b1",
"auth_time": 1553518560,
"idp": "local",
"amr": [
"pwd"
],
"name": "Bob Smith",
"given_name": "Bob",
"family_name": "Smith",
"preferred_username": "bob"



The other solutions that I have found on Stack Overflow seem to be based on memory solutions.



Note: this is all based on the Combined_AspId_and_EFStorage example for IdentityServer4.



In Database:



ApsNetRoleClaims
1 | -uudi- | role | CustomerAdministrator

ApsNetRoles
1 | -uudi- | CustomerAdministrator | CustomerAdministrator | -uuid

ApsNetUserRoles
1 | -uuid User- | -uuid RoleId-

ClientScopes
3 | api1 | 1
4 | openid | 4
5 | profile | 4
6 | api | 4
7 | profile | 3
8 | api | 3
10 | role | 1
11 | role | 2
12 | role | 3
13 | role | 4

IdentityResources
1 | 1 | openip | Your user identifier | NULL | 1 | 0 | 1 | ...
2 | 1 | profile| You profile... | ... | 0 | 1 | 1 | ...
3 | 6 | role | User Role | Role | 1 | 1 | 1 | ...









share|improve this question
























  • Did you include the role claim type to your identity resource or protected resource?

    – penleychan
    Mar 25 at 16:42











  • Opdated with what i added in database and what was in those tables what am i missing?

    – user2438077
    Mar 26 at 9:39













1












1








1








I am using EF6 with IdentityServer4. Everything is the database - Users, Claims, and Clients.



How do I get User's Roles out of my bearer token to the clients? Currently I have a user with a Role named CustomerAdministrator assigned to my test but I am not able to get this role out.



My CustomerAdministrator role was added in tables:



  • AspNetRoleClaims

  • AspNetRoles

  • AspNetUserRoles

What am i missing?
Token result:




"sid": "20d62652c0504f2b521c8a7c24ee7320",
"sub": "a997a3ad-82bd-430f-9191-5b95408967b1",
"auth_time": 1553518560,
"idp": "local",
"amr": [
"pwd"
],
"name": "Bob Smith",
"given_name": "Bob",
"family_name": "Smith",
"preferred_username": "bob"



The other solutions that I have found on Stack Overflow seem to be based on memory solutions.



Note: this is all based on the Combined_AspId_and_EFStorage example for IdentityServer4.



In Database:



ApsNetRoleClaims
1 | -uudi- | role | CustomerAdministrator

ApsNetRoles
1 | -uudi- | CustomerAdministrator | CustomerAdministrator | -uuid

ApsNetUserRoles
1 | -uuid User- | -uuid RoleId-

ClientScopes
3 | api1 | 1
4 | openid | 4
5 | profile | 4
6 | api | 4
7 | profile | 3
8 | api | 3
10 | role | 1
11 | role | 2
12 | role | 3
13 | role | 4

IdentityResources
1 | 1 | openip | Your user identifier | NULL | 1 | 0 | 1 | ...
2 | 1 | profile| You profile... | ... | 0 | 1 | 1 | ...
3 | 6 | role | User Role | Role | 1 | 1 | 1 | ...









share|improve this question
















I am using EF6 with IdentityServer4. Everything is the database - Users, Claims, and Clients.



How do I get User's Roles out of my bearer token to the clients? Currently I have a user with a Role named CustomerAdministrator assigned to my test but I am not able to get this role out.



My CustomerAdministrator role was added in tables:



  • AspNetRoleClaims

  • AspNetRoles

  • AspNetUserRoles

What am i missing?
Token result:




"sid": "20d62652c0504f2b521c8a7c24ee7320",
"sub": "a997a3ad-82bd-430f-9191-5b95408967b1",
"auth_time": 1553518560,
"idp": "local",
"amr": [
"pwd"
],
"name": "Bob Smith",
"given_name": "Bob",
"family_name": "Smith",
"preferred_username": "bob"



The other solutions that I have found on Stack Overflow seem to be based on memory solutions.



Note: this is all based on the Combined_AspId_and_EFStorage example for IdentityServer4.



In Database:



ApsNetRoleClaims
1 | -uudi- | role | CustomerAdministrator

ApsNetRoles
1 | -uudi- | CustomerAdministrator | CustomerAdministrator | -uuid

ApsNetUserRoles
1 | -uuid User- | -uuid RoleId-

ClientScopes
3 | api1 | 1
4 | openid | 4
5 | profile | 4
6 | api | 4
7 | profile | 3
8 | api | 3
10 | role | 1
11 | role | 2
12 | role | 3
13 | role | 4

IdentityResources
1 | 1 | openip | Your user identifier | NULL | 1 | 0 | 1 | ...
2 | 1 | profile| You profile... | ... | 0 | 1 | 1 | ...
3 | 6 | role | User Role | Role | 1 | 1 | 1 | ...






c# entity-framework identityserver4






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 9:38







user2438077

















asked Mar 25 at 12:57









user2438077user2438077

588 bronze badges




588 bronze badges












  • Did you include the role claim type to your identity resource or protected resource?

    – penleychan
    Mar 25 at 16:42











  • Opdated with what i added in database and what was in those tables what am i missing?

    – user2438077
    Mar 26 at 9:39

















  • Did you include the role claim type to your identity resource or protected resource?

    – penleychan
    Mar 25 at 16:42











  • Opdated with what i added in database and what was in those tables what am i missing?

    – user2438077
    Mar 26 at 9:39
















Did you include the role claim type to your identity resource or protected resource?

– penleychan
Mar 25 at 16:42





Did you include the role claim type to your identity resource or protected resource?

– penleychan
Mar 25 at 16:42













Opdated with what i added in database and what was in those tables what am i missing?

– user2438077
Mar 26 at 9:39





Opdated with what i added in database and what was in those tables what am i missing?

– user2438077
Mar 26 at 9:39










1 Answer
1






active

oldest

votes


















0














Do you mean, you want the login user's role from JWT-Token at client site?
If yes, you can pass the role name or role id at Claim objects.



 List<string> roleNames = _userManager.GetRolesAsync(user).Result.ToList();
string userRoles = "";
foreach(string rname in roleNames)

if (userRoles.Trim().Length == 0)
userRoles = rname;
else
userRoles = userRoles + "," + rname;

var claims = new List<Claim>

new Claim("UserId", user.Id),
new Claim("UserName", user.UserName),
new Claim("UserRoles", userRoles),
new Claim(ClaimTypes.Role,roleNames.FirstOrDefault()),
new Claim(ClaimTypes.Sid, user.Id)
;


From client site by angular



OnSubmit(userName,password){
const jwtHelper = new JwtHelperService();
this.accountService.userAuthentication(userName,password).subscribe((data : any)=>
var decodedToken=jwtHelper.decodeToken(data.toString());
var userRoles = decodedToken.UserRoles;
);





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%2f55338342%2fhow-can-i-get-a-role-from-identityserver4-authorization%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














    Do you mean, you want the login user's role from JWT-Token at client site?
    If yes, you can pass the role name or role id at Claim objects.



     List<string> roleNames = _userManager.GetRolesAsync(user).Result.ToList();
    string userRoles = "";
    foreach(string rname in roleNames)

    if (userRoles.Trim().Length == 0)
    userRoles = rname;
    else
    userRoles = userRoles + "," + rname;

    var claims = new List<Claim>

    new Claim("UserId", user.Id),
    new Claim("UserName", user.UserName),
    new Claim("UserRoles", userRoles),
    new Claim(ClaimTypes.Role,roleNames.FirstOrDefault()),
    new Claim(ClaimTypes.Sid, user.Id)
    ;


    From client site by angular



    OnSubmit(userName,password){
    const jwtHelper = new JwtHelperService();
    this.accountService.userAuthentication(userName,password).subscribe((data : any)=>
    var decodedToken=jwtHelper.decodeToken(data.toString());
    var userRoles = decodedToken.UserRoles;
    );





    share|improve this answer



























      0














      Do you mean, you want the login user's role from JWT-Token at client site?
      If yes, you can pass the role name or role id at Claim objects.



       List<string> roleNames = _userManager.GetRolesAsync(user).Result.ToList();
      string userRoles = "";
      foreach(string rname in roleNames)

      if (userRoles.Trim().Length == 0)
      userRoles = rname;
      else
      userRoles = userRoles + "," + rname;

      var claims = new List<Claim>

      new Claim("UserId", user.Id),
      new Claim("UserName", user.UserName),
      new Claim("UserRoles", userRoles),
      new Claim(ClaimTypes.Role,roleNames.FirstOrDefault()),
      new Claim(ClaimTypes.Sid, user.Id)
      ;


      From client site by angular



      OnSubmit(userName,password){
      const jwtHelper = new JwtHelperService();
      this.accountService.userAuthentication(userName,password).subscribe((data : any)=>
      var decodedToken=jwtHelper.decodeToken(data.toString());
      var userRoles = decodedToken.UserRoles;
      );





      share|improve this answer

























        0












        0








        0







        Do you mean, you want the login user's role from JWT-Token at client site?
        If yes, you can pass the role name or role id at Claim objects.



         List<string> roleNames = _userManager.GetRolesAsync(user).Result.ToList();
        string userRoles = "";
        foreach(string rname in roleNames)

        if (userRoles.Trim().Length == 0)
        userRoles = rname;
        else
        userRoles = userRoles + "," + rname;

        var claims = new List<Claim>

        new Claim("UserId", user.Id),
        new Claim("UserName", user.UserName),
        new Claim("UserRoles", userRoles),
        new Claim(ClaimTypes.Role,roleNames.FirstOrDefault()),
        new Claim(ClaimTypes.Sid, user.Id)
        ;


        From client site by angular



        OnSubmit(userName,password){
        const jwtHelper = new JwtHelperService();
        this.accountService.userAuthentication(userName,password).subscribe((data : any)=>
        var decodedToken=jwtHelper.decodeToken(data.toString());
        var userRoles = decodedToken.UserRoles;
        );





        share|improve this answer













        Do you mean, you want the login user's role from JWT-Token at client site?
        If yes, you can pass the role name or role id at Claim objects.



         List<string> roleNames = _userManager.GetRolesAsync(user).Result.ToList();
        string userRoles = "";
        foreach(string rname in roleNames)

        if (userRoles.Trim().Length == 0)
        userRoles = rname;
        else
        userRoles = userRoles + "," + rname;

        var claims = new List<Claim>

        new Claim("UserId", user.Id),
        new Claim("UserName", user.UserName),
        new Claim("UserRoles", userRoles),
        new Claim(ClaimTypes.Role,roleNames.FirstOrDefault()),
        new Claim(ClaimTypes.Sid, user.Id)
        ;


        From client site by angular



        OnSubmit(userName,password){
        const jwtHelper = new JwtHelperService();
        this.accountService.userAuthentication(userName,password).subscribe((data : any)=>
        var decodedToken=jwtHelper.decodeToken(data.toString());
        var userRoles = decodedToken.UserRoles;
        );






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 10:12









        Zin MinZin Min

        5894 silver badges18 bronze badges




        5894 silver badges18 bronze badges
















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            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%2f55338342%2fhow-can-i-get-a-role-from-identityserver4-authorization%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

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript