2015-10-15 82 views
0

轉發我已經配置了我所有的春季安全和OAuth令牌獲取等春天的OAuth攔截REST API的調用,並從一個攔截器

但我必須驗證從DB用戶在每個REST API調用?

這是我的例子API:

@GET 
@Path("/getUUID") 
public Response getUUID(@Context HttpServletRequest request, final @Context SecurityContext securityContext) { 
    //here do i have to do this in each api or there is one filter that can i write and pass this user object from that to api 
    User loadUser = loadUserFromSecurityContext(securityContext); 
} 

protected User loadUserFromSecurityContext(SecurityContext securityContext) { 

    OAuth2Authentication requestingUser = (OAuth2Authentication) (securityContext).getUserPrincipal(); 
    String principal = requestingUser.getUserAuthentication().getName(); 
    User user = null; 
    user = new UserDAO().getUser(principal); 

    return user; 
} 

回答

0

您可以通過實現以下過濾器攔截API調用:

public class AuthenticationTokenProcessingFilter extends GenericFilterBean { 

AuthenticationManager authManager; 

public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) { 
    this.authManager = authManager; 
} 

@Override 
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {   
    HttpServletRequest httpServletRequest = (HttpServletRequest)request; 

    //access your token here and do what you wanna do with it 
    String authToken = httpServletRequest.getHeader("AUTHORIZATION"); 

    // continue thru the filter chain 
    chain.doFilter(request, response); 
    } 
} 

而在你爲spring-servlet.xml

<http pattern="/api/**" create-session="never" use-expressions="true" 
     entry-point-ref="oauthAuthenticationEntryPoint" xmlns="http://www.springframework.org/schema/security"> 
    <anonymous enabled="false" /> 
    <intercept-url pattern="/api/**" /> 
    <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /> 
    <custom-filter ref="authenticationTokenProcessingFilter" before="FORM_LOGIN_FILTER"/> 
    <access-denied-handler ref="oauthAccessDeniedHandler" /> 
</http> 

<bean id="authenticationTokenProcessingFilter" class="com.yourpackage.AuthenticationTokenProcessingFilter"> 
    <constructor-arg ref="authenticationManager" /> 
</bean> 
+0

我有這些確切的設置,但攔截器沒有收到請求。任何想法 ? –