天天看點

springboot結合jwt實作基于restful接口的身份認證

基于restful接口的身份認證,可以采用jwt的方式實作,想了解jwt,可以查詢相關資料,這裡不做介紹~

下面直接看如何實作

1、首先添加jwt的jar包,pom.xml中添加依賴包:

<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>      

2、添加工具類JwtUtil.java:

package com.demo.news.common;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    static final String SECRET = "ThisIsASecret";

    public static String generateToken(String username) {
        HashMap<String, Object> map = new HashMap<>();
        //you can put any data in the map
        map.put("username", username);
        String jwt = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 3600_000_000L))// 1000 hour
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        return "Bearer "+jwt; //jwt前面一般都會加Bearer
    }

    public static void validateToken(String token) {
        try {
            // parse the token.
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace("Bearer ",""))
                    .getBody();
        }catch (Exception e){
            throw new IllegalStateException("Invalid Token. "+e.getMessage());
        }
    }
}      

這個工具類有兩個方法,一個生成token,一個驗證token

添加過濾器JwtAuthenticationFilter.java

package com.demo.news.common;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            if(isProtectedUrl(request)) {
                String token = request.getParameter("token");
                //檢查jwt令牌, 如果令牌不合法或者過期, 裡面會直接抛出異常, 下面的catch部分會直接傳回
                JwtUtil.validateToken(token);
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }
        //如果jwt令牌通過了檢測, 那麼就把request傳遞給後面的RESTful api
        filterChain.doFilter(request, response);
    }


    //我們隻對位址 /api 開頭的api檢查jwt. 不然的話登入/login也需要jwt
    private boolean isProtectedUrl(HttpServletRequest request) {
        return pathMatcher.match("/api/**", request.getServletPath());
    }

}      

這個過濾器會過濾所有以api打頭的路徑

注冊過濾器MyJwtFilter.java

package com.demo.news.common;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyJwtFilter {
    
    @Bean
    public FilterRegistrationBean jwtFilter() {
        final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
        registrationBean.setFilter(filter);
        return registrationBean;
    }

}      

3、開始使用

通過之前的代碼,所有路徑以api開頭的請求如果不添加token參數都會報沒有權限的錯誤,說明過濾器已經生效了

springboot結合jwt實作基于restful接口的身份認證

下面我們根據使用者名和密碼來驗證使用者身份,如果使用者身份通過驗證,那個生成token,拿到這個token,路徑以api打頭的請求添加上這個token參數

驗證使用者身份的代碼:

if(使用者驗證成功) {
    String token = JwtUtil.generateToken(user.getUsername());
}      

拿到這個token,在路徑以api打頭的請求上添加上這個token,比如:

http://localhost:8083/news/api/list?token=Bearer eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NTM2MjQxMzgsInVzZXJuYW1lIjoiYWRtaW4ifQ.FQsNIr_b9105CoV-jx8k9lgtyJ6cM_z48g1fQeSUBowkOGBk-OXGdgtVa1215lD75U3N3tF3yZs10MtJ7kZstA