IFastModularRealm.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package com.ifast.common.shiro.realm;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.shiro.authc.AuthenticationException;
  4. import org.apache.shiro.authc.AuthenticationInfo;
  5. import org.apache.shiro.authc.AuthenticationToken;
  6. import org.apache.shiro.authc.UnknownAccountException;
  7. import org.apache.shiro.authc.pam.AuthenticationStrategy;
  8. import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
  9. import org.apache.shiro.authc.pam.UnsupportedTokenException;
  10. import org.apache.shiro.realm.Realm;
  11. import java.util.Collection;
  12. /**
  13. * <pre>
  14. * </pre>
  15. * <small> 2018年5月1日 | Aron</small>
  16. */
  17. @Slf4j
  18. public class IFastModularRealm extends ModularRealmAuthenticator {
  19. @Override
  20. protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
  21. if (!realm.supports(token)) {
  22. throw new UnsupportedTokenException("不支持的token类型");
  23. }
  24. AuthenticationInfo info = realm.getAuthenticationInfo(token);
  25. if (info == null) {
  26. throw new UnknownAccountException("token无效");
  27. }
  28. return info;
  29. }
  30. @Override
  31. protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
  32. AuthenticationStrategy strategy = getAuthenticationStrategy();
  33. AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
  34. if (log.isTraceEnabled()) {
  35. log.trace("Iterating through {} realms for PAM authentication", realms.size());
  36. }
  37. AuthenticationException ex = null;
  38. for (Realm realm : realms) {
  39. aggregate = strategy.beforeAttempt(realm, token, aggregate);
  40. if (realm.supports(token)) {
  41. AuthenticationInfo info = null;
  42. try {
  43. info = realm.getAuthenticationInfo(token);
  44. } catch (AuthenticationException e) {
  45. e.printStackTrace();
  46. ex = e;
  47. }
  48. aggregate = strategy.afterAttempt(realm, token, info, aggregate, ex);
  49. } else {
  50. log.debug("Realm [{}] does not support token {}. Skipping realm.", realm, token);
  51. }
  52. }
  53. try {
  54. aggregate = strategy.afterAllAttempts(token, aggregate);
  55. } catch (Exception e) {
  56. log.debug(e.getMessage());
  57. }
  58. if (ex != null){
  59. throw ex;
  60. }
  61. return aggregate;
  62. }
  63. }