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後(用戶的信息),我們就可以對頁面和功能進行控制,哪些是用戶可以用的,哪些不能用。這裏就要用到攔截器,對用戶的信息進行攔截,然後進行判斷要怎麼去控制。