Skip to content

Instantly share code, notes, and snippets.

@yterradas
Created August 22, 2014 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yterradas/eb6a897b00248d9caff9 to your computer and use it in GitHub Desktop.
Save yterradas/eb6a897b00248d9caff9 to your computer and use it in GitHub Desktop.
http.addFilterBefore(customAuthFilter(), SecurityContextPersistenceFilter.class)
.authorizeRequests()
.antMatchers("/**")
.authenticated()
.and()
.exceptionHandling().disable()
.sessionManagement().disable()
.rememberMe().disable()
.x509().disable()
.headers().disable()
.jee().disable()
.requestCache().disable()
.httpBasic().disable()
.csrf().disable()
.anonymous().disable()
.formLogin().disable()
.logout().disable();
public class customAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final Logger log = LoggerFactory.getLogger(getClass());
private RestOperations authTemplate;
private String checkTokenUrl;
public customAuthenticationFilter() {
super(new AntPathRequestMatcher("/**"));
}
@Override
public Authentication attemptAuthentication( final HttpServletRequest request, final HttpServletResponse response )
throws AuthenticationException {
AuthUserDetails authDetails = loadUserDetails(request);
// TODO: remove once provider is sending necessary details
authDetails.setUserId("abcde12345");
authDetails.setUsername("username");
if ( isEmpty(authDetails.getUsername()) || isEmpty(authDetails.getUserId()) ) {
throw new BadCredentialsException("User details does not have sufficient credentials");
}
// NOTE: Ensure OAuth2 provider returns roles. Using ROLE_USER as default
List<? extends GrantedAuthority> authorities = Collections
.unmodifiableList(Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
AuthSSOUser principal = new AuthSSOUser(authDetails.getUsername(), authDetails.getUserId(), authorities);
return new UsernamePasswordAuthenticationToken(principal, null, authorities);
}
public void setAuthTemplate( final RestOperations authTemplate ) {
this.authTemplate = authTemplate;
}
public void setCheckTokenUrl( final String checkTokenUrl ) {
this.checkTokenUrl = checkTokenUrl;
}
private AuthUserDetails loadUserDetails( final HttpServletRequest req ) {
final String authHeader = req.getHeader("Authorization");
log.debug("Authenticating {}", authHeader);
final HttpHeaders headers = new HttpHeaders() {{
set("Authorization", authHeader);
}};
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<AuthUserDetails> authProviderResp = authTemplate
.exchange(checkTokenUrl, HttpMethod.GET, entity, AuthUserDetails.class);
AuthUserDetails authDetails = authProviderResp.getBody();
log.debug("Received {} from OAuth2 provider", authDetails);
return authDetails;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment