tlias管理系统--登录校验-登录接口生成并下发JWT令牌
This commit is contained in:
@@ -3,12 +3,18 @@ package com.inmind.controller;
|
||||
import com.inmind.pojo.Emp;
|
||||
import com.inmind.pojo.Result;
|
||||
import com.inmind.service.EmpService;
|
||||
import com.inmind.utils.JwtUtils;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
public class LoginController {
|
||||
@@ -21,7 +27,16 @@ public class LoginController {
|
||||
//调用业务层的登录操作
|
||||
Emp e = empService.login(emp);
|
||||
//此时要根据返回的数据,进行登录成功和失败的判断
|
||||
if (e != null) {
|
||||
//生成令牌并下发
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("id", e.getId());
|
||||
claims.put("username", e.getUsername());
|
||||
claims.put("name", e.getName());
|
||||
String jwt = JwtUtils.generateJwt(claims);
|
||||
return Result.success(jwt);
|
||||
}
|
||||
|
||||
return e == null? Result.error("用户名或密码错误"):Result.success();
|
||||
return Result.error("用户名或密码错误");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.inmind.utils;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
public class JwtUtils {
|
||||
|
||||
private static String signKey = "inmind";
|
||||
private static Long expire = 43200000L;
|
||||
|
||||
/**
|
||||
* 生成JWT令牌
|
||||
* @param claims JWT第二部分负载 payload 中存储的内容
|
||||
* @return
|
||||
*/
|
||||
public static String generateJwt(Map<String, Object> claims){
|
||||
String jwt = Jwts.builder()
|
||||
.addClaims(claims)
|
||||
.signWith(SignatureAlgorithm.HS256, signKey)
|
||||
.setExpiration(new Date(System.currentTimeMillis() + expire))
|
||||
.compact();
|
||||
return jwt;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析JWT令牌
|
||||
* @param jwt JWT令牌
|
||||
* @return JWT第二部分负载 payload 中存储的内容
|
||||
*/
|
||||
public static Claims parseJWT(String jwt){
|
||||
Claims claims = Jwts.parser()
|
||||
.setSigningKey(signKey)
|
||||
.parseClaimsJws(jwt)
|
||||
.getBody();
|
||||
return claims;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user