如何在spring security

时间:2016-11-29 09:10:12

标签: java spring spring-mvc 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>

2 个答案:

答案 0 :(得分:1)

请尝试以下

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

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

OR

@Component
public class MyAuthFilter extends UsernamePasswordAuthenticationFilter {

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

答案 1 :(得分:1)

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>