java - 如何在spring boot secuirty中为具有不同请求方法类型的同一url赋予不同的角色权限

标签 java spring spring-boot authentication authorization

我正在使用 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/

相关文章:

java - 具有泛型参数的 Java 方法 - 为什么我不能传递具有作为方法参数子类的泛型参数的对象?

java - Spring JUnit 未从 XML 加载整个 applicationContext

java - org.springframework.beans.factory.UnsatisfiedDependencyException : Error creating bean with name

java - 连接到多个 mongo 数据库主机并在 spring boot 中使用不同的数据库进行身份验证

java - Android:使用 TabHost 和 TabWidget 自定义选项卡的外观

java - 使用 Java 创建作业队列或任务 Controller 并动态向其中添加任务

spring - 为什么我需要 @Transactional 来保存 OneToOne 映射实体

Spring data solr 3.0.6 版本的基于 java 的配置

Java SecurityManager - 在运行时修改之前保护代码

spring - 如何以编程方式在 Cucumber 中设置 Spring 配置文件