Spring Securiy OAuth2资源服务器:通过HTTP方法访问

时间:2020-01-11 12:43:29

标签: java spring spring-boot spring-security oauth-2.0

我有一个使用spring-security-oauth2-autoconfigure来运行OAuth2资源服务器的Spring Boot应用程序:

@Configuration
@EnableResourceServer
public class OAuth2Config extends ResourceServerConfigurerAdapter {

    @Value("${security.oauth2.resource.id}")
    private String resourceId;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/api/**").authenticated()
                .anyRequest().permitAll();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(resourceId);
    }

}

一切正常。只有获得授权,我才能访问/api之后的所有端点。我的一个控制器如下所示:

@RestController
@RequestMapping("/api/events")
@Slf4j
public class EventController {

    // ...

    @RequestMapping(path = "", method = RequestMethod.GET)
    public List<Event> getEvents() {
        return Lists.newArrayList(eventRepository.findAll());
    }

    @RequestMapping(name = "", method = RequestMethod.POST)
    public ResponseEntity<Event> createEvent(@RequestBody Event event) {
        Event newEvent = eventRepository.save(event);
        return new ResponseEntity<>(newEvent, HttpStatus.CREATED);
    }

    // ...

}

现在我的问题:我如何允许用户A仅访问GET /api/events,而用户B访问两个端点(POST /api/events)?我想出了如何控制访问权限在端点级别,但是我不知道如何基于HTTP方法进行控制。

0 个答案:

没有答案