Spring Boot Basic Authentication 和 OAuth2 在同一个项目中?

Dul*_*ter 7 java intellij-idea spring-security maven spring-boot

是否可以在我的休息应用程序中对某些端点使用 OAuth2,并为其他一些端点使用基本身份验证。它应该都适用于 spring 安全版本 2.0.1.RELEASE。我希望有人能进一步帮助我。

Twi*_*wiN 7

是的,可以使用基本身份验证和 OAuth2 身份验证交织在一起,但我怀疑您能否轻松设置它,因为 HttpSecurity 的authenticated()方法不允许您选择哪种身份验证方法(oauth2Login/formLogin)将工作。

然而,有一种方法可以轻松绕过这个问题:

ROLE_BASICAUTH当用户使用基本身份验证连接时以及ROLE_OAUTH2当用户使用 OAuth2 连接时,您可以添加自定义权限(我们称之为 ) 。这样,您就可以使用

.antMatchers("/endpoint-that-requires-basic-auth").hasRole("BASICAUTH")
.antMatchers("/endpoint-that-requires-oauth2").hasRole("OAUTH2")
    .anyRequest().authenticated()
Run Code Online (Sandbox Code Playgroud)

当他们到达您想要基本身份验证(而不是 OAuth2)的端点时,您检查他们当前的权限,如果不是BASICAUTH,那么您使他们的会话无效,您显示一个没有 OAuth2 的登录表单(以强制他们使用基本身份验证)。

这样做的缺点是您需要同时实现自定义UserDetailsService和自定义OAuth2UserService......

但这实际上并不难:

@Service
public class UserService extends DefaultOAuth2UserService implements UserDetailsService {

    // ...

    @Override
    public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException {
        OAuth2User user = super.loadUser(oAuth2UserRequest);

        Map<String, Object> attributes = user.getAttributes();
        Set<GrantedAuthority> authoritySet = new HashSet<>(user.getAuthorities());
        String userNameAttributeName = oAuth2UserRequest.getClientRegistration().getProviderDetails()
                .getUserInfoEndpoint().getUserNameAttributeName();

        authoritySet.add(new SimpleGrantedAuthority("ROLE_OAUTH2"));

        return new DefaultOAuth2User(authoritySet, attributes, userNameAttributeName);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails user = getUserFromDatabase(username); // you'll need to provide that method (where are the username/password stored?)
        if (user == null) { // UserDetailsService doesn't allow loadUserByUsername to return null, so throw exception
            throw new UsernameNotFoundException("Couldn't find user with username '"+username+"'");
        }
        // add ROLE_BASICAUTH (you might need a custom UserDetails implementation here, because by defaut, UserDetails.getAuthorities() is immutable (I think, I might be a liar)
        return user;
    }

}
Run Code Online (Sandbox Code Playgroud)

请注意,这是一个粗略的实现,因此您也必须自己解决一下。

您还可以使用我制作的此存储库https://github.com/TwinProduction/spring-security-oauth2-client-example/tree/master/custom-userservice-sample作为自定义 OAuth2UserService 的指南

祝你好运。