JWTModularRealmAuthenticator.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.dk.oauth.shiro.realm;
  2. import com.dk.oauth.shiro.jwt.JWTToken;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.shiro.authc.AuthenticationException;
  5. import org.apache.shiro.authc.AuthenticationInfo;
  6. import org.apache.shiro.authc.AuthenticationToken;
  7. import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
  8. import org.apache.shiro.realm.Realm;
  9. import java.util.ArrayList;
  10. import java.util.Collection;
  11. import java.util.List;
  12. /**
  13. * 当配置了多个Realm时,我们通常使用的认证器是shiro自带的org.apache.shiro.authc.pam.ModularRealmAuthenticator,其中决定使用的Realm的是doAuthenticate()方法
  14. * <p>
  15. * 自定义Authenticator,通过grantType进行判断
  16. */
  17. @Slf4j
  18. public class JWTModularRealmAuthenticator extends ModularRealmAuthenticator {
  19. @Override
  20. protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
  21. throws AuthenticationException {
  22. log.info("JWTModularRealmAuthenticator:method doAuthenticate() execute ");
  23. // 判断getRealms()是否返回为空
  24. assertRealmsConfigured();
  25. // 强制转换回自定义的CustomizedToken
  26. //UserToken userToken = (UserToken) authenticationToken;
  27. JWTToken jwtToken = (JWTToken) authenticationToken;
  28. // 登录类型
  29. String grantType = jwtToken.getGrantType();
  30. // 所有Realm
  31. Collection<Realm> realms = getRealms();
  32. // 登录类型对应的所有Realm
  33. List<Realm> typeRealms = new ArrayList<>();
  34. for (Realm realm : realms) {
  35. CustomeRealm customeRealm = (CustomeRealm) realm;
  36. if (customeRealm.getGrantType().contains(grantType)) {
  37. typeRealms.add(realm);
  38. }
  39. }
  40. // 判断是单Realm还是多Realm
  41. if (typeRealms.size() == 1) {
  42. log.info("doSingleRealmAuthentication() execute ");
  43. return doSingleRealmAuthentication(typeRealms.get(0), jwtToken);
  44. } else {
  45. log.info("doMultiRealmAuthentication() execute ");
  46. return doMultiRealmAuthentication(typeRealms, jwtToken);
  47. }
  48. }
  49. }