Java实现token的生成与验证-登录功能

一、token与cookie相比较的优势
1、支持跨域访问,将token置于请求头中,而cookie是不支持跨域访问的;

2、无状态化,服务端无需存储token,只需要验证token信息是否正确即可,而session需要在服务端存储,一般是通过cookie中的sessionID在服务端查找对应的session;

3、无需绑定到一个特殊的身份验证方案(传统的用户名密码登陆),只需要生成的token是符合我们预期设定的即可;

4、更适用于移动端(Android,iOS,小程序等等),像这种原生平台不支持cookie,比如说微信小程序,每一次请求都是一次会话,当然我们可以每次去手动为他添加cookie,详情请查看博主另一篇博客;

5、避免CSRF跨站伪造攻击,还是因为不依赖cookie;

二、基于JWT的token认证实现
JWT:JSON Web Token,其实token就是一段字符串,由三部分组成:Header,Payload,Signature

1、引入依赖

1
2
3
4
5
<dependency>
      <groupId>com.auth0</groupId>
      <artifactId>java-jwt</artifactId>
      <version>3.8.2</version>
</dependency>

2、完整工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.hospital.total_managed.utils;

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.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * token工具类
 */
public class TokenUtils {<!-- -->

    //设置过期时间
    private static final long EXPIRE_DATE=1 * 60 * 1000;
    //token秘钥
    private static final String TOKEN_SECRET = "DeepenLin77543DeepenLin77543";

    //实现签名方法
    public static String token (String username,String password){<!-- -->

        String token = "";
        try {<!-- -->
            //这里将useName 和 password 存入了Token,在下面的解析中,也会有解析的方法可以获取到Token里面的数据
            //Token过期的时间
            //过期时间
            Date date = new Date(System.currentTimeMillis()+EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息,类型以及签名所用的算法
            Map<String,Object> header = new HashMap<>();
            header.put("typ","JWT");
            header.put("alg","HS256");
            //携带username,password信息,存入token,生成签名
            token = JWT.create()
                    .withHeader(header)
                    //存储自己想要留给前端的内容
                    .withClaim("username",username)
                    .withClaim("password",password).withExpiresAt(date)
                    .sign(algorithm);
        }catch (Exception e){<!-- -->
            e.printStackTrace();
            return  null;
        }
        return token;
    }
    //验证token
    public static boolean verify(String token){<!-- -->
        /**
         * @desc   验证token,通过返回true
         * @params [token]需要校验的串
         **/
        try {<!-- -->
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){<!-- -->
            e.printStackTrace();
            System.out.println("Token超时,需要重新登录");
        }
        return false;
    }

    /**
     * 获取token中信息 userName
     * @param token
     * @return
     */

    public static String getUsername(String token){<!-- -->
        try {<!-- -->
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userName").asString();

        }catch (JWTDecodeException e){<!-- -->
            e.printStackTrace();
        }
        return null;
    }

//    //测试
//    public static void main(String[] args) {<!-- -->
//        String username ="zhangsan";
//        String password = "123";
//        String token = token(username,password);
//        System.out.println(token);
//        boolean b = verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMyIsImV4cCI6MTYwNTY5NzExNiwidXNlcm5hbWUiOiJ6aGFuZ3NhbiJ9.8l9gHPvXMut7HjfIT2vG0Dv3kTM9Cs6q0axRTPWqcO4");
//        System.out.println(b);
//    }

}

转自:https://www.cnblogs.com/achengmu/p/12693260.html