0

我正在編寫一個攔截Restful API調用的過濾器,提取一個承載令牌並調用授權服務器進行驗證。Spring Boot Oauth2驗證資源所有者的訪問令牌密碼憑據授予

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

經驗教訓,春季安全oauth2文檔中是遠遠不夠的,忘掉試圖使用框架,而無需通過源代碼完全梳理。另一方面,代碼編寫得很好,易於遵循Dave Syer的榮譽。

1. Here is my config: 

protected void configure(HttpSecurity http) throws Exception { 
     http.csrf().disable();     
     http.authorizeRequests() 
     .antMatchers("/") 
     .permitAll() 
     .and()  
     .addFilterBefore(getOAuth2AuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class) 
     .exceptionHandling();       
    } 
2. Here is my getOAuth2AuthenticationProcessingFilter method 
private OAuth2AuthenticationProcessingFilter getOAuth2AuthenticationProcessingFilter(){  

     // configure token Extractor 
     BearerTokenExtractor tokenExtractor = new BearerTokenExtractor(); 
     // configure Auth manager 
     OAuth2Authenti`enter code here`cationManager 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; 

    } 

這就是所有人。

相關問題