網上Jersey中文資料很少,更別提其餘了。本人跟進項目具體需求弄了簡單的api認證機制前端
基本流程圖ios
後端登陸退出代碼:axios
@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信息的,因此得把他排除在外面去。api
後端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']=''; }); }