2017-07-15 95 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