前后端分离的开发中,应用服务需要进行用户身份的验证才允许访问数据。实现的方法很简单。创建一个webapi项目。在App_Start目录下找到WebApiConfig.cs, 在里面增加一个实现类。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
config.Filters.Add(new CustomAuthorize());
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
public class CustomAuthorize : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
//如果用户的Action带有AllowAnonymousAttribute,则不用检测
if (actionContext.ActionDescriptor.GetCustomAttributes<System.Web.Http.AllowAnonymousAttribute>().Any())
{
return;
}
app 接口检测
object au = actionContext.Request.Headers.Authorization;
if (au == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Ret = 4002, Msg = "Token错误!" });
}
else if (!Redis.haskey(au.ToString()))
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Ret = 4008, Msg = "Token超时!" });
}
}
}
}
Controller 类的实现:
[RoutePrefix("api/v1")]
public class ValuesController : ApiController
{
[AllowAnonymous] //匿名访问
[Route("getData1"), HttpPost]
public JObject getData1([FromBody] JObject data)
{
return data;
}
//登录访问
[Route("getData2"), HttpPost]
public JObject getData2([FromBody] JObject data)
{
return data;
}
}