Spring @RestController 匿名和授权用户的单一方法

Spring @RestController single method for anonymous and authorized users

我有以下 Spring RestController:

@RestController
@RequestMapping("/v1.0/tenants")
public class TenantController {

    @Autowired
    private TenantService tenantService;

    @RequestMapping(value = "/{tenantId}", method = RequestMethod.GET)
    public TenantResponse findTenantById(@PathVariable @NotNull @DecimalMin("0") Long tenantId) {
        Tenant tenant = tenantService.findTenantById(tenantId);
        return new TenantResponse(tenant);
    }

}

findTenantById 方法应由匿名和授权用户访问。在匿名用户的情况下 SecurityContextHolder.getContext().getAuthentication() 必须 return NULL 或 AnonymousAuthenticationToken 但在授权的情况下 - 身份验证对象。

在我的应用程序中,我使用 OAuth2 + JWT 令牌实现了安全模型。

这是我的配置:

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http                
            .antMatcher("/v1.0/**").authorizeRequests()
            .antMatchers("/v1.0/tenants/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(STATELESS); 
        // @formatter:on
    }

此外,对于安全端点,我在需要的地方应用了 @PreAuthorize 注释,但在 findTenantById 的情况下没有,因为正如我之前所说,我需要授予匿名和授权访问此端点的权限用户。在端点业务逻辑内部,我将根据不同的条件决定谁能够继续。

现在即使我已经为这个端点提供了我的 accessToken,我也无法从 SecurityContextHolder.getContext().getAuthentication().

获得经过身份验证的用户对象

如何配置此端点以便以上述方式工作?

我想我已经找到了解决方案 - 我已经用以下方法注释了我的方法:

@PreAuthorize("isAnonymous() or isFullyAuthenticated()")

如果有更好的解决方案,请告诉我。