我正在使用Spring Boot安全性来认证和授权其余的HTTP API。 我看到我们可以像这样设置授权设置
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
// .anyRequest().permitAll()
.antMatchers("/user/health_check/*").permitAll()
.antMatchers("/user/registration").permitAll()
.antMatchers("/user/login","/user/logout").hasAnyRole("USER","ADMIN","MANAGER")
.antMatchers("/admin/*").fullyAuthenticated()
.and().httpBasic()
.and().csrf().disable();
}
}
我想知道如何对请求方法不同的不同URL赋予不同的权限?
例如: 如果我必须有两个
// GET /api/account/{id}
// POST /api/account/{id}
// PUT /api/account/{id}
我只希望对PUT授予管理员访问权限,而对GET授予用户访问权限,而对POST则授予用户和管理员访问权限。
答案 0 :(得分:2)
您可以在控制器的方法上使用@PreAuthorize
批注:
@GetMapping("/api/account/{id}")
@PreAuthorize("hasAutority('readAccountById')")
public Account getAccount(@PathVariable Integer id){
...
}
它与Spring安全上下文一起使用,并且您可以检查用户角色,权限等。
供参考,请参阅本文https://www.baeldung.com/spring-security-method-security
答案 1 :(得分:2)
您可以在antMatchers
中传递请求方法。
尝试一下:
http
.httpBasic().and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/account/**").hasRole("ADMIN")
.antMatchers(HttpMethod.POST, "/api/account/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/api/account/**").hasRole("ADMIN");