JWTCredentialsMatcher.java 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package com.yaozhitech.spring5.jwt;
  2. import java.io.UnsupportedEncodingException;
  3. import org.apache.shiro.authc.AuthenticationInfo;
  4. import org.apache.shiro.authc.AuthenticationToken;
  5. import org.apache.shiro.authc.credential.CredentialsMatcher;
  6. import com.auth0.jwt.JWT;
  7. import com.auth0.jwt.JWTVerifier;
  8. import com.auth0.jwt.algorithms.Algorithm;
  9. import com.auth0.jwt.exceptions.JWTVerificationException;
  10. import com.yaozhitech.spring5.dto.UserDto;
  11. import lombok.extern.slf4j.Slf4j;
  12. @Slf4j
  13. public class JWTCredentialsMatcher implements CredentialsMatcher {
  14. @Override
  15. public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
  16. String token = (String) authenticationToken.getCredentials();
  17. Object stored = authenticationInfo.getCredentials();
  18. String salt = stored.toString();
  19. UserDto user = (UserDto)authenticationInfo.getPrincipals().getPrimaryPrincipal();
  20. try {
  21. Algorithm algorithm = Algorithm.HMAC256(salt);
  22. JWTVerifier verifier = JWT.require(algorithm)
  23. .withClaim("username", user.getUsername())
  24. .build();
  25. verifier.verify(token);
  26. return true;
  27. } catch (UnsupportedEncodingException | JWTVerificationException e) {
  28. log.error("Token Error:{}", e.getMessage());
  29. }
  30. return false;
  31. }
  32. }