第3篇 讲过,用户登录时,系统会读取用户的UserDetails对其认证,认证过程是由系统自动完成的,主要是检查用户密码。而在现实中,登录方式并不一定是检查密码,也可能是验证码或其他,此时就需要自定义认证。

AuthenticationProvider

自定义认证逻辑在AuthenticationProvider的authenticate方法中完成, 第4篇 讲过,认证的入参是一个未认证Authentication,出参是一个已认证Authentication,formLogin的默认Authentication实现是UsernamePasswordAuthenticationToken。

	public void configure(AuthenticationManagerBuilder auth){
		auth.authenticationProvider(authenticationProvider());	
	@Bean
	public AuthenticationProvider authenticationProvider() {
		return new AuthenticationProvider() {
			//检查入参Authentication是否是UsernamePasswordAuthenticationToken或它的子类
			public boolean supports(Class<?> authentication) {
				return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
			public Authentication authenticate(Authentication authentication) throws AuthenticationException {
				//第4篇讲过的其他参数,默认details类型中包含用户ip和sessionId
				WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
				//用户名和密码
				String username = authentication.getName(); 	
				String password = authentication.getCredentials().toString(); 
				//根据以上参数,自定义认证逻辑,系统默认实现就是在此读取UserDetails认证密码
                //这里只给个简化逻辑,验证密码是否是123,实际中要根据具体业务来实现
				if(!password.equals("123")){
					throw new BadCredentialsException("密码错误");				
				// 认证通过,从数据库中查询用户权限 
				List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
				authorities.add(new SimpleGrantedAuthority("ROLE_role1"));
				//生成已认证Authentication,系统会将其写入SecurityContext
				return new UsernamePasswordAuthenticationToken(username, password, authorities);

supports方法用于检查入参的类型,AuthenticationProvider只会认证符合条件的类型,下面会讲

AuthenticationManager

一个AuthenticationProvider对应一种认证逻辑,而有时用户即可选择密码登录,也可选择验证码登录,这就需要有多个认证逻辑同时存在,即多个AuthenticationProvider 。而AuthenticationManager就是用来管理多个AuthenticationProvider的。

public void configure(AuthenticationManagerBuilder auth)

以上configure方法的作用是快速自动构建AuthenticationManager,而此时要自定义AuthenticationManager,就不再需要这个方法了。而是在security配置类中使用另一个方法初始化AuthenticationManager,如下加载了两个AuthenticationProvider 

	protected AuthenticationManager authenticationManager() throws Exception {
		List list = new ArrayList();
		list.add(authenticationProvider1());
		list.add(authenticationProvider2());
		return new ProviderManager(list);

将前面的authenticationProvider方法复制出第二个方法,修改方法名为authenticationProvider1和authenticationProvider2,现在就有两个authenticationProvider了,AuthenticationManager构建比较简单,此时认证流程如下

多重认证流程

  1. 执行第1个authenticationProvider的supports方法,结果false会跳到下个authenticationProvider。结果true则执行当前authenticationProvider的认证逻辑。
  2. 认证不通过,会抛出相关异常,会直接跳出AuthenticationManager。
  3. 认证通过,返回已认证Authentication,同样跳出AuthenticationManager。
  4. 如果需要进一步认证,可返回null,跳到下一个authenticationProvider,可实现多重认证。

我之前说过,系统默认的Authentication入参都是UsernamePasswordAuthenticationToken类型,所以这里supports必须为true。下篇我会讲自定义认证过滤器,到时候就可以自定义不同的入参类型了,以适用于不同的AuthenticationProvider。

自定义Details

如果要实现对用户/密码以外的参数进行认证,如验证码,还需要自定义Details。上面代码中的WebAuthenticationDetails是默认的Details实现类,其中包括用户ip和sessionId两个参数。以下方式可以添加自定义参数:如验证码code。

public class MyWebAuthenticationDetails extends WebAuthenticationDetails {
	private String code;
	public String getCode() {
		return code;
	public void setCode(String code) {
		this.code = code;
	public MyWebAuthenticationDetails(HttpServletRequest request) {
		super(request);
		code=request.getParameter("code");

修改上面的代码,WebAuthenticationDetails改成MyWebAuthenticationDetails,就可以对验证码进行认证。

        MyWebAuthenticationDetails details = (MyWebAuthenticationDetails)authentication.getDetails();
        if(!details.getCode().equals("123")){
	        throw new BadCredentialsException("验证码错误");				

上一篇讲过,Details是Authentication的一个参数,而Authentication是在认证过滤器中封装而成的。而formLogin会使用系统默认的认证过滤器,其默认Details也是WebAuthenticationDetails类型,需要以下配置将它改成MyWebAuthenticationDetails类型。

	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests() 
				.anyRequest().authenticated().and() 
			.formLogin() //配置Details源
				.authenticationDetailsSource(authenticationDetailsSource()).and()
			.csrf().disable();
	@Bean
	public AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource() {
		return new AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails>() {
			public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
				return new MyWebAuthenticationDetails(context);//配置Details类型
                    第3篇讲过,用户登录时,系统会读取用户的UserDetails对其认证,认证过程是由系统自动完成的,主要是检查用户密码。而在现实中,登录方式并不一定是检查密码,也可能是验证码或其他,此时就需要自定义认证。AuthenticationProvider自定义认证逻辑在AuthenticationProvider的authenticate方法中完成,第4篇讲过,认证的入参是一个未认证Authen...
import cn.edu.zstu.shihua.xihu.model.Log;
import cn.edu.zstu.shihua.xihu.service.ILogService;
import cn.edu.zstu.shihua.xihu.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.Query.
启用S​​pring WebFlux安全性
在你的应用程序首先使Webflux安全@EnableWebFluxSecurity
 @SpringBootApplication
@EnableWebFluxSecurity
public class SecuredRestApplication {
创建一个InMemory UserDetailsS​​ervice
 定义一个自定义UserDetailsService bean,在其中添加具有密码和初始角色的User:
 @Bean
    public MapReactiveUserDetailsService userDetailsRepository() {
        UserDetails user = User . withDefaultPasswordEncoder()
                .username( " user " )
				
spring security 使用总结 两大核心:1、认证 2授权 认证:就是常见的用户名密码校验 通过实现UserDetailsService 中 loadUserByUsername 方法 完成用户认证 授权:通过继承BasicAuthenticationFilter实现doFilterInternal 方法实现授权 spring security 里面封装的内容很多 里面都是通过filter使用责任链的模式来实现的 暂时只用到了认证 @Configuration @EnableWebSecurity
验证码 Servlet,这里大家不需要关心内部怎么实现的,我也是百度直接copy的 @Component public class VerifyServlet extends HttpServlet { private static final long serialVersionUID = -5051097528828603895L; * 验证码图片的宽度。 private int widt
  在使用Spring Security框架过程中,经常会有这样的需求,即在登录验证时,附带增加额外的数据,如验证码、用户类型等。下面将介绍如何实现。   注:我的工程是在Spring Boot框架基础上的,使用xml方式配置的话请读者自行研究吧。 实现自定义WebAuthenticationDetails   该类提供了获取用户登录时携带的额外信息的功能,默认实现WebAuthe...
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!---... 验证码相关的依赖和代码,在上一篇已经写到了,这里不在赘述。 1.实现一个封装额外信息的detail类 package com.demo.springsecuritydemo.detail; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springfra...
关于spring-authorization-server自定义认证配置,我可以回答您的问题。 Spring Authorization Server 是 Spring Security 的一个子项目,它提供了 OAuth 2.0 和 OpenID Connect(OIDC)的认证和授权功能。在使用 Spring Authorization Server 进行自定义认证配置时,可以通过创建实现特定接口的 bean 或者在配置文件中指定相关配置来完成。 具体地说,可以通过实现 AuthorizationServerConfigurer 接口来进行自定义认证配置。该接口定义了一系列方法,例如: - configure(ClientDetailsServiceConfigurer clients):配置客户端详情服务。 - configure(AuthorizationServerEndpointsConfigurer endpoints):配置授权端点的URL和令牌服务。 - configure(AuthorizationServerSecurityConfigurer security):配置授权服务器的安全性。 通过实现这些方法并设置相关属性,可以对 Spring Authorization Server 进行自定义认证配置。例如,可以设置支持的授权类型、客户端详情信息、令牌存储方式、用户认证方式等等。 除了实现接口进行自定义配置外,还可以通过在配置文件中指定相关配置来完成。例如,在 application.yml 文件中添加以下配置可以设置支持的授权类型: spring: authorization: server: token: issuer-uri: https://example.com/ access-token: signature-algorithm: RS256 jwk-set-uri: https://example.com/oauth2/keys supported-grant-types: authorization_code,client_credentials,password,refresh_token 以上是关于spring-authorization-server自定义认证配置的回答,希望能对您有所帮助。
CSDN-Ada助手: 非常感谢博主的辛勤创作,这篇关于JWT token的博客非常详细、易懂,对我们这些初学者来说很有帮助。博主的专业知识和经验让我倍感钦佩,希望你能继续分享你的宝贵经验,让更多人受益。再次感谢博主的付出和分享! 为了方便博主创作,提高生产力,CSDN上线了AI写作助手功能,就在创作编辑器右侧哦~(https://mp.csdn.net/edit?utm_source=blog_comment_recall )诚邀您来加入测评,到此(https://activity.csdn.net/creatActivity?id=10450&utm_source=blog_comment_recall)发布测评文章即可获得「话题勋章」,同时还有机会拿定制奖牌。 spring security 5 (9)-httpBasic基本认证 振国119: 微信测试账号 (2)-消息验证sha1签名 ZJZQL: 这个依赖很关键, spring security 5 (9)-httpBasic基本认证 _Cade_: 这个用户密码的页面是浏览器实现的吗 Netty (3)-ByteBuf、池、直接内存、16进制 和煦晨阳: 如何通过十六进制创建一个ByteBuf?