springboot token签名

使用JWT(JSON WEB TOKEN)工具, <artifactId>jjwt</artifactId>

生成token方式

package com.travelsky.auto.token;

import com.travelsky.config.TokenConfig;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * token工厂
 */
@Component
@Slf4j
public class TokenFactory {

    @Autowired
    private TokenConfig tokenConfig;

    /**
     * 生成token
     * @param key
     * @return
     */
    public TokenContent createToken(final String key) {
        final LocalDateTime now = LocalDateTime.now();
        // Claims保存主题信息
        final Claims claims = Jwts.claims().setSubject(tokenConfig.getSubject());
        final String token = Jwts.builder()
                // 设置信息
                .setClaims(claims)
                // 设置主体
                .setIssuer(tokenConfig.getIssuer())
                // 设置创建时间
                .setIssuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()))
                // 设置过期时间
                .setExpiration(Date.from(now.plusMinutes(tokenConfig.getExpiration()).atZone(ZoneId.systemDefault()).toInstant()))
                // 使用HS512加密
                .signWith(SignatureAlgorithm.HS512, key)
                // 生成字符串token
                .compact();
        return new TokenContent(token, claims);
    }

根据前端取回的token进行验证方式

package com.travelsky.auto.token;

import com.travelsky.config.TokenConfig;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * token工厂
 */
@Component
@Slf4j
public class TokenFactory {

    @Autowired
    private TokenConfig tokenConfig;
/**
     * 验证token
     * @param key 与subject一致
     * @param token 页面传回的token字符串
     */
    void parser(final String key, final String token) {
        try {
            // 验证token
            Jwts.parser().setSigningKey(key).parseClaimsJws(token);
        } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
            log.error("不可用Invalid Token", ex);
            throw new BadCredentialsException("验证失败,Token不可用:Invalid token: ", ex);
        } catch (ExpiredJwtException expiredEx) {
            log.info("过期Token is expired", expiredEx);
            throw new ExpiredTokenException("token过期", expiredEx);
        }
    }
}

token配置类

package com.travelsky.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@Data
@ConfigurationProperties(prefix = "token")
public class TokenConfig {

    private String issuer;

    private Long expiration;

    private String subject;
}

token配置文件

token:
  issuer: antlord
  expiration: 20
  subject: token

猜你喜欢

转载自www.cnblogs.com/antlord/p/10283037.html
今日推荐