2017-07-15 154 views
-1

爲什麼在發生異常之後調用超類方法?如果發生異常,調用堆棧將返回給調用者而不是執行超類方法?Spring Security UsernamePasswordAuthenticationToken在調用超類方法之前拋出異常

public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { 
     if (isAuthenticated) { 
      throw new IllegalArgumentException(
        "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); 
     } 

     super.setAuthenticated(false); 
    } 

https://github.com/spring-projects/spring-security/blob/master/core/src/main/java/org/springframework/security/authentication/UsernamePasswordAuthenticationToken.java

+1

爲什麼會出現向下投票呢? – youcanlearnanything

回答

1

在UsernamePasswordAuthenticationToken類setAuthenticated(布爾isAuthenticated)方法被覆蓋AbstractAuthenticationToken類的方法。

在此類中設置私有身份驗證屬性的唯一方法是通過其super.setAuthenticated(boolean authenticated)方法。

setAuthenticated方法的重寫此行爲可以確保它只能通過它的構造函數中的一個設置爲true:

public UsernamePasswordAuthenticationToken(Object principal, Object credentials, 
      Collection<? extends GrantedAuthority> authorities) { 
     super(authorities); 
     this.principal = principal; 
     this.credentials = credentials; 
     super.setAuthenticated(true); // must use super, as we override 
} 

而且它不允許設置身份驗證屬性爲true明確。

關於父類方法的調用,有一個構造函數,利用這個功能:

public UsernamePasswordAuthenticationToken(Object principal, Object credentials) { 
     super(null); 
     this.principal = principal; 
     this.credentials = credentials; 
     setAuthenticated(false); 
} 
+0

我瞭解代碼,但我想知道爲什麼在super方法之前處理異常。 – youcanlearnanything