我正在构建一个具有固定凭据的简单应用程序,因此无需与 EF 或其他任何东西集成。
我正在尝试将 AspNet.Security.OpenIdConnect.Server 包与 JWT 配置一起使用,我可以验证我的凭据并返回令牌,但使用 [Authorize] 属性我的端点总是返回 401 未授权。
启动.cs
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddOpenIdConnectServer(options =>
{
options.AllowInsecureHttp = true;
options.AccessTokenLifetime = TimeSpan.FromHours(1);
options.TokenEndpointPath = "/v1/authtoken";
options.AccessTokenHandler = new JwtSecurityTokenHandler
{
OutboundClaimTypeMap = new Dictionary<string, string>()
};
options.Provider = new AuthorizationProvider();
options.SigningCredentials.AddKey(Key);
})
.AddJwtBearer();
....
app.UseAuthentication();
授权提供者.cs
public override Task HandleTokenRequest(HandleTokenRequestContext context)
{
if (context.Request.IsClientCredentialsGrantType())
{
if (!string.Equals(context.Request.ClientId, "username", StringComparison.Ordinal) ||
!string.Equals(context.Request.ClientSecret, "password, StringComparison.Ordinal))
{
context.Reject(
error: OpenIdConnectConstants.Errors.InvalidGrant,
description: "Invalid user credentials.");
return Task.CompletedTask;
}
var identity = new ClaimsIdentity(context.Scheme.Name);
identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.Subject, "subject"));
identity.AddClaim(ClaimTypes.Role, "user", OpenIdConnectConstants.Destinations.AccessToken,
OpenIdConnectConstants.Destinations.AccessToken);
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(), context.Scheme.Name);
ticket.SetResources("resource_server");
context.Validate(ticket);
}
return Task.CompletedTask;
}
控制器
[Authorize(Roles = "user")]
public class ValuesController : Controller
根据 jwt.io,这是 JWT 内部的有效负载:
{
"sub": "subject",
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "user",
"token_usage": "access_token",
"jti": "7b5d3180-b535-489b-97ec-fccaedf9615a",
"cfd_lvl": "private",
"aud": "resource_server",
"azp": "username",
"nbf": 1550510623,
"exp": 1550514223,
"iat": 1550510623,
"iss": "https://localhost:44302/"
}
也尝试使用 just [Authorize]
,但我也得到 401 未授权。
如果我使用默认的 ASOS 令牌,它可以正常工作,只是在使用 JWT 时出现问题(我正在尝试使用它,因为我想添加自定义密钥而不是证书)。