网上Jersey中文资料不多,更别提其他了。本人跟进项目具体需求弄了简单的api认证机制
基本流程图
后端登录退出代码:
@Path("Account") public class AccountResource { @GET public Response Login() { Map<String,Object> m = new HashMap<String,Object>(); m.put("userid", "admin"); String token = JavaWebToken.createJavaWebToken(m); return Response.ok(token).build(); } @POST public Response LoginOut(String t) { return Response.ok("ok").build(); } }
后端Jersey验证流程
http在跨域请求过程中:首先发起OPTIONS请求,然后再发送真正的GET\PUT\POST\DELETE请求。而且OPTIONS请求是不带heads信息的,所以得把他排除在外面去。
后端Jersey过滤器代码
public class CheckRequestFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { String url=requestContext.getUriInfo().getPath(); if(!url.contains("Dicts")&&!url.contains("Account")) { if(!requestContext.getMethod().equals("OPTIONS")) { String token = requestContext.getHeaderString("authorization"); if(!GeneralMethod.IsNullOrEmpty(token)){ if (!JavaWebToken.isLegal(token)) { requestContext.abortWith(Response .status(Response.Status.UNAUTHORIZED) .entity("无权访问该资源.") .build()); } }else { requestContext.abortWith(Response .status(Response.Status.UNAUTHORIZED) .entity("无权访问该资源.") .build()); } } } } }
前端登录和退出代码
login(){ var self = this; this.axios.get(‘Account‘).then(function (res) { self.axios.defaults.headers.common[‘authorization‘]=res.data; }); }, loginOut(){ var self = this; this.axios.post(‘Account‘,{t:‘1‘}).then(function (res) { self.axios.defaults.headers.common[‘authorization‘]=‘‘; }); }