Spring Security最新配置怎么写
时间: 2023-07-25 11:44:48 浏览: 59
Spring Security最新的配置需要使用Java配置类来实现,以下是一个基本的Spring Security配置类示例:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/").permitAll()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
这个示例中,我们首先使用`@Configuration`注解将这个类声明为配置类,然后使用`@EnableWebSecurity`注解启用Spring Security的Web安全功能。我们还继承了`WebSecurityConfigurerAdapter`类,这个类提供了一些默认的Web安全配置。
在`configure(AuthenticationManagerBuilder auth)`方法中,我们配置了一个`UserDetailsService`,用于提供用户认证信息。
在`configure(HttpSecurity http)`方法中,我们定义了一些安全规则,比如哪些URL需要哪些角色才能访问,以及登录和注销的相关配置。其中,我们使用了`formLogin()`方法来定义表单登录的相关配置,`logout()`方法来定义注销的相关配置。
最后,我们使用了`@Bean`注解来声明一个`PasswordEncoder`,用于对密码进行加密和解密操作。这里我们使用了BCrypt算法来实现加密。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)