Identity Server 6:问题是如何在Asp.net(.Net Framework 4.8)中进行API授权?

iyfjxgzm  于 2023-08-08  发布在  .NET
关注(0)|答案(1)|浏览(149)

我在下面的API启动中尝试了这个方法,并显示我通过Web MVC项目调用API时的错误。错误为“响应状态代码未指示成功:401(未经授权)。”

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {

            AuthenticationType = "jwt",
            AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
            TokenValidationParameters = new TokenValidationParameters
            {

                ValidIssuer = Urls.IdentityServer,
                ValidateIssuer = true,

                ValidAudience = Urls.IdentityServer + "/resources", 
                ValidateAudience = true,

                ValidateIssuerSigningKey = true,

                ValidateLifetime = true,
                IssuerSigningKeyResolver = LoadKeys,
                NameClaimType = "name",
                RoleClaimType = "role",
            },
        });

字符串
Web API Startup中的My Keyset方法。

internal static DiscoveryCache _discoveryCache = new DiscoveryCache(Urls.IdentityServer);

    private IEnumerable<SecurityKey> LoadKeys(string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameters)
    {
       
        var disco = _discoveryCache.GetAsync().Result;

        var keys = disco.KeySet.Keys
            .Where(x => x.N != null && x.E != null)
            .Select(x =>
            {
                var rsa = new RSAParameters
                {
                    Exponent = Base64UrlEncoder.DecodeBytes(x.E),
                    Modulus = Base64UrlEncoder.DecodeBytes(x.N),
                };

                return new RsaSecurityKey(rsa)
                {
                    KeyId = x.Kid
                };
            });

        
        return keys;
    }


策略/规则方法。这是我的“public Task GetProfileDataAsync(ProfileDataRequestContext context)”方法。

{
        var UserName = "";
      

        foreach (var data in context.Subject.Identities)
        {
            UserName = data.Name;
          
        }
        var Roless = _loginValidationService.RoleAsync(UserName).Result;

        List<Claim> customClaims = new List<Claim>();

        foreach (var item in Roless)
        {
            var role = new Claim("role", item.Name);
            customClaims.Add(role);
        }

        var RoleClaim = _loginValidationService.ClaimAsync(Roless).Result;

        foreach (var claim in RoleClaim)
        {
            var Roleclaim = new Claim( claim.ClaimType, claim.ClaimValue) ;
            customClaims.Add(Roleclaim);
        }

        var getuser = _applicationDbContext.Users.Where(x => x.UserName.Equals(UserName)).ToList();

        foreach (var user in getuser)
        {
            var Userclaims = _applicationDbContext.UserClaims.Where(x => x.UserId.Equals(user.Id)).ToList();
            foreach (var Claim in Userclaims)
            {
                var role = new Claim(Claim.ClaimType, Claim.ClaimValue);
                customClaims.Add(role);
            }
        }
        

        context.IssuedClaims.AddRange(customClaims);
        return Task.CompletedTask;
    }`

gcuhipw9

gcuhipw91#

好吧,我有一个答案这个问题。KeySet在我的Web API启动中为null。我为这个解决方案提供了一个方法。我用这个方法解决了我的问题。方法是。。

{
public class OpenIdConnectSigningKeyResolver
{
    private readonly OpenIdConnectConfiguration openIdConfig;

    public OpenIdConnectSigningKeyResolver(string authority)
    {
        var cm = new ConfigurationManager<OpenIdConnectConfiguration>($"{authority.TrimEnd('/')}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
        openIdConfig = AsyncHelper.RunSync(async () => await cm.GetConfigurationAsync());
    }

    public SecurityKey[] GetSigningKey(string kid)
    {
        return new[] { openIdConfig.JsonWebKeySet.GetSigningKeys().FirstOrDefault(t => t.KeyId == kid) };
    }
}

字符串
}
我的Web API启动是…

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var Domain = Urls.IdentityServer;
        var KeyResolver = new OpenIdConnectSigningKeyResolver(Domain);

        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AuthenticationType = "jwt",
            AuthenticationMode = AuthenticationMode.Active,
            TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = Domain,
                ValidAudience = "APICore",
                IssuerSigningKeyResolver = (token, securityToken, kid, parameters) => KeyResolver.GetSigningKey(kid)
            }
        });

        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional });
        app.UseWebApi(config);
    }
}

相关问题