Spring Security基本源码解析(超精细版)

发布于:2024-07-03 ⋅ 阅读:(137) ⋅ 点赞:(0)

一、基本源码解析

1.1 UsernamePasswordAuthenticationFilter

用户名称和密码的过滤器

浏览器发送用户名称和密码 ----》 经过过滤器「UsernamePasswordAuthenticationFitler」

1.2 UsernamePasswordAuthenticationFilter核心方法

重写父类「AbstractAuthenticationProcessingFilter.java」当中的抽象方法.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException {
    if (this.postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }
    String username = obtainUsername(request);
    username = (username != null) ? username.trim() : "";
    String password = obtainPassword(request);
    password = (password != null) ? password : "";
    UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,password);
    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);
    // 调用认证方法.
    return this.getAuthenticationManager().authenticate(authRequest);
}

1.3 AuthenticationManager「重点」

认证管理器.

this.getAuthenticationManager(), 这里获取的是实现类的对象.

protected AuthenticationManager getAuthenticationManager() {
    return this.authenticationManager;
}
​
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
}

AuthenticationManager接口源码

public interface AuthenticationManager {
    // 核心认证方法.
    // 参数: Authentication, 认证接口
    // 返回值: Authentication, 认证接口
    Authentication authenticate(Authentication authentication) throws AuthenticationException; 
}

实现类

1.4 Authentication接口

认证接口.

// 认证接口.
public interface Authentication extends Principal, Serializable {
    // 获取所有的权限
    Collection<? extends GrantedAuthority> getAuthorities();
    // 用户凭证, 通常这里指的密码.
    Object getCredentials();
    // 存储有关身份验证请求的其他详细信息。这些可能是 IP 地址、证书序列号等。
    Object getDetails();
    // 要进行身份验证的主体的身份。对于带有用户名和密码的身份验证请求,这将是用户名。调用方应填充身份验证请求的主体。
    // AuthenticationManager 实现通常会返回包含更丰富信息的身份验证作为应用程序使用的主体。许多身份验证提供程序将创建一个UserDetails对象作为主体。
    // 返回:
    // Principal被身份验证或身份验证后的身份验证主体。
    Object getPrincipal();
    // 是否已经认证过
    boolean isAuthenticated();
    // 有关完整说明,请参阅 isAuthenticated() 。
    // 实现应 始终 允许使用参数调用 false 此方法,因为各种类使用它来指定不应信任的身份验证令牌。如果实现希望拒绝带有参数的 true 调用(这将指示身份验证令牌受信任 - 潜在的安全风险),则实现应抛出 IllegalArgumentException.
    void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
}

1.5 ProviderManager

// AuthenticationManager接口的实现类. 一般情况下都会这东西.
public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean {
    // 存放各种各样的providers的集合.
    private List<AuthenticationProvider> providers = Collections.emptyList();
 
    // 核心认证方法.
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Class<? extends Authentication> toTest = authentication.getClass();
        AuthenticationException lastException = null;
        AuthenticationException parentException = null;
        Authentication result = null;
        Authentication parentResult = null;
        int currentPosition = 0;
        int size = this.providers.size();
        for (AuthenticationProvider provider : getProviders()) {
            if (!provider.supports(toTest)) {
                continue;
            }
            if (logger.isTraceEnabled()) {
                logger.trace(LogMessage.format("Authenticating request with %s (%d/%d)",
                        provider.getClass().getSimpleName(), ++currentPosition, size));
            }
            try {
                // 执行各种各样的认证.
                result = provider.authenticate(authentication);
                if (result != null) {
                    copyDetails(authentication, result);
                    break;
                }
            }
            catch (AccountStatusException | InternalAuthenticationServiceException ex) {
                prepareException(ex, authentication);
                // SEC-546: Avoid polling additional providers if auth failure is due to
                // invalid account status
                throw ex;
            }
            catch (AuthenticationException ex) {
                lastException = ex;
            }
        }
        if (result == null && this.parent != null) {
            // Allow the parent to try.
            try {
                parentResult = this.parent.authenticate(authentication);
                result = parentResult;
            }
            catch (ProviderNotFoundException ex) {
                // ignore as we will throw below if no other exception occurred prior to
                // calling parent and the parent
                // may throw ProviderNotFound even though a provider in the child already
                // handled the request
            }
            catch (AuthenticationException ex) {
                parentException = ex;
                lastException = ex;
            }
        }
        if (result != null) {
            if (this.eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) {
                // Authentication is complete. Remove credentials and other secret data
                // from authentication
                ((CredentialsContainer) result).eraseCredentials();
            }
            // If the parent AuthenticationManager was attempted and successful then it
            // will publish an AuthenticationSuccessEvent
            // This check prevents a duplicate AuthenticationSuccessEvent if the parent
            // AuthenticationManager already published it
            if (parentResult == null) {
                this.eventPublisher.publishAuthenticationSuccess(result);
            }
​
            return result;
        }
​
        // Parent was null, or didn't authenticate (or throw an exception).
        if (lastException == null) {
            lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound",
                    new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}"));
        }
        // If the parent AuthenticationManager was attempted and failed then it will
        // publish an AbstractAuthenticationFailureEvent
        // This check prevents a duplicate AbstractAuthenticationFailureEvent if the
        // parent AuthenticationManager already published it
        if (parentException == null) {
            prepareException(lastException, authentication);
        }
        throw lastException;
    }
}

1.6 AuthenticationProvider

提供各种认证器.它是一个接口.

public interface AuthenticationProvider {
    // 使用与 相同的 AuthenticationManager.authenticate(Authentication) 协定执行身份验证。
    // 参数:
    // authentication – 身份验证请求对象。
    // 返回:
    // 包含凭据的完全身份验证的对象。如果 无法支持对传递Authentication的对象进行身份验证,则AuthenticationProvider可能返回null。在这种情况下,将尝试下一个AuthenticationProvider支持所呈现Authentication类的方法。
    // 抛出:
    // AuthenticationException – 如果身份验证失败。
    Authentication authenticate(Authentication authentication) throws AuthenticationException;
    
    // 如果支持AuthenticationProvider指示Authentication的对象,则返回true。
    // 返回并不true保证 将AuthenticationProvider能够对所呈现的类实例Authentication进行身份验证。它只是表明它可以支持对它的更仔细的评估。仍然可以从该方法返回 null authenticate(Authentication) can AuthenticationProvider 以指示应尝试另一个AuthenticationProvider方法。
    // 选择能够执行身份验证的在AuthenticationProvider运行时进行。ProviderManager
    // 参数:
    // authentication
    // 返回:
    // true 如果实现可以更仔细地评估所呈现的 Authentication 类
    boolean supports(Class<?> authentication);
}

这里般用的是: DaoAuthenticationProvider.

1.7 UserDetailsService 「重要」

  • 加载用户特定数据的核心界面。它在整个框架中用作用户 DAO,并且是 .DaoAuthenticationProvider该接口只需要一种只读方法,这简化了对新数据访问策略的支持。另请参阅:org.springframework.security.authentication.dao.DaoAuthenticationProvider, UserDetails

public interface UserDetailsService {
    // 根据用户名定位用户。在实际实现中,搜索可能区分大小写或不区分大小写,具体取决于实现实例的配置方式。在这种情况下, UserDetails 返回的对象可能具有与实际请求的用户名不同的大小写。
    // 参数:
    // username – 标识需要其数据的用户的用户名。
    // 返回:
    // 完全填充的用户记录(从不 null)
    // 抛出:
    // UsernameNotFoundException – 如果找不到用户或用户没有授权
    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

1.8 UserDetails 「重要」

实现类是User对象,这个User由spring security提供的.

提供核心用户信息。出于安全目的,Spring 安全性不会直接使用实现。它们只是存储用户信息,这些信息随后封装到对象中 Authentication 。这允许将非安全相关的用户信息(例如电子邮件地址、电话号码等)存储在方便的位置。具体的实现必须特别注意确保强制执行针对每种方法详述的非空协定。有关参考实现(您可能希望在代码中扩展或使用),请参阅 User 。

public interface UserDetails extends Serializable {
​
    /**
     * Returns the authorities granted to the user. Cannot return <code>null</code>.
     * @return the authorities, sorted by natural key (never <code>null</code>)
     */
    Collection<? extends GrantedAuthority> getAuthorities();
​
    String getPassword();
    String getUsername();
    boolean isAccountNonExpired();
    boolean isAccountNonLocked();
    boolean isCredentialsNonExpired();
    boolean isEnabled();
}