JwtProvider.java 2.93 KB
package com.glsx.usedcar.web;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.glsx.usedcar.module.security.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.summerframework.storage.domain.FileInfo;
import org.summerframework.web.auth.AbstractJwtProvider;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;


/**
 * JWT认证服务
 */
@Slf4j
@Component
public class JwtProvider extends AbstractJwtProvider {

    protected static final String REAL_NAME = "realName";
    protected static final String AVATAR = "avatar";

    /**
     * 生成token
     *
     * @param user user
     * @return token
     */
    public String generateUser(User user) {
        String[] roleCodes = user.getAuthorities().stream().map(GrantedAuthority::getAuthority).toArray(String[]::new);
        try {
            return JWT.create()
                    .withIssuer(jwtProperties.getIssuer())
                    .withIssuedAt(new Date())
                    .withExpiresAt(new Date(System.currentTimeMillis() + jwtProperties.getExpiration() * 1000))
                    .withJWTId(String.valueOf(user.getUserId()))
                    .withSubject(user.getUsername())
                    .withClaim(CLAIM_PASSWORD, user.getPassword())
                    .withArrayClaim(CLAIM_AUTHORITIES, roleCodes)
                    .withClaim(REAL_NAME, user.getRealName())
                    .sign(algorithm);
        } catch (IllegalArgumentException | TokenExpiredException e) {
            return null;
        }
    }

    /**
     * 解析token
     *
     * @param token token
     * @return User
     */
    public User verifyUser(String token) {
        if (token == null) {
            return null;
        }
        try {
            DecodedJWT jwt = verifier.verify(token);
            // 获取用户的权限
            String[] roles = jwt.getClaim(CLAIM_AUTHORITIES).asArray(String.class);
            String password = jwt.getClaim(CLAIM_PASSWORD).asString();
            String realName = jwt.getClaim(REAL_NAME).asString();
            String avatar = jwt.getClaim(AVATAR).asString();
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            for (String securityRole : roles) {
                grantedAuthorities.add(new SimpleGrantedAuthority(securityRole));
            }
            User user = new User(Integer.parseInt(jwt.getId()), jwt.getSubject(), grantedAuthorities);
            user.setRealName(realName);
            FileInfo empty = FileInfo.empty();
            empty.setFilePath(avatar);
//        user.setAvatar(empty);
            user.setPassword(password);
            return user;
        } catch (Exception e) {
            return null;
        }
    }


}