springboot+jwt

1.pom

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

2.JwtFilterConfig

@Configuration
public class JwtFilterConfig {

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

3.JwtAuthenticationFilter

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());
    }

}

4.JwtUtil

public class JwtUtil {

    private static final String SECRET = "xxxxxxxxxxxxxxxxxxx";

    private static final String ID_IN_TOKEN = "id";
    private static final String NAME_IN_TOKEN = "name";

    /**
     * 生成token
     * @param data
     * @return
     */
    public static String generateToken(String data) {
        HashMap<String, Object> map = new HashMap<>();
        //you can put any data in the map
//        map.put(ID_IN_TOKEN, data);
        map.put(NAME_IN_TOKEN, data);
        String jwt = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 3600_000_00L))// 1000 hour
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        return jwt;
    }

    /**
     * 验证token
     * @param token
     */
    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获得CustomerId
     * @param token
     * @return
     */
    public static int getCustomerId(String token){
        Map<String, Object> body = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
        return Integer.parseInt(body.get(ID_IN_TOKEN).toString());
    }

    /**
     * 解析token获得LoginName
     * @param token
     * @return
     */
    public static String getLoginName(String token){
        Map<String, Object> body = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
        return body.get(NAME_IN_TOKEN).toString();
    }
}

5.登录时生成token,调用接口时解析验证token

        // 登录时 用户是用id做token
        String token = JwtUtil.generateToken(customer.getId().toString());
        // 或者
        String token = JwtUtil.generateToken(customer.getUsername().toString());
		// 调用接口时,取出token中的信息
        int customerId = JwtUtil.getCustomerId(request.getParameter("token"));
        // 或者
        String loginName = JwtUtil.getLoginName(request.getParameter("token"));

你可能感兴趣的:(demo)