Jwt令牌授权不起作用
我试图创建Jwt令牌授权。为了这个目的,我有这样的代码发行人部分:我Jwt令牌授权不起作用
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)
}
});
}
至于我可以看到发出的令牌是有效的(:
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);
}
和“资源”部分应该接受承载令牌在jwt.io上进行了验证),所以问题在于别的。当我在邮递员中发送令牌时,调用控制器受到[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。这是两个不同的应用程序独立运行。
在邮递员确保您使用以下格式发送授权头:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
确保你离开的授权选项卡设置为Type: No Auth
。
如果您仍然遇到问题,请在您的GrantResourceOwnerCredentials
中设置断点并查看是否达到该点。如果您想在事件链的早期进行调试,也可考虑覆盖ValidateClientAuthentication方法OAuthAuthorizationServerProvider
,该方法应在GrantResourceOwnerCredentials
之前调用。
邮差的Tha代码:Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9。eyJ1bmlxdWVfbmFtZSI6ImFuZHJleS5zaGVka29AZ21haWwuY29tIiwic3ViIjoiYW5kcmV5LnNoZWRrb0BnbWFpbC5jb20iLCJyb2xlIjoiQWRtaW4iLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjUyNzk5IiwiYXVkIjoiMDk5MTUzYzI2MjUxNDliYzhlY2IzZTg1ZTAzZjAwMjIiLCJleHAiOjE0ODc3NzIxOTEsIm5iZiI6MTQ4Nzc3MDM5MX0.5GFpvU08CjaS5LTH0vRVFIGuilenkEgVu_aJLma4lPo –
这是问题 - 在我没有安装Asp.Net身份“resorce” API,在本教程中说的 - http://bitoftech.net/2014/10/27/json-web-token-asp-净网页API-2,智威汤逊 - owin授权服务器/评论页-3 /#评论-97300。方法GrantResourceOwnerCredentials我只有“发行者”部分。 –
@ andrey.shedko你没有发布你试图通过邮递员运行的内容,但401表明某些东西没有通过你的授权。设置中断点应允许您检查并找到具体的故障点。如果您删除授权属性并通过邮递员运行请求,它会起作用吗? – cchamberlain
我刚刚尝试运行SON Web Token in ASP.NET Web API 2 using Owin中提到的demo project,并且所有按预期工作。
我注意到您的Protect
方法的实现有很大不同。我建议你将你的实现与本文给出的例子进行比较。尝试先做好这项工作。
另请确保两台服务器上的颁发者,受众和秘密相同。
如果您提供完整的源代码,我可以尝试调查更多。
请问http://security.stackexchange.com/a/128882/131820有帮助吗? – Tatranskymedved
我对此不确定。头文件有问题吗,我会收到一些不好的请求,但不会不合理。 –
我没有使用'jwt'的exp,只通过URL通过'REST'查询,其中请求标头'Authorization:Basic'是需要的,如果有错误(pass/name/syntax)它向我扔了401。 –
Tatranskymedved