Skip to content

Instantly share code, notes, and snippets.

@Enigo
Created March 1, 2021 10:43
Show Gist options
  • Save Enigo/cdf4e5261ae13ded41a07604bda50dc6 to your computer and use it in GitHub Desktop.
Save Enigo/cdf4e5261ae13ded41a07604bda50dc6 to your computer and use it in GitHub Desktop.
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String GROUPS = "groups";
@Override
public void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/login**", "/oauth2/authorization/**").permitAll()
.antMatchers("/zoo/add/**").access("hasRole('ADMIN')")
.antMatchers("/zoo/all/**").access("hasAnyRole('ADMIN, USER')")
.anyRequest().authenticated()
.and()
.oauth2Login();
}
@Bean
public GrantedAuthoritiesMapper userAuthoritiesMapper() {
return authorities -> {
final Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
authorities.forEach(authority -> {
if (authority instanceof OAuth2UserAuthority) {
final var role = ((OAuth2UserAuthority) authority).getAttributes().get(GROUPS);
if (Role.USER.name().equals(role)) {
mappedAuthorities.add(new SimpleGrantedAuthority(Role.Code.USER));
} else if (Role.ADMIN.name().equals(role)) {
mappedAuthorities.add(new SimpleGrantedAuthority(Role.Code.ADMIN));
}
}
});
return mappedAuthorities;
};
}
...
private ClientRegistration createClientRegistration() {
return ClientRegistration.withRegistrationId("onelogin")
...
.scope("openid", "profile", "email", GROUPS)
...
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment