springsecurity整合springboot
时间: 2023-10-09 10:16:04 浏览: 103
Spring Security是一个基于Spring的安全框架,用于保护Spring Boot应用程序中的资源。它提供了许多功能,如认证、授权、密码加密等,用于确保应用程序的安全性。
在Spring Boot中整合Spring Security的步骤如下:
1. 引入Spring Security依赖。在项目的pom.xml文件中添加以下依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 创建一个继承自 `WebSecurityConfigurerAdapter` 的配置类,并重写其中的 `configure` 方法。在该方法中,可以进行一些安全配置,如定义认证规则、授权规则等。示例代码如下:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/test").permitAll() // 允许匿名访问的接口
.anyRequest().authenticated() // 其他接口需要认证
.and()
.formLogin() // 开启表单登录
.and()
.httpBasic(); // 开启基础认证
}
}
```
3. 在上述配置类中,可以通过 `UserDetailsService` 接口来定义用户信息。可以使用内存用户存储、数据库存储或其他自定义方式进行用户认证。示例代码如下:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin").roles("ADMIN") // 使用明文密码
.and()
.withUser("user").password("{noop}user").roles("USER");
}
}
```
4. 最后,启动应用程序并访问受保护的资源,您将被重定向到登录页面。您可以使用上述配置中定义的用户名和密码进行登录。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)