Last active
October 24, 2020 14:58
-
-
Save atkiss/d11f7b5c6d21e2607349077afd4f12aa to your computer and use it in GitHub Desktop.
Spring Security config to use ADFS and extract additional attributes from JWT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
public class SecurityConfig extends WebSecurityConfigurerAdapter { | |
@Override | |
protected void configure(HttpSecurity http) throws Exception {// @formatter:off | |
http.cors() | |
.and() | |
.authorizeRequests() | |
.antMatchers(HttpMethod.GET, "/user/info", "/api/foos/**") | |
.hasRole("User") | |
.antMatchers(HttpMethod.POST, "/api/foos") | |
.hasRole("Admin") | |
.anyRequest() | |
.authenticated() | |
.and() | |
.oauth2ResourceServer() | |
.jwt().jwtAuthenticationConverter(getJwtAuthenticationConverter()); | |
} | |
private Converter<Jwt, AbstractAuthenticationToken> getJwtAuthenticationConverter() { | |
JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); | |
converter.setJwtGrantedAuthoritiesConverter(jwt -> getRoleCollection(jwt.getClaim("rol")).stream().map(s -> new SimpleGrantedAuthority("ROLE_" + s)).collect(Collectors.toList())); | |
return converter; | |
} | |
@SuppressWarnings("unchecked") | |
private Collection<String> getRoleCollection(Object roles) { | |
if (roles instanceof String) { | |
return Collections.singletonList(roles.toString()); | |
} else if (roles instanceof Collection) { | |
return (Collection<String>)roles; | |
} else { | |
return Collections.emptyList(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment