ssm 使用token校驗(yàn)登錄的實(shí)現(xiàn)
背景
token的意思是“令牌”,是服務(wù)端生成的一串字符串,作為客戶端進(jìn)行請(qǐng)求的一個(gè)標(biāo)識(shí)。
當(dāng)用戶第一次登錄后,服務(wù)器生成一個(gè)token并將此token返回給客戶端,以后客戶端只需帶上這個(gè)token前來請(qǐng)求數(shù)據(jù)即可,無需再次帶上用戶名和密碼。
簡(jiǎn)單token的組成;uid(用戶唯一的身份標(biāo)識(shí))、time(當(dāng)前時(shí)間的時(shí)間戳)、sign(簽名,token的前幾位以哈希算法壓縮成的一定長(zhǎng)度的十六進(jìn)制字符串。為防止token泄露)
使用場(chǎng)景
- token 還能起到反爬蟲的作用,當(dāng)然爬蟲也是有突破的方法的,盡管如此還是能減少一部分爬蟲訪問服務(wù)器的所帶來的負(fù)載。相對(duì)的爬蟲技術(shù)門檻變高了。
- 使用session也能達(dá)到用戶驗(yàn)證的目的 、但是session 是消耗服務(wù)器的內(nèi)存,在對(duì)性能要求較高的項(xiàng)目中 ,開發(fā)中該技術(shù)相較于token已經(jīng)過時(shí)
補(bǔ)充
- token主要使用于在廣大的安卓開發(fā)中
- 使用springmvc 中攔截器實(shí)現(xiàn)
使用方法
在maven ssm項(xiàng)目中pom.xml 配置 中引用jar包
<!--token生成--> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.3.0</version> </dependency>
創(chuàng)建JwtUtil 工具類
package xyz.amewin.util; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.DecodedJWT; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Java web token 工具類 * * @author qiaokun * @date 2018/08/10 */ public class JwtUtil { /** * 過期時(shí)間一天, * TODO 正式運(yùn)行時(shí)修改為15分鐘 */ private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000; /** * token私鑰 */ private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618"; /** * 校驗(yàn)token是否正確 * * @param token 密鑰 * @return 是否正確 */ public static boolean verify(String token) { try { Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); JWTVerifier verifier = JWT.require(algorithm) .build(); DecodedJWT jwt = verifier.verify(token); return true; } catch (Exception exception) { return false; } } /** * 獲得token中的信息無需secret解密也能獲得 * * @return token中包含的用戶名 */ public static String getUsername(String token) { try { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("loginName").asString(); } catch (JWTDecodeException e) { return null; } } /** * 獲取登陸用戶ID * @param token * @return */ public static String getUserId(String token) { try { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("userId").asString(); } catch (JWTDecodeException e) { return null; } } /** * 生成簽名,15min后過期 * * @param username 用戶名 * @return 加密的token */ public static String sign(String username,String userId) { try { // 過期時(shí)間 Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); // 私鑰及加密算法 Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); // 設(shè)置頭部信息 Map<String, Object> header = new HashMap<>(2); header.put("typ", "JWT"); header.put("alg", "HS256"); // 附帶username,userId信息,生成簽名 return JWT.create() .withHeader(header) .withClaim("loginName", username) .withClaim("userId",userId) .withExpiresAt(date) .sign(algorithm); } catch (UnsupportedEncodingException e) { return null; } } }
創(chuàng)建TokenInterceptor 攔截器
package xyz.amewin.interceptor; import com.alibaba.fastjson.JSONObject; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import xyz.amewin.util.ApiResponse; import xyz.amewin.util.Contant; import xyz.amewin.util.JwtUtil; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; /** * @author Amewin * @date 2020/4/17 22:42 * 此處攔截器 */ public class TokenInterceptor implements HandlerInterceptor { /** * 攔截器和過濾器的區(qū)別 * 1.攔截器針對(duì)訪問控制器進(jìn)行攔截 * 及 @RequestMapping(value = {"/test"}) * 簡(jiǎn)而言說就是訪問方法的url * 應(yīng)用:可以作為權(quán)限的判斷, * 2.過濾器則是針對(duì)全局的請(qǐng)求 * 包括:css/js/html/jpg/png/git/... * 及靜態(tài)文件 * 20200417 23:13 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("執(zhí)行方法之前執(zhí)行這步操作!"); response.setCharacterEncoding("utf-8"); Cookie cookie=getCookieByName(request,"_COOKIE_NAME"); //如果已經(jīng)登錄,不攔截 if (null != cookie) { //驗(yàn)證token是否正確 boolean result = JwtUtil.verify(cookie.getValue()); if (!result) { return false; } return true; } //如果沒有登錄,則跳轉(zhuǎn)到登錄界面 else { //重定向 第一種 調(diào)用控制器 方法 response.sendRedirect(request.getContextPath() + "/login"); //重定向 第二種 重定向方法 // request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request, response); // System.out.println(request.getContextPath()); return false; /** * 以下是為了登錄成功后返回到剛剛的操作,不跳到主界面 * 實(shí)現(xiàn):通過將請(qǐng)求URL保存到session的beforePath中,然后在登錄時(shí)判斷beforePath是否為空 */ } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } /** * 根據(jù)名字獲取cookie * * @param request * @param name cookie名字 * @return */ public static Cookie getCookieByName(HttpServletRequest request, String name) { Map<String, Cookie> cookieMap = ReadCookieMap(request); if (cookieMap.containsKey(name)) { Cookie cookie = cookieMap.get(name); return cookie; } else { return null; } } /** * 將cookie封裝到Map里面 * * @param request * @return */ private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) { Map<String, Cookie> cookieMap = new HashMap<String, Cookie>(); Cookie[] cookies = request.getCookies(); if (null != cookies) { for (Cookie cookie : cookies) { cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } /** * 返回信息給客戶端 * * @param response * @param out * @param apiResponse */ private void responseMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out, ApiResponse apiResponse) throws IOException { response.setContentType("application/json; charset=utf-8"); out.print(JSONObject.toJSONString(apiResponse)); out.flush(); out.close(); } }
spring-mvc.xml配置攔截器:
<!--自定義攔截器--> <mvc:interceptors> <!-- 驗(yàn)證是否登錄 通過cookie --> <mvc:interceptor> <!-- 攔截所有mvc控制器 --> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/checkLogin"/> <bean class="xyz.amewin.interceptor.TokenInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
在控制器中使用
//查詢數(shù)據(jù)庫,登錄 PwUser pwUser = loginService.jsonLogin(username, password); if (pwUser != null) { json.setSuccess(true); json.setMsg("登錄成功!"); String token = JwtUtil.sign(pwUser.getUsernuber(), pwUser.getUserid().toString()); if (token != null) { Cookie cookie = new Cookie("_COOKIE_NAME", token); cookie.setMaxAge(3600);//設(shè)置token有效時(shí)間 cookie.setPath("/"); response.addCookie(cookie); }else{ json.setMsg("密碼或賬號(hào)錯(cuò)誤!"); } } else { json.setMsg("密碼或賬號(hào)錯(cuò)誤!"); }
最后一點(diǎn)要web.xml 中配置加載spring-mvc攔截器
<!-- 3.Servlet 前端控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 路徑--> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!-- 自動(dòng)加載--> <load-on-startup>1</load-on-startup> <!-- <async-supported>true</async-supported> --> </servlet>
到此這篇關(guān)于ssm 使用token校驗(yàn)登錄的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)ssm token校驗(yàn)登錄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
maven依賴關(guān)系中的<scope>provided</scope>使用詳解
這篇文章主要介紹了maven依賴關(guān)系中的<scope>provided</scope>使用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07springboot內(nèi)置tomcat之NIO處理流程一覽
這篇文章主要介紹了springboot內(nèi)置tomcat之NIO處理流程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12springboot 配置DRUID數(shù)據(jù)源的方法實(shí)例分析
這篇文章主要介紹了springboot 配置DRUID數(shù)據(jù)源的方法,結(jié)合實(shí)例形式分析了springboot 配置阿里DRUID數(shù)據(jù)源的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2019-12-12SpringMVC中RequestBody注解的List參數(shù)傳遞方式
這篇文章主要介紹了SpringMVC中RequestBody注解的List參數(shù)傳遞方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10springboot如何配置上傳文件的maxRequestSize
這篇文章主要介紹了springboot如何配置上傳文件的maxRequestSize,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Springboot如何切換默認(rèn)的Tomcat容器
這篇文章主要介紹了Springboot如何切換默認(rèn)的Tomcat容器,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06PowerJob的DesignateServer工作流程源碼解讀
這篇文章主要介紹了PowerJob的DesignateServer工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01