我在下面的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;
}`
型
1条答案
按热度按时间gcuhipw91#
好吧,我有一个答案这个问题。KeySet在我的Web API启动中为null。我为这个解决方案提供了一个方法。我用这个方法解决了我的问题。方法是。。
字符串
}
我的Web API启动是…
型