Próbuję utworzyć autoryzację tokena Jwt. W tym celu muszę emitenta część z kodem tak:Autoryzacja tokenów Jwt nie działa
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);
}
i „zasobów” część, która powinna przyjąć okaziciela Token:
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)
}
});
}
O ile widzę wydany żeton są ważne (I czy sprawdzanie poprawności na jwt.io), więc problem jest trochę inny. Kiedy wysyłam tokenowi w Postmanie z wywołaniem kontrolera chronionym atrybutem [Authorize]
, zawsze zwraca on kod 401. Czy możesz doradzić, jak to naprawić?
P.S. W ten sposób zaimplementowałem niestandardową fortecę Jwt:
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. Faceci, bardzo mi przykro, ale zapomniałem wytłumaczyć, że "emitent" jest częścią kodu, który jest samodzielną aplikacją, a tymczasem "publiczność" jest chroniona przez web api. To dwie różne aplikacje działające niezależnie.
Czy http://security.stackexchange.com/a/128882/131820 nie pomoże? – Tatranskymedved
Nie jestem tego pewien. Czy jest problem z nagłówkami, otrzymam coś takiego, jak zła prośba, ale nie bez towarzystwa. –
Nie mam exp z 'jwt', tylko z zapytaniami' REST' przez URL, gdzie nagłówek żądania 'Authorization: Basic' był potrzebny i jeśli coś było nie tak (pass/name/syntax), rzuciło mi 401. –
Tatranskymedved