123456789101112131415161718192021222324252627282930313233343536373839404142 |
- package com.yaozhitech.spring5.jwt;
- import java.io.UnsupportedEncodingException;
- import org.apache.shiro.authc.AuthenticationInfo;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.credential.CredentialsMatcher;
- import com.auth0.jwt.JWT;
- import com.auth0.jwt.JWTVerifier;
- import com.auth0.jwt.algorithms.Algorithm;
- import com.auth0.jwt.exceptions.JWTVerificationException;
- import com.yaozhitech.spring5.dto.UserDto;
- import lombok.extern.slf4j.Slf4j;
- @Slf4j
- public class JWTCredentialsMatcher implements CredentialsMatcher {
-
- @Override
- public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
- String token = (String) authenticationToken.getCredentials();
- Object stored = authenticationInfo.getCredentials();
- String salt = stored.toString();
- UserDto user = (UserDto)authenticationInfo.getPrincipals().getPrimaryPrincipal();
- try {
- Algorithm algorithm = Algorithm.HMAC256(salt);
- JWTVerifier verifier = JWT.require(algorithm)
- .withClaim("username", user.getUsername())
- .build();
- verifier.verify(token);
- return true;
- } catch (UnsupportedEncodingException | JWTVerificationException e) {
- log.error("Token Error:{}", e.getMessage());
- }
- return false;
- }
- }
|