springboot整合secruty
时间: 2023-10-23 08:10:41 浏览: 22
Spring Boot整合Spring Security可以通过以下步骤实现:
1. 添加Spring Security依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 配置Spring Security
在Spring Boot的配置类中添加以下代码:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@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("/");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin").roles("ADMIN")
.and()
.withUser("user").password("{noop}user").roles("USER");
}
}
```
上述代码中,我们定义了两个用户:admin和user,分别具有ADMIN和USER角色。我们还定义了访问/admin/**路径需要ADMIN角色,访问/user/**路径需要ADMIN或USER角色。
3. 测试Spring Security
启动应用程序并访问http://localhost:8080/admin/或http://localhost:8080/user/,您将被重定向到登录页面。使用admin或user作为用户名和密码进行登录,您将被重定向到相应的页面。