为REST服务构建一个Spring安全拦截器

5
我有一个基础的REST服务,使用Spring MVC和@RestController机制提供各种API。现在,我正试图添加一个Spring安全拦截器,以便在访问其他请求之前需要登录(通过特定的REST请求)。想法是拦截器检查请求的活动会话,并将其指向登录服务,如果没有找到活动登录。如果找到了活动登录,则拦截器允许请求通过到正确的URL。
我一直在尝试通过XML文件来调整配置,但一直遇到重定向循环问题。 :( 值得注意的是,我根本没有与此服务器关联的视图。访问是通过我无法访问的GUI的http请求完成的。
以下是我的配置: Web.xml:
    <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml, /WEB-INF/spring/application-security.xml</param-value>
    </context-param>

    <filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/aisrv/*</url-pattern>
</filter-mapping>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>aisrvServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/aisrvServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>aisrvServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Servlet-Context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.bmc.ai.server" />
    <!--- Specific beans for my server -->
</beans:beans>

application-security.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
    http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http pattern="/resources/**" security="none" />

    <http auto-config="true" use-expressions="true">
   <!--       <intercept-url pattern="/login" access="ROLE_ADMIN" /> -->

  <!--       <intercept-url pattern="/logout" access="permitAll" />
        <intercept-url pattern="/accessdenied" access="permitAll" /> -->

        <intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
<!--          <http-basic /> -->
         <form-login default-target-url="/test"  /> 
   <!--     <logout logout-success-url="/logout" />  -->
    </http>

    <authentication-manager alias="authenticationManager">
        <authentication-provider>
            <user-service>
                <user name="user" password="123" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

我相信这是一些非常基本和容易解决的问题,但我似乎找不到头绪。任何帮助都将不胜感激。

============ 编辑 =============== ======= 根据Varun的示例,我已经修改了我的application-security.xml文件,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
    http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http pattern="/resources/**" security="none" />

     <http auto-config="true" use-expressions="true">
  <!-- other filters -->
  <custom-filter ref="myCustomFilter" before="SESSION_MANAGEMENT_FILTER" />  
    <intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
</http>


<beans:bean id="myCustomFilter" class="com.company.server.impl.security.RestFilter">

</beans:bean>


<!--     <http auto-config="true" use-expressions="true">
         <intercept-url pattern="/login" access="ROLE_ADMIN" />

        <intercept-url pattern="/logout" access="permitAll" />
        <intercept-url pattern="/accessdenied" access="permitAll" />

        <intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
         <http-basic />
         <form-login default-target-url="/test"  /> 
       <logout logout-success-url="/logout" /> 
    </http>-->

    <authentication-manager alias="authenticationManager">
        <authentication-provider>
            <user-service>
                <user name="user" password="123" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

并添加了以下 RestFiletClass:

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.GenericFilterBean;

import com.company.server.controller.ExcpetionHandling.GenericErrorExeception;
import com.company.server.interfaces.comm.ICorbaClient;

public class RestFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {

         HttpServletResponse response = ((HttpServletResponse) res);
            HttpServletRequest request = ((HttpServletRequest) req);
            ICorbaClient corba = (ICorbaClient)request.getSession().getAttribute("corba");
            if(corba.getSuccessfulLogin()){
                System.out.println("Authorized through filter");
                chain.doFilter(req, res);
            }else{
                throw new GenericErrorExeception("User unauthorized", null, HttpServletResponse.SC_UNAUTHORIZED);
            }
    }

}

然而,Spring框架似乎完全跳过了该过滤器。我需要将其添加到某个位置或进行更多操作吗?


为什么不使用Spring Security?在我看来,你是在绕过Spring Security而不是使用它。创建一个实现AuthenticationEntryPoint的实现,将其重定向到所需位置。无需拦截器。此外,您的springSecurityFilterChain应映射到/*dispatcherServlet,否则它将无法处理所有请求。为什么不为rest服务使用基本身份验证或摘要身份验证?由于这是http规范中的默认设置,似乎增加了您现在正在进行的复杂性。 - M. Deinum
1个回答

3

您需要在Spring Security XML中添加自定义过滤器。在下面的示例中,一个预先构建的过滤器已经被修改,但是您可以查看这些类作为参考来构建自己的过滤器。

<http use-expressions="true">
  <!-- other filters -->
  <custom-filter ref="myCustomFilter" before="SESSION_MANAGEMENT_FILTER" />  
</http>


<beans:bean id="myCustomFilter" class="com.mycompany.RestFilter">

</beans:bean>

public class RestFilter extends GenericFilterBean {

   // @Override of Filter.doFilter() method
   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
      // Implement
   }
}

Spring Security会在预定义的SESSION_MANAGEMENT_FILTER之前自动调用此过滤器并运行您的代码。


我有点不清楚,这里有一堆Bean,但我不确定应该用我的实现替换哪些。我猜应该是trelta的两个Bean,因为在STS上它们会报错。我是对的吗? - bharel
简化后的代码确实有所帮助,但似乎仍然跳过了过滤器。我已经编辑了我的原始问题。 - bharel
我认为你需要删除 <http auto-config="true"> - Varun Achar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接