常见认证机制学习(五)

2023-10-13 11:28:39 浏览数 (2)

5.3 JWT工具类

在ihrm_common工程中创建JwtUtil工具类

代码语言:javascript复制
@ConfigurationProperties("jwt.config")
public class JwtUtil {
    private String key;
    private long ttl;
    public String getKey() {
        return key;
   }
    public void setKey(String key) {
        this.key = key;
   }
    public long getTtl() {
        return ttl;
   }
    public void setTtl(long ttl) {
        this.ttl = ttl;
   }
    /**
     * 签发 token
     */
    public String createJWT(String id, String subject,Map<String,Object> map){
        long now=System.currentTimeMillis();
        long exp=now ttl;
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
               .setSubject(subject).setIssuedAt(new Date())
               .signWith(SignatureAlgorithm.HS256, key);
        for(Map.Entry<String,Object> entry:map.entrySet()) {
            jwtBuilder.claim(entry.getKey(),entry.getValue());
       }
        if(ttl>0){
            jwtBuilder.setExpiration( new Date(exp));
       }
        String token = jwtBuilder.compact();
        return token;
   }
    /** 
        * 解析JWT
     * @param token
     * @return
     */
    public Claims parseJWT(String token){
        Claims claims = null;
        try {
            claims = Jwts.parser()
                   .setSigningKey(key)
                   .parseClaimsJws(token).getBody();
       }catch (Exception e){
       }
        return claims;
   }
}

(3) 修改ihrm_common工程的application.yml, 添加配置

代码语言:javascript复制
jwt:
 config:
    key: saas-ihrm
    ttl: 360000

5.4 登录成功签发token

(1)配置JwtUtil。修改ihrm_system工程的启动类

代码语言:javascript复制
@Bean    
public JwtUtil jwtUtil(){    
 return new util.JwtUtil();        
}

(2)添加登录方法

代码语言:javascript复制
   /**
     * 用户登录
     * 1.通过service根据mobile查询用户
     * 2.比较password
     * 3.生成jwt信息
     *
     */
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public Result login(@RequestBody Map<String,String> loginMap) {
        String mobile = loginMap.get("mobile");
        String password = loginMap.get("password");
        User user = userService.findByMobile(mobile);
        //登录失败
        if(user == null || !user.getPassword().equals(password)) {
            return new Result(ResultCode.MOBILEORPASSWORDERROR);
       }else { 
        
         //登录成功
            Map<String,Object> map = new HashMap<>();
            map.put("companyId",user.getCompanyId());
            map.put("companyName",user.getCompanyName());
            String token = jwtUtils.createJwt(user.getId(), user.getUsername(), map);
            return new Result(ResultCode.SUCCESS,token);
       }
   }

(3)测试运行结果

使用postman验证登录返回:

代码语言:javascript复制
{"success":true,"code":10000,"message":"操作成
功!","data":"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMDYyNjYxODkxNjE4Mzc3NzI4Iiwic3ViIjoiemhhb
mdzYW4iLCJpYXQiOjE1NDI0NjgzNzcsImNvbXBhbnlJZCI6IjEiLCJjb21wYW55TmFtZSI6IuS8oOaZuuaSreWu
oiIsImV4cCI6MTU0MjU1NDc3N30.J-8uv8jOp2GMLpBwrUOksnErjA4-DOJ_qvy7tsJbsa8"}

0 人点赞