詳解shrio的認證(登錄)過程

shrio是一個比較輕量級的安全框架,主要的作用是在後端承擔認證和授權的工作。今天就講一下shrio進行認證的一個過程。
首先先介紹一下在認證過程中的幾個關鍵的對象:

  • Subject:主體

訪問系統的用戶,主體可以是用戶、程序等,進行認證的都稱為主體;

  • Principal:身份信息

是主體(subject)進行身份認證的標識,標識必須具有唯一性,如用戶名、手機號、郵箱地址等,一個主體可以有多個身份,但是必須有一個主身份(Primary Principal)。

  • credential:憑證信息

是隻有主體自己知道的安全信息,如密碼、證書等。
接著我們就進入認證的具體過程:
首先是從前端的登錄表單中接收到用戶輸入的token(username + password):

@RequestMapping("/login")
public String login(@RequestBody Map user){
  Subject subject = SecurityUtils.getSubject();
  UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.get("email").toString(), user.get("password").toString());
   try {
      subject.login(usernamePasswordToken);
   } catch (UnknownAccountException e) {
      return "郵箱不存在!";
   } catch (AuthenticationException e) {
      return "賬號或密碼錯誤!";
   }
    return "登錄成功!";
  }

這裡的usernamePasswordToken(以下簡稱token)就是用戶名和密碼的一個結合對象,然後調用subject的login方法將token傳入開始認證過程。
接著會發現subject的login方法調用的其實是securityManager的login方法:

Subject subject = securityManager.login(this, token);

再往下看securityManager的login方法內部:

public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
  AuthenticationInfo info;
   try {
      info = authenticate(token);
   } catch (AuthenticationException ae) {
      try {
        onFailedLogin(token, ae, subject);
   } catch (Exception e) {
        if (log.isInfoEnabled()) {
          log.info("onFailedLogin method threw an " +
              "exception. Logging and propagating original AuthenticationException.", e);
   }
      }
      throw ae; //propagate
   }
    Subject loggedIn = createSubject(token, info, subject);
   onSuccessfulLogin(token, info, loggedIn);
   return loggedIn;
}

上面代碼的關鍵在於:

info = authenticate(token);

即將token傳入authenticate方法中得到一個AuthenticationInfo類型的認證信息。
以下是authenticate方法的具體內容:

public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
  if (token == null) {
    throw new IllegalArgumentException("Method argument (authentication token) cannot be null.");
  }
  log.trace("Authentication attempt received for token [{}]", token);
  AuthenticationInfo info;
  try {
    info = doAuthenticate(token);
  if (info == null) {
      String msg = "No account information found for authentication token [" + token + "] by this " +
          "Authenticator instance. Please check that it is configured correctly.";
  throw new AuthenticationException(msg);
  }
  } catch (Throwable t) {
    AuthenticationException ae = null;
  if (t instanceof AuthenticationException) {
      ae = (AuthenticationException) t;
  }
    if (ae == null) {
      //Exception thrown was not an expected AuthenticationException. Therefore it is probably a little more
  //severe or unexpected. So, wrap in an AuthenticationException, log to warn, and propagate: String msg = "Authentication failed for token submission [" + token + "]. Possible unexpected " +
          "error? (Typical or expected login exceptions should extend from AuthenticationException).";
  ae = new AuthenticationException(msg, t);
  if (log.isWarnEnabled())
        log.warn(msg, t);
  }
    try {
      notifyFailure(token, ae);
  } catch (Throwable t2) {
      if (log.isWarnEnabled()) {
        String msg = "Unable to send notification for failed authentication attempt - listener error?. " +
            "Please check your AuthenticationListener implementation(s). Logging sending exception " +
            "and propagating original AuthenticationException instead...";
  log.warn(msg, t2);
  }
    }
    throw ae;
  }
  log.debug("Authentication successful for token [{}]. Returned account [{}]", token, info);
  notifySuccess(token, info);
  return info;
}

