首页 > 解决方案 > 为什么OAuth2UserService在WebSecurityConfigurerAdapter下的Spring Boot中没有运行角色授权?

问题描述

我正在尝试按照Spring Security 的文档使用 Spring Security 来实现角色,但我无法运行 OAuth2UserService。

这是我拥有的配置文件和 OAuth2UserService,它遵循他们的文档。终端打印ABC,但不是DEF这样,当我以“/test”页面为例时,它没有运行。我将 Google 身份与 OAuth2 结合使用。

身份验证有效,但不幸的是,这没有。我也试过使用GrantedAuthoritesMapper和其他一些例子,但同样的事情发生了。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .logout(l -> {
            l.logoutSuccessUrl("/").permitAll();})
        .authorizeRequests(a -> a
            .antMatchers("/", "/js/**", "/css/**").permitAll()
            .antMatchers("/test").hasRole("ADMIN")
            .anyRequest().authenticated()
        )
        .csrf(c -> c
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        )
        .oauth2Login(oauth2 -> oauth2
            .userInfoEndpoint(userInfo -> userInfo
                .userService(this.oauth2UserService()
            ))
        );
    }

private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
    final DefaultOAuth2UserService delegate = new DefaultOAuth2UserService();
    System.out.println("ABC");

    return (userRequest) -> {
        System.out.println("DEF");
        OAuth2User oauth2User = delegate.loadUser(userRequest);
        Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

        mappedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        oauth2User = new DefaultOAuth2User(mappedAuthorities, 
                oauth2User.getAttributes(), oauth2User.getName());
        return oauth2User;
    };
}

任何帮助将非常感激。谢谢你。

标签: spring-bootspring-securitygoogle-oauthspring-security-oauth2

解决方案


推荐阅读