簡體   English   中英

Jwt令牌授權不起作用

[英]Jwt tokens authorization is not working

我正在嘗試創建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代碼。 你能告訴我如何解決這個問題嗎?

PS這就是我實現自定義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;
}

PS伙計們,我很抱歉,但我忘了解釋“發行人”部分代碼是獨立應用程序,同時“受眾”是受保護的web api。 這是兩個獨立運行的不同應用程序。

在Postman中,確保使用以下格式發送授權標頭:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

郵差授權標題

確保將“授權”選項卡設置為“ Type: No Auth

如果您仍然遇到問題,請在GrantResourceOwnerCredentials設置斷點,看看它是否達到了這一點。 還要考慮覆蓋OAuthAuthorizationServerProviderValidateClientAuthentication方法,如果要在事件鏈中先調試,則應在GrantResourceOwnerCredentials之前調用該方法。

我剛剛嘗試使用Owin在ASP.NET Web API 2中運行SON Web Token中提到的演示項目 ,並且所有工作都按預期工作。

我注意到你的Protect方法的實現有很大的不同。 我建議你將你的實現與文章中給出的例子進行比較。 嘗試先做到這一點。

另外,請確保兩台服務器上的頒發者,受眾和秘密相同。

如果您提供完整的源代碼,我可以嘗試進行更多調查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM