认证源码分析与自定义后端认证逻辑

简介: 本文深入分析Spring Security认证流程,从UsernamePasswordAuthenticationFilter过滤器入手,解析用户登录请求如何通过AuthenticationManager委托给AuthenticationProvider进行认证,最终由UserDetailsService加载用户信息并完成身份验证的全过程,揭示自定义认证逻辑的关键实现点。

认证流程分析
UsernamePasswordAuthenticationFilter
先看主要负责认证的过滤器UsernamePasswordAuthenticationFilter,有删减,注意注释。
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter
{
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
private String usernameParameter = "username";
private String passwordParameter = "password";
private boolean postOnly = true;

public UsernamePasswordAuthenticationFilter() {
    super(new AntPathRequestMatcher("/login", "POST"));
}

public Authentication attemptAuthentication(HttpServletRequest request, 
                                            HttpServletResponse response) throws AuthenticationException {
    //必须为POST请求
    if (this.postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " +
                                                 request.getMethod());
    } else {

        String username = this.obtainUsername(request);
        String password = this.obtainPassword(request);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        //将填写的用户名和密码封装到了UsernamePasswordAuthenticationToken中
        UsernamePasswordAuthenticationToken authRequest = new
        UsernamePasswordAuthenticationToken(username, password);

        this.setDetails(request, authRequest);
        //调用AuthenticationManager对象实现认证
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}

}
AuthenticationManager
由上面源码得知,真正认证操作在AuthenticationManager里面!
public class ProviderManager implements AuthenticationManager, MessageSourceAware,
InitializingBean {

private static final Log logger = LogFactory.getLog(ProviderManager.class);
private AuthenticationEventPublisher eventPublisher;
private List<AuthenticationProvider> providers;
protected MessageSourceAccessor messages;
private AuthenticationManager parent;
private boolean eraseCredentialsAfterAuthentication;

//注意AuthenticationProvider这个对象,SpringSecurity针对每一种认证,什么qq登录啊,
//用户名密码登陆啊,微信登录啊都封装了一个AuthenticationProvider对象。
public ProviderManager(List<AuthenticationProvider> providers) {
    this(providers, (AuthenticationManager)null);
}

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;
    boolean debug = logger.isDebugEnabled();
    Iterator var8 = this.getProviders().iterator();

    //循环所有AuthenticationProvider,匹配当前认证类型。
    while(var8.hasNext()) {
        AuthenticationProvider provider = (AuthenticationProvider)var8.next();
        if (provider.supports(toTest)) {
            if (debug) {
                logger.debug("Authentication attempt using " +
                             provider.getClass().getName());
            }
            try {
                //找到了对应认证类型就继续调用AuthenticationProvider对象完成认证业务。
                result = provider.authenticate(authentication);
                if (result != null) {
                    this.copyDetails(authentication, result);
                    break;
                }
            } catch (AccountStatusException var13) {
                this.prepareException(var13, authentication);
                throw var13;
            } catch (InternalAuthenticationServiceException var14) {
                this.prepareException(var14, authentication);
                throw var14;
            } catch (AuthenticationException var15) {
                lastException = var15;
            }
        }
    }

    if (result == null && this.parent != null) {
        try {
            result = parentResult = this.parent.authenticate(authentication);
        } catch (ProviderNotFoundException var11) {
        } catch (AuthenticationException var12) {
            parentException = var12;
            lastException = var12;
        }
    }

    if (result != null) {
        if (this.eraseCredentialsAfterAuthentication && result instanceof
            CredentialsContainer) {
            ((CredentialsContainer)result).eraseCredentials();
        }
        if (parentResult == null) {
            this.eventPublisher.publishAuthenticationSuccess(result);
        }
        return result;
    } else {
        if (lastException == null) {
            lastException = new
            ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound", new
                                                               Object[]{toTest.getName()}, "No AuthenticationProvider found for {0}"));
        }
        if (parentException == null) {
            this.prepareException((AuthenticationException)lastException, authentication);
        }
        throw lastException;
    }
}

}
AbstractUserDetailsAuthenticationProvider
咱们继续再找到AuthenticationProvider的实现类AbstractUserDetailsAuthenticationProvider:
public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
private PasswordEncoder passwordEncoder;
private volatile String userNotFoundEncodedPassword;
private UserDetailsService userDetailsService;
private UserDetailsPasswordService userDetailsPasswordService;
protected final UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
this.prepareTimingAttackProtection();
try {
//重点来了!主要就在这里了!
//可别忘了,咱们为什么要翻源码,是想用自己数据库中的数据实现认证操作啊!
//UserDetails就是SpringSecurity自己的用户对象。
//this.getUserDetailsService()其实就是得到UserDetailsService的一个实现类
//loadUserByUsername里面就是真正的认证逻辑
//也就是说我们可以直接编写一个UserDetailsService的实现类,告诉SpringSecurity就可以了!
//loadUserByUsername方法中只需要返回一个UserDetails对象即可
UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
//若返回null,就抛出异常,认证失败。
if (loadedUser == null) {
throw new InternalAuthenticationServiceException("UserDetailsService returned
null, which is an interface contract violation");
} else {
//若有得到了UserDetails对象,返回即可。
return loadedUser;
}
} catch (UsernameNotFoundException var4) {
this.mitigateAgainstTimingAttack(authentication);
throw var4;
} catch (InternalAuthenticationServiceException var5) {
throw var5;
} catch (Exception var6) {
throw new InternalAuthenticationServiceException(var6.getMessage(), var6);
}
}
}
AbstractUserDetailsAuthenticationProvider
按理说到此已经知道自定义认证方法的怎么写了,但咱们把返回的流程也大概走一遍,上面不是说到返回了一个 UserDetails对象对象吗?
跟着它就又回到AbstractUserDetailsAuthenticationProvider对象中authenticate方法最后一行了。
public abstract class AbstractUserDetailsAuthenticationProvider implements
AuthenticationProvider, InitializingBean, MessageSourceAware {

public Authentication authenticate(Authentication authentication) throws
AuthenticationException {
    //最后一行返回值,调用了createSuccessAuthentication方法,此方法就在下面!
    return this.createSuccessAuthentication(principalToReturn, authentication, user);
}

//咿!?怎么又封装了一次UsernamePasswordAuthenticationToken,开局不是已经封装过了吗?
protected Authentication createSuccessAuthentication(Object principal, 
                                                     Authentication authentication, 
                                                     UserDetails user) {
    //那就从构造方法点进去看看,这才干啥了。
    UsernamePasswordAuthenticationToken result = new
    UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(),
                                        this.authoritiesMapper.mapAuthorities(user.getAuthorities()));
    result.setDetails(authentication.getDetails());
    return result;
}

}
UsernamePasswordAuthenticationToken
来到UsernamePasswordAuthenticationToken对象发现里面有两个构造方法
public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {

private static final long serialVersionUID = 510L;
private final Object principal;
private Object credentials;

//认证成功前,调用的是这个带有两个参数的。
public UsernamePasswordAuthenticationToken(Object principal, 
                                           Object credentials) {
    super((Collection)null);
    this.principal = principal;
    this.credentials = credentials;
    this.setAuthenticated(false);
}

//认证成功后,调用的是这个带有三个参数的。
public UsernamePasswordAuthenticationToken(Object principal, 
                                           Object credentials,
                                           Collection<? extends GrantedAuthority> authorities) {
    //看看父类干了什么!
    super(authorities);
    this.principal = principal;
    this.credentials = credentials;
    super.setAuthenticated(true);
}

}
AbstractAuthenticationToken
再点进去super(authorities)看看:
public abstract class AbstractAuthenticationToken implements Authentication,
CredentialsContainer {

private final Collection<GrantedAuthority> authorities;
private Object details;
private boolean authenticated = false;

public AbstractAuthenticationToken(Collection<? extends GrantedAuthority> authorities) {

    //这时两个参数那个分支!
    if (authorities == null) {
        this.authorities = AuthorityUtils.NO_AUTHORITIES;
    } else {
        //三个参数的,看这里!
        Iterator var2 = authorities.iterator();
        //原来是多个了添加权限信息的步骤
        GrantedAuthority a;
        do {
            if (!var2.hasNext()) {
                ArrayList<GrantedAuthority> temp = new ArrayList(authorities.size());
                temp.addAll(authorities);
                this.authorities = Collections.unmodifiableList(temp);
                return;
            }
            a = (GrantedAuthority)var2.next();
        } while(a != null);
        //若没有权限信息,是会抛出异常的!
        throw new IllegalArgumentException("Authorities collection cannot contain any null
        elements");
    }
}

}
由此,咱们需要牢记自定义认证业务逻辑返回的UserDetails对象中一定要放置权限信息! 现在可以结束源码分析了?先不要着急! 咱们回到最初的地方UsernamePasswordAuthenticationFilter,你看好看了,这可是个过滤器,咱们分析这么 久,都没提到doFilter方法,你不觉得心里不踏实?可是这里面也没有doFilter呀?那就从父类找!
AbstractAuthenticationProcessingFilter

相关文章
|
C语言
C语言入门——printf(““)左对齐与右对齐问题
C语言入门——printf(““)左对齐与右对齐问题
2403 0
C语言入门——printf(““)左对齐与右对齐问题
|
Windows
『NSSM』将Kibana及Logstash设置为Windows服务启动
📣读完这篇文章里你能收获到 - NSSM下载及使用 - 将Kibana及Logstash设置为Windows服务启动
1023 0
『NSSM』将Kibana及Logstash设置为Windows服务启动
|
2月前
|
人工智能 编解码 数据可视化
阿里云国际站代理商:GPU 选型避坑指南 2026 大模型训练与推理算力配置
本文聚焦2026年AI多模态时代GPU选型实战。针对训练、推理、渲染三大场景,详解gn8v(H100/H200)、gn8is(L20)、gn7i(A10)等主流实例的适用性与性价比,并提醒账号风控、配额限制、地域库存等关键避坑点。(239字)
|
10月前
|
运维 Java Nacos
Nacos配置中心
本章基于Nacos实现配置中心,解决微服务架构中配置管理难题。通过引入nacos-config依赖与bootstrap.yaml文件,实现应用启动时优先加载远程配置,动态获取userservice-dev.yaml等环境配置,支持热更新、集中化管理,提升系统可用性与运维效率。
|
10月前
|
Dubbo Java 应用服务中间件
Feign远程调用
本章介绍Feign如何优雅替代RestTemplate实现HTTP跨服务调用。通过引入Feign,结合注解声明远程接口,避免服务地址硬编码,提升代码可读性与维护性,并支持自定义日志、编码等配置,实现高效、简洁的微服务通信方案。
|
7月前
|
JSON 监控 Java
亿级流量系统 JVM 全链路调优:从压测瓶颈定位到线上稳态落地全指南
本文系统讲解亿级流量下JVM调优的工程化实践,涵盖压测基准建设、瓶颈根因定位、JDK17内存模型与GC原理、代码级优化(避免短生命周期/大对象、规范ThreadLocal)、G1/ZGC参数调优、OS内核优化及线上稳态保障,强调“先代码、后配置、再参数”的科学路径。
584 2
|
监控 NoSQL 算法
阿里本地生活EMonitor根因分析大揭秘
阿里集团针对故障处理提出了“**1/5/10**”的目标-- 1 分钟发现、5 分钟定位、10 分钟恢复,这对我们的定位能力提出了更高的要求。
4912 113
阿里本地生活EMonitor根因分析大揭秘
|
存储 SQL 算法
Mysql底层原理详细剖析+常见面试题(全)
这篇博客主要通过进行学习2021年最新大厂数据库面试讲解,45讲让你透彻理解MySQL索引!前情回顾,如果想了解更多的数据库底层原理可看我其他的文章底层知识链接DQL、DML、DDL、DCL的定义数据库之DQL、DML、DDL、DCL定义事务四个特性、隔离级别以及面临的问题数据库关于事务的详解分析(全)包含面试常问的细节Mysql的主从复制以及Redis的主从复制关于主从复制的超详细解析(全)索引的优化分析、查询截取分析、锁机制Mysql优化高级篇(全)还有其他细节以及数据库的算法题 可看我的专栏。...
1457 0
Mysql底层原理详细剖析+常见面试题(全)
|
运维 负载均衡 监控
Spring Cloud 微服务优雅下线 + 灰度发布的正确姿势,写得太好了!
在生产环境中,如何保证在服务升级的时候,不影响用户的体验,这个是一个非常重要的问题。如果在我们升级服务的时候,会造成一段时间内的服务不可用,这就是不够优雅的。那什么是优雅的呢?主要就是指在服务升级的时候,不中断整个服务,让用户无感知,进而不会影响用户的体验,这就是优雅的。
1573 0
Spring Cloud 微服务优雅下线 + 灰度发布的正确姿势,写得太好了!
|
异构计算
FPGA - 7系列 FPGA内部结构之SelectIO -02- 源语简介(一)
FPGA - 7系列 FPGA内部结构之SelectIO -02- 源语简介
1942 0
FPGA - 7系列 FPGA内部结构之SelectIO -02- 源语简介(一)

热门文章

最新文章