springsecurity快速入门
时间: 2023-09-04 15:09:25 浏览: 53
Spring Security 是一个强大且灵活的身份验证和访问控制框架,可以在 Spring 应用程序中轻松添加安全性。下面是一个快速入门指南,帮助你了解如何在 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
在 application.properties 文件中添加以下配置:
```
spring.security.user.name=admin
spring.security.user.password=admin123
```
这样就创建了一个名为 "admin",密码为 "admin123" 的用户。你可以通过在应用程序中使用这个用户来测试 Spring Security。
3. 创建安全配置
创建一个类来配置 Spring Security,这个类需要继承 WebSecurityConfigurerAdapter 类。在这个类中,你可以配置安全性规则和用户访问权限。
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/**").permitAll()
.and()
.formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin123").roles("ADMIN")
.and()
.withUser("user").password("{noop}user123").roles("USER");
}
}
```
在上面的示例代码中,我们配置了以下规则:
- 所有 "/admin/**" 的请求需要有 "ADMIN" 角色才能访问;
- 所有 "/user/**" 的请求需要有 "USER" 或 "ADMIN" 角色才能访问;
- 所有其他请求都允许访问;
- 启用表单登录。
我们还在 configureGlobal() 方法中配置了两个用户,一个是 "admin",另一个是 "user"。这两个用户都有不同的角色,可以用于测试。
4. 测试应用程序
现在你可以启动应用程序并测试它了。你可以使用 "/admin/**" 和 "/user/**" 路径中的不同 URL 来测试不同的角色。如果你尝试访问没有权限的 URL,系统会自动重定向到登录页面。
这就是 Spring Security 的快速入门指南。希望这篇文章能够帮助你快速了解 Spring Security 的基本用法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)