springboot 整合springsecurity
时间: 2023-10-20 18:09:13 浏览: 155
要在Spring Boot中整合Spring Security,需要在pom.xml文件中添加Spring Security依赖项,并创建一个Security配置类来配置安全性规则和用户身份验证。以下是一个简单的示例:
1. 添加依赖项:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 创建Security配置类:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout().logoutSuccessUrl("/login");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
在上面的示例中,我们配置了三个安全规则:只有具有ADMIN角色的用户才能访问/admin路径,具有ADMIN或USER角色的用户才能访问/user路径,其他所有请求都需要进行身份验证。我们还配置了一个自定义的UserDetailsService来加载用户信息,并使用BCryptPasswordEncoder来加密密码。
阅读全文
相关推荐












