处理AuthorizeAttribute回答

时间:2017-08-03 18:53:56

标签: c# owin authorize-attribute

我确实创建了应该处理Jwt Bearer令牌的自定义AuthorizeAttribute,但问题是 - 现在我收到所有答案,包括Ok状态下的200和401,我应该如何更改它以便接收正确的http状态代码?以下是public class JwtAuthorizeAttribute : AuthorizeAttribute { private readonly string role; public JwtAuthorizeAttribute() { } public JwtAuthorizeAttribute(string role) { this.role = role; } protected override bool IsAuthorized(HttpActionContext actionContext) { var jwtToken = new JwtToken(); string json = String.Empty; var ctx = actionContext.Request.GetRequestContext(); if (ctx.Principal.Identity.IsAuthenticated) return true; if (actionContext.Request.Headers.Contains("Authorization")) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); json = decoder.Decode(actionContext.Request.Headers.Authorization.Parameter, SiteGlobal.Secret, verify: true); jwtToken = JsonConvert.DeserializeObject<JwtToken>(json); if (jwtToken.aud != SiteGlobal.Audience || jwtToken.iss != SiteGlobal.Issuer || role != jwtToken.role) { return false; } } catch (TokenExpiredException) { return false; } catch (SignatureVerificationException) { return false; } } else { return false; } var identity = new ClaimsIdentity("JWT"); identity.AddClaim(new Claim(ClaimTypes.Name, jwtToken.unique_name)); identity.AddClaim(new Claim(ClaimTypes.Role, jwtToken.role)); identity.AddClaim(new Claim("user_id", jwtToken.user_id.ToString())); actionContext.Request.GetRequestContext().Principal = new ClaimsPrincipal(identity); return true; } } 的样子:

[JwtAuthorize("Admin")]
[HttpGet]
[ResponseType(typeof(CatalogueListDto))]
public async Task<IHttpActionResult> Get()
  {
    var result = await _catalogueService.GetCatalogues();
    if (result == null) return BadRequest(ActionAnswer.Failed.CatalogueNotFound);
     return Ok(result);
  }

这就是控制器的样子:

curl --request POST \
--url 'https://usX.api.mailchimp.com/3.0/lists/57afe96172/members' \
--user 'anystring:apikey' \
--header 'content-type: application/json' \
--data '{"email_address":"urist.mcvankab+3@freddiesjokes.com", "status":"subscribed"}' \
--include

1 个答案:

答案 0 :(得分:1)

我有一个类似的属性,通过遵循过去的一些教程。如果获得授权,我不会返回true,但我会回复:

ionic cordova emulate android

如果这返回正确的状态代码,可能值得检查。