【问题标题】:Spring security with OAuth2 and Github to only allow developers in an organization to use certain APIs使用 OAuth2 和 Github 的 Spring 安全性仅允许组织中的开发人员使用某些 API
【发布时间】:2020-03-05 11:14:57
【问题描述】:

我有一组 api,我只希望 github 中的组织中的开发人员使用。为了对用户进行身份验证,我使用了 github 的 OAuth。但是使用带有 oauth 的 Spring 安全性似乎并没有这样做,因为它允许不在组织中的开发人员使用它。我该怎么做?

【问题讨论】:

  • 您能否添加更多细节,例如您尝试过的代码等?
  • @YogeshPrajapati 在 pom 中添加 spring-boot-starter-oauth2-client 可以在所有 api 上启用 oauth。然后在 github 上创建了一个 oauth 应用程序。现在,当我尝试任何 api 时,请求被拦截并重定向到 github 的 oauth,我允许访问我的 github。在此之后,链接被转发到受保护的 api。在这里,我希望只有在将用户添加到组织时才能访问该 api。

标签: spring-boot github spring-security oauth-2.0 spring-security-oauth2


【解决方案1】:

看起来这个spring.io 教程有一个针对这个确切用例的示例:

@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService(WebClient rest) {
    DefaultOAuth2UserService delegate = new DefaultOAuth2UserService();
    return request -> {
        OAuth2User user = delegate.loadUser(request);
        if (!"github".equals(request.getClientRegistration().getRegistrationId())) {
            return user;
        }

        OAuth2AuthorizedClient client = new OAuth2AuthorizedClient
                (request.getClientRegistration(), user.getName(), request.getAccessToken());
        String url = user.getAttribute("organizations_url");
        List<Map<String, Object>> orgs = rest
                .get().uri(url)
                .attributes(oauth2AuthorizedClient(client))
                .retrieve()
                .bodyToMono(List.class)
                .block();

        if (orgs.stream().anyMatch(org -> "spring-projects".equals(org.get("login")))) {
            return user;
        }

        throw new OAuth2AuthenticationException(new OAuth2Error("invalid_token", "Not in Spring Team", ""));
    };
}

【讨论】:

  • 我最终使用过滤器链来做到这一点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
  • 2016-04-15
  • 1970-01-01
  • 2017-05-09
  • 2020-02-29
  • 2018-11-29
  • 2013-04-12
相关资源
最近更新 更多