我查看 Microsoft.Owin.Security.Jwt 源代码,发现它无法处理 Response 。你可以这样做。
public class TokenAuthorizeAttribute: AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
//Write Your Response Body ,Now I Throw a Custom ValidateException;
throw new TokenValidateException();
//base.HandleUnauthorizedRequest(actionContext);
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
return base.IsAuthorized(actionContext);
}
}
另一种方法
1.添加扩展
public static class AppBuilderExtensions
{
/// <summary>
/// Jwt Authentication Extension
/// </summary>
/// <param name="app"></param>
/// <param name="options"></param>
public static void UseJwtAuthentication(this IAppBuilder app, JwtBearerAuthenticationOptions options)
{
app.UseJwtBearerAuthentication(options);
app.Use<JwtToken>();
}
}
2.制作中间件
using Microsoft.Owin;
using System.Security.Principal;
using System.Threading;
using AppFunc = Func<IDictionary<string, object>, Task>;
/// <summary>
/// 访问授权验证
/// </summary>
public class JwtToken
{
AppFunc _NextFunc;
public JwtToken(AppFunc headerAuthentication)
{
_NextFunc = headerAuthentication;
}
public async Task Invoke(IDictionary<string, object> environment)
{
IOwinContext context = new OwinContext(environment);
if (AuthorizeCore(context))
{
await _NextFunc.Invoke(environment);
}else{
IOwinResponse response = context.Response;
response.StatusCode = 401;
response.ContentType = "application/json; charset=utf-8";
response.Write(string.Format("{{\"ErrCode\": 0,\"ErrMsg\": null,\"SubErrCode\": {0},\"SubErrMsg\": \"\"}}",
HandlerErrorStatusCode.SystemParamsValidateException));
}
}
///Check Token IsAuthenticated
private bool AuthorizeCore(IOwinContext httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.Authentication.User;
if (user == null || !user.Identity.IsAuthenticated)
{
return false;
}
return true;
}
/// <summary>
/// 资源的释放
/// </summary>
public void Dispose() { }
}