1.jwt :java web token。所谓token 就是根据用户信息(用户名,密码等)加密形成唯一的字符串,这个字符串可以经过解析后 得到用户信息,token 有2种情况,一种是保存在后端redis,一种是保存在前端。jwt就是保存在前端的token,这样浏览器有了用户的信息(token),就可以访问同个公司不同的系统,这个就是单点登录(前提是这个公司支持单点登录)。 所以,jwt,记住2点就行:1)携带用户信息的字符串,2)保存在客户端可用于单点登录。
2.token 什么时候产生: 用户登录后产生(有了用户信息后,我们就可以根据不同用户,去控制他们的权限,如管理员就可以访问管理员的页面,普通会员不能访问)
代码:
1)新建一个springboot项目 jwteasydemo:
建3个类:
pom加入几个jar包:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
jwtUtil 里面有生成jwt和解析jwt的方法,可以重点看下,这个我是拿别人来用的。
package com.example.jwteasydemo.pojo;
public class User {
/**
* 用户id
*/
private int userId;
/**
* 用户名
*/
private String username;
/**
* 用户密码
*/
private String password;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
import com.example.jwteasydemo.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class JwtUtil {
/**
* 生成密钥
* @return SecretKey
*/
private static SecretKey generalKey(){
String stringKey = "7786df7fc3a34e26a61c034d5ec8245d";
byte[] encodedKey = Base64.decodeBase64(stringKey);
SecretKey secretKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return secretKey;
// SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
// return key;
}
/**
* 根据用户信息为其签发tocken
* @param user
* @return String
*/
public static String generalTocken(User user){
try {
// 设置签发算法
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
// 生成密钥
SecretKey key = generalKey();
// System.out.println("签发时生成的key为:" + key);
// 设置私有声明
Map<String, Object> claims = new HashMap<>(16);
claims.put("userId", user.getUserId());
claims.put("username", user.getUsername());
// 记录生成JWT的时间
long nowMillis = System.currentTimeMillis();
Date nowTime = new Date(nowMillis);
// 设置过期时间 6分钟
long expMillis = nowMillis + 10 * 60 * 1000;
Date expTime = new Date(expMillis);
// 创建tocken构建器实例
JwtBuilder jwtBuilder = Jwts.builder()
// 设置自己的私有声明
.setClaims(claims)
// 设置该tocken的Id,用于防止tocken重复
.setId(UUID.randomUUID().toString())
// 设置签发者
.setIssuer("FUQI-PC")
// 设置签发时间
.setIssuedAt(nowTime)
// 设置过期时间
.setExpiration(expTime)
// 设置tocken的签发对象
.setSubject("users")
// 设置签发算法和密钥
.signWith(signatureAlgorithm, key);
return jwtBuilder.compact();
} catch (Exception e) {
e.printStackTrace();
return "生成tocken失败";
}
}
/**
* 解析tocken,从中提取出声明信息,里面包含用户信息
* @param tocken
* @return Claims
* @throws Exception
*/
public static Claims parseTocken(String tocken) throws Exception{
SecretKey key = generalKey();
// System.out.println("解析tocken时生成的key为:" + key);
// 获取tocken中的声明部分
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(tocken).getBody();
return claims;
}
}
import com.example.jwteasydemo.pojo.User;
import com.example.jwteasydemo.utils.JwtUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class Controller {
@RequestMapping("/login")
public Map login(User user){
Map result = new HashMap<>();
//1.登录成功后生成jwt
if("abc".equals(user.getUsername()) && "123".equals(user.getPassword())){
String jwt = JwtUtil.generalTocken(user);
result.put("code","1");
result.put("message","登录成功,生成jwt!");
result.put("token",jwt);
}else {//2.失败后不生成jwt,返回错误信息
result.put("code","1");
result.put("message","登录失败,生成jwt!");
}
return result;
}
}
端口默认8080,我有其他项目冲突了改成8081了:
http://localhost:8081/login?username=abc&password=123
有了jwt后(用户的信息),我们就可以对页面和功能进行控制,哪些是用户可以用的,哪些不能用。这里就要用到拦截器,对用户的信息进行拦截,然后进行判断要怎么去控制。