Spinrg Security Authentication(二)

具体原理请参考Spring Boot Security原理一(八)Spinrg Security Authentication(一)

1 认证方式

1.1 内存中认证

@EnableWebSecurity
public class WebSecurityConfig implements WebMvcConfigurer {

	@Bean
	public UserDetailsService userDetailsService() throws Exception {
		InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
		manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
		return manager;
	}
}

1.2 JDBC身份验证

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
	// ensure the passwords are encoded properly
	UserBuilder users = User.withDefaultPasswordEncoder();
	auth
		.jdbcAuthentication()
			.dataSource(dataSource)
			.withDefaultSchema()
			.withUser(users.username("user").password("password").roles("USER"))
			.withUser(users.username("admin").password("password").roles("USER","ADMIN"));
}

1.3 LDAP认证

2 AuthenticationProvider

可以通过将自定义AuthenticationProvider为bean 来定义自定义身份验证。例如,以下将自定义身份验证,假设SpringAuthenticationProvider实现AuthenticationProvider:

仅在AuthenticationManagerBuilder尚未填充时使用

@Bean
 public SpringAuthenticationProvider springAuthenticationProvider(){
	 return  new SpringAuthenticationProvider();
}

3 UserDetailsS​​ervice

可以通过将自定义公开UserDetailsService为bean 来定义自定义身份验证。例如,以下将自定义身份验证,假设SpringDataUserDetailsService实现UserDetailsService:

仅在AuthenticationManagerBuilder尚未填充且未AuthenticationProviderBean定义时才使用此选项。

@Bean
 public SpringDataUserDetailsS​​ervice springDataUserDetailsS​​ervice(){
	 return  new SpringDataUserDetailsS​​ervice();
}

您还可以通过将PasswordEncoderbean 公开为bean 来自定义密码的编码方式。例如,如果使用bcrypt,则可以添加bean定义,如下所示:

@Bean
 public BCryptPasswordEncoder passwordEncoder(){
	 return  new BCryptPasswordEncoder();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值