I am trying to implement roles with Spring Security by following Spring Security's documentation, but I haven't been able to run the OAuth2UserService.
This is the configuration file that I have and OAuth2UserService, which is following their documentation. The terminal prints ABC, but not DEF so it's not running when I go to the page "/test" as an example. I'm using Google Identity with OAuth2.
The authentication works, but unfortunately this doesn't. I've tried using GrantedAuthoritesMapper and a number of other examples as well, but the same thing happens.
@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;
};
}
Any help would be much appreciated. Thank you.