问题 Java spring-rest / Jersey如何安全的休息路由与过滤器


我在下面使用了以下内容 pom.xml 这实际上确保了   路线, 我看到身份验证过程在浏览器中启动几秒钟

  <filter>
    <filter-name>CsrfFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RestCsrfPreventionFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CsrfFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

现在我有特定的路线,当用户选择它时我需要保护...

@Path("/run")
public class Service {


...

@GET
@Path("connect/{param}")
public Response connectToHost(@PathParam("param") String host) {

我应该怎么做?通过如上所述的pom配置或通过每条路线的代码?


4000
2018-03-01 06:16


起源

我更愿意使用特定的代码 DummyService。这将有助于保持 pom.xml 干净,代码可以在以后阶段正确维护。 - CodeHunter
@Henry - 不,这是我添加的唯一内容 - Nina watcher
@CodeHunter - 你能举例说明应该怎么做吗? - Nina watcher
@Henry - 是的我使用Jersey休息框架 - Nina watcher
不好意思推迟了。您可以查看本教程以获取更多详细信息:youtube.com/...  这是一个简洁的教程,你会在这里获得更多细节。 - CodeHunter


答案:


你的问题中有一些令人困惑的地方,但我会尽力掩饰。

一。过滤设置  - 根据您的问题,您进行了过滤器设置 pom.xml。但实际上过滤器设置总是在 web.xml 文件。如果您错误地命名为pom.xml,则忽略但如果没有,则将过滤器设置移至web.xml。

二。 在你的问题标签中,你提到你的查询与spring-boot,spring-security有关。但是您附加的代码示例表明您可能正在使用jersey来创建rest apis而不使用spring,spring-security。您实际上是尝试在tomcat服务器级别使用较低级别的csrf保护。没关系。

三。 CSRF保护可以与spring security以及tomcat apis一起使用。

四。 如果您想了解Spring安全性如何为休息端点提供csrf保护,则必须在代码中提供以下配置。

@EnableWebSecurity
public class WebSecurityConfig extends
        WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
}

这将为您的应用程序的所有POST,PUT,PATCH,DELETE请求提供csrf保护。参考 - https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html 更多细节。

五。 现在,您的实际问题是如何为您的多条路线提供csrf保护 球衣 基于休息端点...您可以提供多个网址模式,如下所示。

<filter>
    <filter-name>CsrfFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RestCsrfPreventionFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CsrfFilter</filter-name>
    <url-pattern>/run</url-pattern>
    <url-pattern>/path1</url-pattern>
    <url-pattern>/path2</url-pattern>
</filter-mapping>

参考 - https://tomcat.apache.org/tomcat-8.0-doc/config/filter.html#CSRF_Prevention_Filter_for_REST_APIs 有关详细信息 RestCsrfPreventionFilter


7
2018-03-09 07:26





首先应添加过滤器 web.xml中 文件。这应该 不要添加到pom.xml 文件。 pom.xml只是构建项目的清单。

由于最好只为您的CSRF预防过滤器保护某些网址,因此请在过滤器映射中使用特定网址。

提供了上述的示例 /run 路径。

   <filter>
    <filter-name>CsrfFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RestCsrfPreventionFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CsrfFilter</filter-name>
    <url-pattern>/run</url-pattern>
  </filter-mapping>

请参考 这个oracle文档 了解web.xml元素的用法。

要进一步了解过滤请求和响应,请参阅 这个oracle教程

参考 这个实用的教程 了解锄头在xml和注释方法中配置过滤器。请注意,您不必以两种方式进行配置。它可以基于xml或基于注释的方式完成,因为你很舒服。


1
2018-03-06 12:23





你需要一个扩展的类 WebSecurityConfigurerAdapter

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    RequestMatcher csrfRequestMatcher = new RequestMatcher() {

      private AntPathRequestMatcher[] requestMatchers = {
          new AntPathRequestMatcher("/run/connect/**")
      };

      @Override
      public boolean matches(HttpServletRequest request) {
        for (AntPathRequestMatcher rm : requestMatchers) {
          // If request matches specified urls, apply csfr
          if (rm.matches(request)) { return true; }
        }
        return false;
      }

    }; 
    http
      // Enable csrf only on some request matches
      .csrf()
        .requireCsrfProtectionMatcher(csrfRequestMatcher)
      //Other configurations
  }
}

1
2018-03-07 09:52





**

如果您不使用任何其他规范,使用spring安全性来保护休息完整Web服务的最佳方法。

** 1使用Spring方式,您需要声明     过滤映射  - >

<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>/*</url-pattern>
</filter-mapping>  

2.然后你必须创建一个spring-security.xml。你可以声明你的     你想要阻止访问的方法。所以你可以要求一些     在访问该方法之前检查授权。 

          <beans:bean  id="cacheManager" 
        class="org.springframework.cache.support.SimpleCacheManager">
             <beans:property name="caches">
                 <beans:set>
                     <beans:bean  
     class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
                         <beans:property name="name" value="ltPrevileges"/>
                     </beans:bean >
                     <beans:bean  
    class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
                         <beans:property name="name" value="dashboard"/>
                     </beans:bean >
                 </beans:set>
             </beans:property>
         </beans:bean> 

        <beans:bean id="cacheManager" 
    class="org.springframework.cache.ehcache.EhCacheCacheManager" >
           <beans:property name="cacheManager" ref="ehcache"></beans:property>
        </beans:bean>
         <beans:bean id="ehcache" 
             class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" >
              <beans:property name="configLocation" value="classpath:ehcache.xml"></beans:property>
              <beans:property name="shared" value="true"></beans:property>
        </beans:bean>

        <security:http use-expressions="true" auto-config="false"
            entry-point-ref="http403EntryPoint" 
            pattern="/sheel/practice/getBatchDetails"
            create-session="stateless">
            <security:csrf disabled="true" />
            <security:custom-filter position="PRE_AUTH_FILTER"
                ref="authorizationGlobalFilterBean" />
        </security:http>
        </beans:bean>
        <!-- Login auth ends here -->
        <!-- PreAuth starts here -->
        <security:http use-expressions="true" auto-config="false"
            entry-point-ref="http403EntryPoint" pattern="/framework/**"
            create-session="stateless">
            <security:csrf disabled="true" />
            <security:custom-filter position="PRE_AUTH_FILTER"
                ref="siteminderFilter" />
        </security:http>
            <beans:bean id="authorizationGlobalFilterBean"
            class="com.xplanr.framework.security.AuthorizationGlobalFilter">
        </beans:bean>
        <beans:bean id="siteminderFilter"
    class="org.springframework.security.web.authentication.preauth.RequestHeader    AuthenticationFilter">
            <beans:property name="principalRequestHeader" value="sessionId" />
            <beans:property name="authenticationManager" 
    ref="authenticationManager" />
        </beans:bean>
        <security:authentication-manager alias="authenticationManager">
            <security:authentication-provider
                ref="preauthAuthProvider" />
        </security:authentication-manager>
     <beans:bean id="preauthAuthProvider"        
     class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
        <beans:property name="preAuthenticatedUserDetailsService">
                    <beans:bean id="userDetailsServiceWrapper"
                     class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
                    <beans:property name="userDetailsService" 
                           ref="customUserDetailsService" />
                </beans:bean>
            </beans:property>
        </beans:bean>
         <beans:bean id="customUserDetailsService"
            class="com.practice.framework.security.CustomUserDetailsService"> 
       </beans:bean>
        <beans:bean id="http403EntryPoint"      
        class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint">
        </beans:bean>
       <!--PreAuth ends here -->
        </beans:beans>

1
2018-03-09 07:37