48 lines
1.6 KiB
Java
48 lines
1.6 KiB
Java
package com.wuyiqi.netstateproc.config.shiro;
|
|
|
|
import com.auth0.jwt.JWT;
|
|
import com.auth0.jwt.algorithms.Algorithm;
|
|
import com.auth0.jwt.exceptions.JWTVerificationException;
|
|
import com.auth0.jwt.interfaces.JWTVerifier;
|
|
import com.auth0.jwt.interfaces.Payload;
|
|
import com.wuyiqi.netstateproc.convert.JwtConvert;
|
|
import lombok.Data;
|
|
import lombok.RequiredArgsConstructor;
|
|
import org.apache.shiro.authc.AuthenticationToken;
|
|
import org.apache.shiro.crypto.hash.Sha256Hash;
|
|
import org.mapstruct.factory.Mappers;
|
|
|
|
import java.time.Instant;
|
|
import java.util.List;
|
|
|
|
@Data
|
|
public class JwtToken implements AuthenticationToken {
|
|
|
|
private String token;
|
|
|
|
private String secret;
|
|
|
|
private static final JwtConvert jwtConvert = Mappers.getMapper(JwtConvert.class);
|
|
|
|
@Override
|
|
public String getPrincipal() {
|
|
return JWT.decode(token).getSubject();
|
|
}
|
|
|
|
@Override
|
|
public Payload getCredentials() throws JWTVerificationException {
|
|
Algorithm algorithm = Algorithm.HMAC256(Sha256Hash.toString(secret.getBytes()));
|
|
JWTVerifier verifier = JWT.require(algorithm).build();
|
|
return verifier.verify(token);
|
|
}
|
|
|
|
public static String generate(String subject, Long expire, List<Integer> rules, String secret) {
|
|
Algorithm algorithm = Algorithm.HMAC256(Sha256Hash.toString(secret.getBytes()));
|
|
Claims claims = new Claims(subject, Instant.now().plusSeconds(expire), Instant.now(), rules);
|
|
return JWT.create().withPayload(jwtConvert.conv2Map(claims)).sign(algorithm);
|
|
}
|
|
|
|
public record Claims(String subject, Instant expiresAt, Instant issuedAt, List<Integer> roles) {}
|
|
|
|
}
|