Jwt令牌授权不起作用

时间:2017-02-20 04:01:43

标签: c# oauth-2.0 authorization owin jwt

我正在尝试创建Jwt令牌授权。为此目的,我有发行者部分代码如下:

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
    Users user;
    using (var db = new UserStore())
    {
        user = Task.Run(()=> db.FindUser(context.UserName, context.Password, context.ClientId)).Result;
    }
    if (user == null)
    {
        context.SetError("invalid_grant", "The user name or password is incorrect");
        return Task.FromResult<object>(null);
    }
    var identity = new ClaimsIdentity("JWT");
    identity.AddClaim(new Claim(ClaimTypes.Name, user.Email));
    identity.AddClaim(new Claim("sub", context.UserName));
    identity.AddClaim(new Claim(ClaimTypes.Role, user.Roles.Name));

    var props = new AuthenticationProperties(new Dictionary<string, string>
    {
        {
            "audience", context.ClientId ?? string.Empty
        }
    });
    var ticket = new AuthenticationTicket(identity, props);
    context.Validated(ticket);
    return Task.FromResult<object>(null);
}

应该接受持有人令牌的“资源”部分:

public void ConfigureOAuth(IAppBuilder app)
{
    var issuer = SiteGlobal.Issuer;
    var audience = SiteGlobal.Audience;
    var secret = TextEncodings.Base64Url.Decode(SiteGlobal.Secret);
    app.UseJwtBearerAuthentication(
    new JwtBearerAuthenticationOptions
    {
        AuthenticationMode = AuthenticationMode.Active,
        AllowedAudiences = new[] { audience },
        IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        {
            new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
        }
    });
}

据我所知,发布的令牌是有效的(我在jwt.io上做了验证),所以问题就是其他问题。当我在Postman中发送令牌并调用受[Authorize]属性保护的控制器时,它总是返回401代码。你能告诉我如何解决这个问题吗?

P.S。这就是我实现自定义Jwt fortmat的方法:

public string Protect(AuthenticationTicket data)
{
    if (data == null)
    {
        throw new ArgumentNullException("data");
    }
    string audienceId = data.Properties.Dictionary.ContainsKey(AudiencePropertyKey) ? data.Properties.Dictionary[AudiencePropertyKey] : null;
    if (string.IsNullOrWhiteSpace(audienceId)) throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience");
    Audience audience;
    using (var store = new AudienceStore())
    {
        audience = Task.Run(()=> store.FindAudience(audienceId)).Result;
    }
    var symmetricKeyAsBase64 = audience.Base64Secret;
    var signingKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(symmetricKeyAsBase64));
    var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
    var issued = data.Properties.IssuedUtc;
    var expires = data.Properties.ExpiresUtc;
    var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);
    var handler = new JwtSecurityTokenHandler();
    var jwt = handler.WriteToken(token);
    return jwt;
}

P.S。伙计们,我很抱歉,但我忘了解释“发行人”代码的一部分是独立的应用程序,同时“受众”是受保护的web api。这是两个独立运行的应用程序。

2 个答案:

答案 0 :(得分:2)

在Postman中,确保使用以下格式发送授权标头:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Postman Authorization Header

确保将“授权”标签设置为Type: No Auth

如果您仍有问题,请在GrantResourceOwnerCredentials中设置一个断点,看看它是否达到了这一点。如果您想在事件链中更早地进行调试,还应考虑覆盖OAuthAuthorizationServerProvider GrantResourceOwnerCredentials方法,该方法应在done之前调用。

答案 1 :(得分:2)

我刚尝试运行demo project中提到的SON Web Token in ASP.NET Web API 2 using Owin,并且都按预期工作。

我注意到Protect方法的实现有很大不同。我建议你将你的实现与文章中给出的例子进行比较。尝试先做到这一点。

另外请确保两台服务器上的发行人,受众和秘密相同。

如果您提供完整的源代码,我可以尝试进行更多调查。