新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

springboot接口权限校验的有哪些方法,spring boot接口

发布时间:2023-08-15 07:59:05

springboot接口权限校验的有哪些方法

Spring Boot中可使用Spring Security来进行接口权限校验。以下是一种常见的方法来实现接口权限校验:
1. 添加依赖:在`pom.xml`文件中添加Spring Security的依赖。
```xml

org.springframework.boot
spring-boot-starter-security

```
2. 创建用户和角色实体类:创建用户和角色的实体类,并使用注解标记实体类和字段与数据库表和列的关系。
3. 创建用户和角色的Repository:创建用户和角色的Repository接口,用于与数据库交互。
4. 创建UserService:创建UserService类,实现UserDetailsService接口,并重写`loadUserByUsername`方法,用于根据用户名加载用户信息。
5. 创建SecurityConfig:创建SecurityConfig类,继承WebSecurityConfigurerAdapter类,并重写`configure`方法,用于配置Spring Security的相关信息。
```java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/public/**").permitAll() // 公然接口,无需认证
.anyRequest().authenticated() // 其他接口需要进行认证
.and()
.formLogin() // 使用表单登录
.loginPage("/login") // 登录页的URL
.loginProcessingUrl("/doLogin") // 登录表单的POST URL
.permitAll()
.and()
.logout()
.logoutUrl("/logout") // 登出URL
.logoutSuccessUrl("/login") // 登出成功后跳转的URL
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
6. 创建Controller:创建Controller类,并使用`@PreAuthorize`注解来标记需要进行权限校验的接口。
```java
@RestController
@RequestMapping("/api")
public class MyController {
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/admin")
public String admin() {
return "Admin Page";
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
@GetMapping("/user")
public String user() {
return "User Page";
}
@GetMapping("/public")
public String publicPage() {
return "Public Page";
}
}
```
以上就是一种基于Spring Boot和Spring Security进行接口权限校验的方法。在这类方法中,我们使用`@PreAuthorize`注解来标记接口,通过指定角色来进行权限校验。当访问带有`@PreAuthorize`注解的接口时,Spring Security会自动进行权限校验,如果用户没有相应的角色,将会返回403 Forbidden毛病。