JWTShiroRealm.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package com.yaozhitech.spring5.jwt;
  2. import org.apache.shiro.authc.AuthenticationException;
  3. import org.apache.shiro.authc.AuthenticationInfo;
  4. import org.apache.shiro.authc.AuthenticationToken;
  5. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  6. import org.apache.shiro.authz.AuthorizationInfo;
  7. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  8. import org.apache.shiro.realm.AuthorizingRealm;
  9. import org.apache.shiro.subject.PrincipalCollection;
  10. import com.yaozhitech.spring5.dto.UserDto;
  11. import com.yaozhitech.spring5.service.UserService;
  12. import com.yaozhitech.spring5.utils.JwtUtils;
  13. /**
  14. * 自定义身份认证
  15. * 基于HMAC( 散列消息认证码)的控制域
  16. */
  17. public class JWTShiroRealm extends AuthorizingRealm {
  18. protected UserService userService;
  19. private String jwtSalt;
  20. public JWTShiroRealm(UserService userService, String jwtSalt){
  21. this.userService = userService;
  22. this.setCredentialsMatcher(new JWTCredentialsMatcher());
  23. this.jwtSalt = jwtSalt;
  24. }
  25. @Override
  26. public boolean supports(AuthenticationToken token) {
  27. return token instanceof JWTToken;
  28. }
  29. /**
  30. * 认证信息.(身份验证) : Authentication 是用来验证用户身份
  31. * 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
  32. */
  33. @Override
  34. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
  35. JWTToken jwtToken = (JWTToken) authcToken;
  36. String token = jwtToken.getToken();
  37. UserDto user = userService.getJwtTokenInfo(JwtUtils.verifyTokenAndGet(token, jwtSalt));
  38. if(user == null)
  39. throw new AuthenticationException("token过期,请重新登录");
  40. SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getSalt(), "jwtRealm");
  41. return authenticationInfo;
  42. }
  43. @Override
  44. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  45. return new SimpleAuthorizationInfo();
  46. }
  47. }