Spring Security UsernamePasswordAuthenticationToken在调用超类方法之前抛出异常

时间:2017-07-15 03:45:21

标签: java spring spring-security

为什么在发生异常后会调用超类方法?如果发生异常,调用堆栈将返回调用者而不是执行超类方法?

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 个答案:

答案 0 :(得分:1)

UsernamePasswordAuthenticationToken类中的setAuthenticated(boolean isAuthenticated)方法是AbstractAuthenticationToken类的重写方法。

在此类中设置私有身份验证属性的唯一方法是通过其super.setAuthenticated(布尔身份验证)方法。

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);
}