Spring Boot Oauth2验证资源所有者密码凭据授权的访问令牌

时间:2017-02-16 17:41:23

标签: spring-security spring-security-oauth2 spring-security-rest

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

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

}

1 个答案:

答案 0 :(得分:5)

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

这是我的配置:

fit.feature_importances_

这是我的getOAuth2AuthenticationProcessingFilter方法:

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