首先就是判斷token是否為空,不為空再將token傳入doAuthenticate方法中:

protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
  assertRealmsConfigured();
  Collection<Realm> realms = getRealms();
  if (realms.size() == 1) {
    return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
  } else {
    return doMultiRealmAuthentication(realms, authenticationToken);
  }
}

這一步是判斷是有單個Reaml驗證還是多個Reaml驗證,單個就執行doSingleRealmAuthentication()方法,多個就執行doMultiRealmAuthentication()方法。
一般情況下是單個驗證:

protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
  if (!realm.supports(token)) {
    String msg = "Realm [" + realm + "] does not support authentication token [" +
        token + "]. Please ensure that the appropriate Realm implementation is " +
        "configured correctly or that the realm accepts AuthenticationTokens of this type.";
    throw new UnsupportedTokenException(msg);
  }
  AuthenticationInfo info = realm.getAuthenticationInfo(token);
  if (info == null) {
    String msg = "Realm [" + realm + "] was unable to find account data for the " +
        "submitted AuthenticationToken [" + token + "].";
    throw new UnknownAccountException(msg);
  }
  return info;
}

這一步中首先判斷是否支持Realm,隻有支持Realm才調用realm.getAuthenticationInfo(token)獲取info。

public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  AuthenticationInfo info = getCachedAuthenticationInfo(token);
  if (info == null) {
    //otherwise not cached, perform the lookup:
    info = doGetAuthenticationInfo(token);
    log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
    if (token != null && info != null) {
      cacheAuthenticationInfoIfPossible(token, info);
    }
  } else {
    log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
  }
  if (info != null) {
    assertCredentialsMatch(token, info);
  } else {
    log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
  }
  return info;
}

首先查看Cache中是否有該token的info,如果有,則直接從Cache中去即可。如果是第一次登錄,則Cache中不會有該token的info,需要調用doGetAuthenticationInfo(token)方法獲取,並將結果加入到Cache中,方便下次使用。而這裡調用的doGetAuthenticationInfo()方法就是我們在自己重寫的方法,具體的內容是自定義瞭對拿到的這個token的一個處理的過程:

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  if (authenticationToken.getPrincipal() == null)
    return null;
  String email = authenticationToken.getPrincipal().toString();
  User user = userService.findByEmail(email);
  if (user == null)
    return null;
  else return new SimpleAuthenticationInfo(email, user.getPassword(), getName());
}

這其中進行瞭幾步判斷:首先是判斷傳入的用戶名是否為空,在判斷傳入的用戶名在本地的數據庫中是否存在,不存在則返回一個用戶名不存在的Exception。以上兩部通過之後生成一個包括傳入用戶名和密碼的info,註意此時關於用戶名的驗證已經完成,接下來進入對密碼的驗證。
將這一步得到的info返回給getAuthenticationInfo方法中的

assertCredentialsMatch(token, info);

此時的info是正確的用戶名和密碼的信息,token是輸入的用戶名和密碼的信息,經過前面步驟的驗證過程,用戶名此時已經是真是存在的瞭,這一步就是驗證輸入的用戶名和密碼的對應關系是否正確。

protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
  CredentialsMatcher cm = getCredentialsMatcher();
  if (cm != null) {
    if (!cm.doCredentialsMatch(token, info)) {
      //not successful - throw an exception to indicate this:
      String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
      throw new IncorrectCredentialsException(msg);
    }
  } 
  else {
    throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +
        "credentials during authentication. If you do not wish for credentials to be examined, you " +
        "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
  }
}

上面步驟就是驗證token中的密碼的和info中的密碼是否對應的代碼。這一步驗證完成之後,整個shrio認證的過程就結束瞭。

以上就是詳解shrio的認證(登錄)過程的詳細內容,更多關於shrio的認證(登錄)過程的資料請關註WalkonNet其它相關文章!