【问题标题】:Building a Spring security interceptor for a rest service为休息服务构建 Spring 安全拦截器
【发布时间】:2018-08-29 22:32:37
【问题描述】:

我有一个基本的 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>

应用程序安全性.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 现在它没有处理所有请求。您为什么不对休息服务使用基本或摘要身份验证?由于这是 http 规范中的默认设置,因此您现在所做的似乎增加了复杂性。

标签: java spring spring-mvc spring-security


【解决方案1】:

您需要在您的 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 中遇到错误。我说的对吗?
  • 简化帮助很大,但它似乎仍然跳过了文件管理器。我已经编辑了我原来的问题。
  • 我认为你需要删除&lt;http auto-config="true"&gt;
猜你喜欢
  • 2014-11-27
  • 2016-11-16
  • 1970-01-01
  • 2020-01-21
  • 2022-01-08
  • 2014-07-18
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
相关资源
最近更新 更多