我正在使用 spring boot security 来验证和授权我的其余 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 的访问权限。我该如何实现?
最佳答案
你可以在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");
关于java - 如何在spring boot secuirty中为具有不同请求方法类型的同一url赋予不同的角色权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51790576/