2

我正在编写一个过滤器,它将拦截一个 Restful API 调用,提取一个承载令牌并调用授权服务器进行验证。

我在 Spring Boot 中找不到开箱即用的方法,但我确信有一种更简洁的方法可以做到这一点。这是我所拥有的(伪代码):

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;
}

}

4

1 回答 1

5

经验教训,Spring Security Oauth2 文档严重不足,忘记在没有完全梳理源代码的情况下尝试使用框架。另一方面,代码写得很好,很容易追随 Dave Syer 的荣誉。

这是我的配置:

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

这是我的 getOAuth2AuthenticationProcessingFilter 方法:

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;
}
于 2017-02-17T17:54:43.870 回答