使用OAuth2和Github的Spring安全性仅允许组织中的开发人员使用某些API

问题描述 投票:0回答:1

我有一组api,我只希望github中的组织中的开发人员使用。为了验证用户身份,我使用了github的OAuth。但是,将Spring安全性与oauth结合使用似乎并不可行,因为它允许不在组织中的开发人员使用它。我该怎么办?

spring-boot github spring-security oauth-2.0 spring-security-oauth2
1个回答
0
投票

看起来像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", ""));
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.