springboot设置资源访问权限
时间: 2023-08-05 14:09:40 浏览: 47
在 Spring Boot 中,可以通过配置 `WebSecurityConfigurerAdapter` 来设置资源访问权限。具体步骤如下:
1. 创建一个继承 `WebSecurityConfigurerAdapter` 的类,并添加 `@Configuration` 注解。
2. 在该类中重写 `configure(HttpSecurity http)` 方法,可以通过该方法来配置所有的 HTTP 安全相关的信息,包括权限、登录、注销等。
3. 通过 `http.authorizeRequests()` 方法来设置请求的权限要求,比如可以使用 `antMatchers()` 方法来指定某些请求需要特定的权限或角色。
4. 如果需要提供用户登录功能,可以使用 `http.formLogin()` 方法来进行配置。比如可以通过设置登录页面的 URL、用户名和密码的参数名等信息。
5. 如果需要提供用户注销功能,可以使用 `http.logout()` 方法进行配置。比如可以通过设置注销 URL、注销成功后重定向的 URL 等信息。
以下是一个示例代码:
```java
@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("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
```
在上述示例中,我们设置了 `/admin/**` 路径需要 `ADMIN` 角色,`/user/**` 路径需要 `USER` 或 `ADMIN` 角色。此外,我们还配置了登录页面的 URL 和注销 URL。同时,我们还通过 `configureGlobal()` 方法设置了 `UserDetailsService`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)