前后端分离,获取token,验证登陆是否失效
2019-09-17 10:22:21来源:博客园 阅读 ()
前后端分离,获取token,验证登陆是否失效
maven依赖
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>2.2.0</version> </dependency>
public class JwtUtils { /** * 密钥 */ private static final String SECRET="xxxx"; /** * 默认字段key:exp */ private static final String EXP="exp"; /** * 默认字段key:payload */ private static final String PAYLOAD="payload"; /** * 加密 * @param object 加密数据 * @param maxTime 有效期(毫秒数) * @param <T> * @return */ public static <T> String encode(T object,long maxTime){ try{ final JWTSigner signer=new JWTSigner(SECRET); final Map<String ,Object> data=new HashMap<>(10); ObjectMapper objectMapper=new ObjectMapper(); String jsonString=objectMapper.writeValueAsString(object); data.put(PAYLOAD,jsonString); data.put(EXP,System.currentTimeMillis()+maxTime); return signer.sign(data); } catch (IOException e) { e.printStackTrace(); return null; } } /** * 数据解密 * @param jwt 解密数据 * @param tClass 解密类型 * @param <T> * @return */ public static <T> T decode(String jwt,Class<T> tClass) { final JWTVerifier jwtVerifier = new JWTVerifier(SECRET); try { final Map<String, Object> data = jwtVerifier.verify(jwt); //判断数据是否超时或者符合标准 if (data.containsKey(EXP) && data.containsKey(PAYLOAD)) { long exp = (long) data.get(EXP); long currentTimeMillis = System.currentTimeMillis(); if (exp > currentTimeMillis) { String json = (String) data.get(PAYLOAD); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, tClass); } } return null; } catch (Exception e) { //e.printStackTrace(); return null; } } //解密token取出userId public static <T> T updateDecode(String jwt,Class<T> tClass){ final JWTVerifier jwtVerifier = new JWTVerifier(SECRET); try { final Map<String, Object> data = jwtVerifier.verify(jwt); String json = (String) data.get(PAYLOAD); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, tClass); } catch (Exception e) { //e.printStackTrace(); return null; } } public static void main(String[] args) throws InterruptedException { // 有效期10秒 // 加密: // TestCenterAdministratorsVO test = new TestCenterAdministratorsVO(); // test.setId(1L); // test.setLoginName("sa"); // String token=encode(test,1000000); // System.out.println("TOKEN======="+token); // //Thread.sleep(10000); //// 解密 // TestCenterAdministratorsVO user=decode(token,TestCenterAdministratorsVO.class); // System.out.println(user.getId()+user.getLoginName()); //removeDecode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NDcwODkwNTYxNDgsInBheWxvYWQiOiJ7XCJpZFwiOjEsXCJuYW1lXCI6bnVsbCxcInBob25lTnVtYmVyXCI6bnVsbCxcImxvZ2luTmFtZVwiOlwic2FcIixcInNlcmlhbE51bWJlclwiOm51bGwsXCJ0eXBlXCI6bnVsbCxcInRlc3RDZW50ZXJJZFwiOm51bGwsXCJvcmdhbml6YXRpb25JZFwiOm51bGwsXCJtYWluU2l0ZUFkbWluXCI6ZmFsc2UsXCJhZG1pblwiOmZhbHNlLFwib3JnYW5pemF0aW9uTmFtZVwiOm51bGx9In0.FgYm4wSDhkZukqlRukjwvxQ1BM746AWQfCmGucMP3pc"); updateDecode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NDcwMTgxNTU4OTYsInBheWxvYWQiOiJ7XCJpZFwiOjIwMTAwMDAzMyxcIm5hbWVcIjpcIuW6numTtuaYjFwiLFwicGhvbmVOdW1iZXJcIjpudWxsLFwibG9naW5OYW1lXCI6XCJwYW5neWluY2hhbmdcIixcInNlcmlhbE51bWJlclwiOm51bGwsXCJ0eXBlXCI6XCJNQUlOU0lURUFETUlOXCIsXCJ0ZXN0Q2VudGVySWRcIjo3OSxcIm9yZ2FuaXphdGlvbklkXCI6XCIwMDFcIixcIm1haW5TaXRlQWRtaW5cIjp0cnVlLFwiYWRtaW5cIjpmYWxzZSxcIm9yZ2FuaXphdGlvbk5hbWVcIjpudWxsfSJ9.yrYlU4djPPQyu1mneQgkVgLCEQiJ2pKkyX8EVw0NcY8",TestCenterAdministratorsVO.class); } }
跨域设置拦截器
import com.alibaba.fastjson.JSONObject; import org.springframework.web.bind.annotation.RequestMethod; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created with IDEA * author:QinWei * Date:2019/1/8 * Time:16:15 */ public class AjaxFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; //禁止首页访问 String url = request.getRequestURI(); if("/".equals(url)){ return; } // 指定允许其他域名访问 response.setHeader("Access-Control-Allow-Origin", "*"); // 响应类型 response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE"); // 响应头设置 response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token"); chain.doFilter(req, res); } @Override public void init(FilterConfig arg0) throws ServletException { } }
web.xml
<filter> <filter-name>ajaxFilter</filter-name> <filter-class>*.*.*.web.servlet.barcode.AjaxFilter</filter-class> </filter> <filter-mapping> <filter-name>ajaxFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
拦截token过滤器,包含获取spring--bean手动注入
response .setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String actionName = context.getActionInvocation().getProxy().getActionName(); String url = request.getRequestURI(); ServletContext application = ServletActionContext.getServletContext(); WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application); this.testCenterService = (TestCenterService)ctx.getBean("testCenterService"); if(!url.equals("/login")){ //悠闲判断是否为空或者时间是否失效 String token = request.getParameter("token"); TestCenterAdministratorsVO user = JwtUtils.decode(token, TestCenterAdministratorsVO.class); if(null==token||"".equals(token)||null==user){ out.print(Message.error(0,"token不合法!")); return null; }else{ try { //再次判断数据库状态 TestCenterAdministratorsVO users = JwtUtils.updateDecode(token, TestCenterAdministratorsVO.class); String tokens = testCenterService.scheckToken(token,users.getId()); if(null==tokens){ out.print(Message.error(0,"token不合法!")); return null; } }catch (Exception e){ out.print(Message.error()); return null; } } }
加群:687942640
微信扫描公众号
原文链接:https://www.cnblogs.com/qwlscn/p/11495368.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:使用AOP进行权限验证
- SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 后 2020-06-10
- Java中jar包获取资源文件的方式 2020-06-05
- Java连载120-反射机制获取构造方法和父类、父接口 2020-06-05
- Java获取当前时间到凌晨12点剩余秒数 2020-06-03
- 初识Nginx——前后端发布 2020-06-03
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash