Dapatkan klaim di klien ASP.NET MVC 5, yang ditetapkan untuk TestUser di Identity Server 4

Saya telah menambahkan Klien saya ke aplikasi penyedia identitas IdentityServer4.

     new Client
        {
            ClientId = "mvc4Simple",
            ClientName = "MVC 4 Web Client",
            AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
            AllowAccessTokensViaBrowser = true,
            RequireConsent = false,
            ClientSecrets =
            {
                new Secret("secret".Sha256())
            },
            AlwaysIncludeUserClaimsInIdToken=true,
            AlwaysSendClientClaims=true,
            RedirectUris = { "https://localhost:44347/signin-oidc" },
            PostLogoutRedirectUris = { "https://localhost:44347/signout-callback-oidc" },
            AllowedScopes = new List<string>
             {
              IdentityServerConstants.StandardScopes.OpenId,
              IdentityServerConstants.StandardScopes.Profile,
              IdentityServerConstants.StandardScopes.Email                 
             },
             AllowOfflineAccess = true,
             RequirePkce = false,
             AllowPlainTextPkce = false
        }

Dan IdentityResources seperti itu

     public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
         new IdentityResources.OpenId(),
         new IdentityResources.Profile(),
         new IdentityResources.Email()
        };
    }

Dan TestUser saya seperti itu

  new TestUser
  {
      SubjectId = "12345678",
      Username = "John",
      Password = "12345",
      Claims = new List<Claim> {
                new Claim(ClaimTypes.Email, "[email protected]"),
                new Claim(ClaimTypes.Role, "admin")
            }
  }

Dan klien saya adalah aplikasi asp.net MVC sederhana. Konfigurasi kliennya seperti itu

    [assembly: OwinStartup(typeof(MVCSimple.Startup))]
    namespace MVCSimple
    {
       public partial class Startup
       {
        public void Configuration(IAppBuilder app)
         {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap =
            new Dictionary<string, string>();            
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
              AuthenticationType = "cookie"
            });          
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
             AuthenticationType = "oidc",           
             Authority = "https://localhost:44316",
             ClientId = "mvc4Simple",
             ClientSecret = "secret",
             ResponseType = "code id_token",
             Scope = "openid profile",
             UseTokenLifetime = false,
             RedirectUri = "https://localhost:44347/signin-oidc",
             PostLogoutRedirectUri = "https://localhost:44347/signout-callback-oidc",                 
             SignInAsAuthenticationType = "cookie",
             Notifications = new OpenIdConnectAuthenticationNotifications
             {
                SecurityTokenValidated = context =>
                        {                             
                        context.AuthenticationTicket.Identity.AddClaim(new 
                          Claim(ClaimTypes.NameIdentifier, context.ProtocolMessage.IdToken));
                            return Task.FromResult(0);
                        },

                RedirectToIdentityProvider = n =>
                {
                    if (n.ProtocolMessage.RequestType == 
                     Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectRequestType.Logout)
                    {
                        var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                        if (idTokenHint != null)
                        {
                            n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                        }

                    }
                    return Task.FromResult(0);
                }
              }
           });
         }
       }
     }

Otentikasi berfungsi dengan baik. Ini mengarahkan saya kembali ke aplikasi saya tetapi saya ingin tahu bagaimana saya bisa menetapkan klaim untuk TestUser saya yaitu Email dan Peran?


person Avinash Singh    schedule 18.08.2020    source sumber


Jawaban (1)


Saya membaca beberapa artikel tentang itu. Dan menyelesaikannya. Saya harus menambahkan satu cakupan.

     new ApiScope("api1.read", "Read Access to API #1")
         {
           UserClaims={
                ClaimTypes.Email,
                ClaimTypes.Role
                }
         }

Kemudian ubah detail klien

    new Client
    {
        ClientId = "mvc4Simple",
        ClientName = "MVC 4 Web Client",
        AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
        AllowAccessTokensViaBrowser = true,
        RequireConsent = false,
        ClientSecrets =
        {
            new Secret("secret".Sha256())
        },
        AlwaysIncludeUserClaimsInIdToken=true,
        AlwaysSendClientClaims=true,
        RedirectUris = { "https://localhost:44347/signin-oidc" },
        PostLogoutRedirectUris = { "https://localhost:44347/signout-callback-oidc" },
        AllowedScopes = new List<string>
         {
          IdentityServerConstants.StandardScopes.OpenId,
          IdentityServerConstants.StandardScopes.Profile,
          IdentityServerConstants.StandardScopes.Email 
          "api1.read"                
         },
         AllowOfflineAccess = true,
         RequirePkce = false,
         AllowPlainTextPkce = false
    }

Kemudian di kelas Startup ditambahkan token sebagai tipe respon.

     public void Configuration(IAppBuilder app)
     {
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap =
        new Dictionary<string, string>();            
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
          AuthenticationType = "cookie"
        });          
        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
         AuthenticationType = "oidc",           
         Authority = "https://localhost:44316",
         ClientId = "mvc4Simple",
         ClientSecret = "secret",
         ResponseType = "code id_token token",
         Scope = "openid profile api1.read",//Include that scope here
         UseTokenLifetime = false,
         RedirectUri = "https://localhost:44347/signin-oidc",
         PostLogoutRedirectUri = "https://localhost:44347/signout-callback-oidc",                 
         SignInAsAuthenticationType = "cookie",
         SaveTokens=true,
         Notifications = new OpenIdConnectAuthenticationNotifications
         {
            SecurityTokenValidated = context =>
                    {                             
                    context.AuthenticationTicket.Identity.AddClaim(new 
                    Claim(ClaimTypes.NameIdentifier,context.ProtocolMessage.IdToken));
              context.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", 
       context.ProtocolMessage.AccessToken));//Set access token in access_token claim
                        return Task.FromResult(0);
                    },

            RedirectToIdentityProvider = n =>
            {
                if (n.ProtocolMessage.RequestType ==                    
      Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectRequestType.Logout)
                {
             var idTokenHint =n.OwinContext.Authentication.User.FindFirst("id_token");
                    if (idTokenHint != null)
                    {
                        n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                    }

                }
                return Task.FromResult(0);
            }
          }
       });
     }

Dan akhirnya, saya bisa mendapatkan klaim tersebut dalam metode tindakan pengontrol saya sebagai berikut

    public ActionResult Index()
    {
        var identity = (ClaimsIdentity)User.Identity;     
        var token= identity.Claims.Where(x => x.Type == "access_token").ToList();
        if (token.Count > 0) 
        {
            var jwtToken = new JwtSecurityToken(token[0].Value);
            var claimsjwt=jwtToken.Claims;//Here you can get all the claims set for the user i.e email , role
        }
        return View();
    } 
person Avinash Singh    schedule 18.08.2020