App下載

教你用token來(lái)實(shí)現(xiàn)ssm中校驗(yàn)登錄的功能

著名野迪表演藝術(shù)家 2021-08-13 14:53:24 瀏覽數(shù) (3162)
反饋

什么是校驗(yàn)登錄?例如我們?cè)诘顷懙臅r(shí)候,需要驗(yàn)證碼等。那么在ssm如何實(shí)現(xiàn)校驗(yàn)登錄呢?將通過(guò)下面的詳細(xì)內(nèi)容,為大家展示如何在ssm中使用token來(lái)實(shí)現(xiàn)校驗(yàn)登錄的功能。

背景

token的意思是“令牌”,是服務(wù)端生成的一串字符串,作為客戶端進(jìn)行請(qǐng)求的一個(gè)標(biāo)識(shí)。
當(dāng)用戶第一次登錄后,服務(wù)器生成一個(gè)token并將此token返回給客戶端,以后客戶端只需帶上這個(gè)token前來(lái)請(qǐng)求數(shù)據(jù)即可,無(wú)需再次帶上用戶名和密碼。
簡(jiǎn)單token的組成;uid(用戶唯一的身份標(biāo)識(shí))、time(當(dāng)前時(shí)間的時(shí)間戳)、sign(簽名,token的前幾位以哈希算法壓縮成的一定長(zhǎng)度的十六進(jìn)制字符串。為防止token泄露)

使用場(chǎng)景

  •  token 還能起到反爬蟲(chóng)的作用,當(dāng)然爬蟲(chóng)也是有突破的方法的,盡管如此還是能減少一部分爬蟲(chóng)訪問(wèn)服務(wù)器的所帶來(lái)的負(fù)載。相對(duì)的爬蟲(chóng)技術(shù)門(mén)檻變高了。
  • 使用session也能達(dá)到用戶驗(yàn)證的目的 、但是session 是消耗服務(wù)器的內(nèi)存,在對(duì)性能要求較高的項(xiàng)目中 ,開(kāi)發(fā)中該技術(shù)相較于token已經(jīng)過(guò)時(shí)

補(bǔ)充

  • token主要使用于在廣大的安卓開(kāi)發(fā)中
  • 使用springmvc 中攔截器實(shí)現(xiàn)

使用方法

在maven ssm項(xiàng)目中pom.xml 配置 中引用jar包

2021042112012257

		<!--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 {
    /**
     * 過(guò)期時(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中的信息無(wú)需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后過(guò)期
     *
     * @param username 用戶名
     * @return 加密的token
     */
    public static String sign(String username,String userId) {
        try {
//            過(guò)期時(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 {

    /**
     * 攔截器和過(guò)濾器的區(qū)別
     * 1.攔截器針對(duì)訪問(wèn)控制器進(jìn)行攔截
     * 及 @RequestMapping(value = {"/test"})
     * 簡(jiǎn)而言說(shuō)就是訪問(wèn)方法的url
     * 應(yīng)用:可以作為權(quán)限的判斷,
     * 2.過(guò)濾器則是針對(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;
        }
        //如果沒(méi)有登錄,則跳轉(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):通過(guò)將請(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配置攔截器:

2021042112012258

			<!--自定義攔截器-->
            <mvc:interceptors>
                <!--		驗(yàn)證是否登錄 通過(guò)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ù)庫(kù),登錄
 				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工具來(lái)實(shí)現(xiàn)校驗(yàn)登錄功能的文章就介紹到此結(jié)束了,還想了解更多關(guān)于SSM框架的其他內(nèi)容,可以多多關(guān)注W3Cschool相關(guān)文章。

0 人點(diǎn)贊