spring security 5 (5)-自定义认证

第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
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 关于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: jwt: signature-algorithm: RS256 jwk-set-uri: https://example.com/oauth2/keys supported-grant-types: authorization_code,client_credentials,password,refresh_token ``` 以上是关于spring-authorization-server自定义认证配置的回答,希望能对您有所帮助。 ### 回答2: spring-authorization-server是Spring框架的一个模块,用于构建带有自定义认证配置的授权服务器。 在使用spring-authorization-server时,我们可以通过自定义认证配置来对授权服务器进行个性化的定制。具体步骤如下: 1. 创建自定义认证配置类:我们可以创建一个自定义的配置类,继承自AuthorizationServerConfigurerAdapter,并在类上加上@Configuration注解。在这个类中,我们可以重写configure方法,对授权服务器的认证配置进行定制。 2. 配置认证服务:在configure方法中,我们可以使用AuthorizationServerEndpointsConfigurer对象的方法对认证服务进行配置。例如,可以使用tokenStore方法设置token的存储方式,使用authenticationManager方法设置认证管理器,使用userDetailsService方法设置用户详细信息服务等。 3. 配置客户端信息:我们可以使用AuthorizationServerEndpointsConfigurer对象的方法对客户端信息进行配置。例如,可以使用inMemory方法将客户端信息存储在内存中,使用withClient方法设置客户端的clientId和clientSecret等。 4. 配置授权的方式:我们可以使用AuthorizationServerSecurityConfigurer对象的方法来配置授权的方式。例如,可以使用tokenKeyAccess方法设置token的访问权限,使用checkTokenAccess方法设置检查token的权限等。 通过以上步骤,我们可以根据业务需要对授权服务器的认证配置进行自定义。可根据具体的需求来选择存储方式、认证方式、访问权限等,从而实现对授权服务器的个性化定制。使用spring-authorization-server的自定义认证配置,可以实现更灵活、更安全的授权服务器构建。 ### 回答3: spring-authorization-server是一个基于Spring框架的授权服务器,用于处理认证和授权的任务。它提供了一种自定义认证配置的方式来满足应用程序的特定需求。 首先,我们可以通过创建一个实现了AuthorizationServerConfigurer接口的配置类来实现自定义认证配置。该接口提供了一些方法,可以用于配置授权服务器的行为。 通过重写configure(ClientDetailsServiceConfigurer clients)方法,我们可以定义客户端的认证信息。我们可以指定客户端的ID和秘钥,并设置各种认证方式,如基于密码、授权码、简化模式等。这些设置将决定客户端可以使用哪种方式进行认证和授权。 其次,我们可以通过重写configure(AuthorizationServerEndpointsConfigurer endpoints)方法来配置授权服务器的终端。我们可以指定认证管理器、用户详情服务和令牌存储等终端的相关信息。我们还可以自定义令牌生成方式、令牌验证方式以及访问令牌的有效期等。 另外,我们还可以通过重写configure(AuthorizationServerSecurityConfigurer security)方法来配置授权服务器的安全性。我们可以设置授权服务器的访问权限,例如要求授权请求必须经过身份验证等。 除了以上方法,我们还可以结合其他Spring框架提供的相关组件和功能来实现自定义认证配置。例如,可以使用自定义的UserDetailsService来配置用户的认证信息,或者使用自定义的TokenStore来实现令牌的自定义存储策略。 总之,通过使用spring-authorization-server,我们可以根据应用程序的需求来灵活地配置认证和授权的行为。通过自定义认证配置,我们可以定制化地满足各种认证需求,提高应用程序的安全性和可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值