JavaHead
JavaHead

Reputation: 663

Spring Boot Oauth2 Validating Access Token for Resource Owner Password Credentials Grant

I'm writing a filter that would intercept an Restful API call , extract a Bearer token and make a call to an Authorization Server for validation.

I couldn't find one in Spring Boot that does it out of the box, but I'm sure there is a cleaner way to do this. here is what I have (pseudo code):

public class SOOTokenValidationFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    String xAuth = request.getHeader("Authorization");

    // validate the value in xAuth
    if(isValid(xAuth) == false){
        throw new SecurityException();
    }  

    // Create our Authentication and set it in Spring 
      Authentication auth = new Authentication ();
      SecurityContextHolder.getContext().setAuthentication(auth);            

    filterChain.doFilter(request, response);

}
private boolean isValid (String token){

    // make a call to SSO passing the access token and 
    // return true if validated
    return true;
}

}

Upvotes: 2

Views: 12262

Answers (1)

JavaHead
JavaHead

Reputation: 663

Lessons learned, Spring Security Oauth2 documentation is woefully inadequate, forget about trying to use the framework without fully combing through the source code. On the flip side the code is well written and easy to follow kudos to Dave Syer.

Here is my config:

protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();                  
    http.authorizeRequests()
        .antMatchers("/")
        .permitAll()
        .and()      
        .addFilterBefore(getOAuth2AuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
        .exceptionHandling();                        
}

Here is my getOAuth2AuthenticationProcessingFilter method:

private OAuth2AuthenticationProcessingFilter getOAuth2AuthenticationProcessingFilter() {       
    // configure token Extractor
    BearerTokenExtractor tokenExtractor = new BearerTokenExtractor();
    // configure Auth manager
    OAuth2AuthenticationManager manager = new OAuth2AuthenticationManager();
    // configure RemoteTokenServices with your client Id and auth server endpoint
    manager.setTokenServices(remoteTokenServices);

    OAuth2AuthenticationProcessingFilter filter = new OAuth2AuthenticationProcessingFilter();
    filter.setTokenExtractor(tokenExtractor);        
    filter.setAuthenticationManager(manager);
    return filter;
}

Upvotes: 5

Related Questions