springboot如何整合 spring security
时间: 2023-10-09 20:17:15 浏览: 80
Spring Boot可以轻松地与Spring Security集成,使得应用程序能够实现基于角色的访问控制和安全认证。
以下是在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:在应用程序的配置类中,添加@EnableWebSecurity注释和WebSecurityConfigurerAdapter类。然后,覆盖configure()方法以指定安全性规则和URL模式。
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
```
3.定义用户和角色:在configureGlobal()方法中,使用内存身份验证定义用户和角色。
4.运行应用程序并测试:使用浏览器访问应用程序的登录页面,输入用户名和密码,然后访问受保护的URL。
以上就是Spring Boot中整合Spring Security的基本步骤。
阅读全文
相关推荐















