【问题标题】:Spring oauth intercept rest api calls and forward from one interceptorSpring oauth 拦截其余 api 调用并从一个拦截器转发
【发布时间】:2016-01-14 02:36:31
【问题描述】:

我已经配置了我所有的 spring 安全和 oauth 令牌获取等

但我是否必须在每个 rest api 调用中验证来自 DB 的用户?

这是我的示例 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;
}

【问题讨论】:

    标签: java spring rest spring-mvc oauth


    【解决方案1】:

    您可以通过实现以下过滤器来拦截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>
    

    【讨论】:

    • 我有这些确切的设置,但拦截器没有捕捉到请求。有什么想法吗?
    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2015-11-22
    • 2014-05-19
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多