繁体   English   中英

如何在Spring Security中注册自定义过滤器

[英]how to register a custom filter in spring security

在我的spring-security.xml中,我有这个

<custom-filter  before="FORM_LOGIN_FILTER" ref="MyAuthFilter" />

我的自定义过滤器是:

@Component
public class MyAuthFilter extends UsernamePasswordAuthenticationFilter {
@Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
......
}
}

但是在启动时我出现了一个错误:没有名为“ MyAuthFilter”的bean可用。

我的web.xml:

 <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/webproject-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Loads Spring Security config file -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <!-- Spring Security -->
    <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>

尝试以下

<custom-filter before="FORM_LOGIN_FILTER" ref="MyAuthFilter" />

<custom-filter  before="FORM_LOGIN_FILTER" ref="myAuthFilter" />

要么

@Component
public class MyAuthFilter extends UsernamePasswordAuthenticationFilter {

@Component("MyAuthFilter")
public class MyAuthFilter extends UsernamePasswordAuthenticationFilter {

我想您的web.xml上下文配置位置中的问题,我需要为ContextLoaderListener定义一次。

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Loads Spring Security config file -->
<context-param>
    <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/webproject-servlet.xml 
            /WEB-INF/spring-security.xml            
    </param-value>
</context-param>

<!-- Spring Security -->
<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM