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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章