ASP.Net ASOS JWT返回令牌,但未授权

时间:2019-02-18 17:31:53

标签: c# asp.net .net-core aspnet-contrib

我正在构建具有固定凭据的简单应用程序,因此无需与EF或其他任何东西集成。

我正在尝试通过JWT配置使用AspNet.Security.OpenIdConnect.Server软件包,我可以验证我的凭据并返回Token,但是使用[Authorize]属性,我的端点始终返回未经授权的401。

Startup.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();

AuthorizationProvider.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/"
}

也尝试仅使用[Authorize],但我也遭到401的未授权使用。

如果我使用默认的ASOS令牌,它可以毫无问题地工作,只是在使用JWT时遇到问题(我想使用它是因为我想添加自定义密钥而不是证书)。

Postman Request body

0 个答案:

没有答案
相关问题