在springSecurityFilterChain之后拦截服务器响应

时间:2014-10-09 14:53:38

标签: java spring-security servlet-filters

在Web应用程序中,我需要以JSON格式发送服务器响应。为此,我使用了一个自定义servlet过滤器,它工作正常,直到我开始使用spring安全过滤器链进行身份验证。验证成功通过后,我的过滤器会根据需要更改响应,但如果失败,则UsernamePasswordAuthenticationFilter会捕获身份验证异常并以html格式向客户端发送错误响应,然后链中的其他过滤器(包括我的过滤器)完成其工作。那么,你能否提出一些放置我的过滤器或任何其他解决方案以拦截错误响应的变体?

弹簧security.xml文件:

<beans:beans
xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"

xsi:schemaLocation="http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Rest authentication entry point configuration -->
<http use-expressions="true" entry-point-ref="restAuthenticationEntryPoint">

    <intercept-url pattern="/api/companies" access="hasRole('ROLE_SYSADMIN')"/>
    <custom-filter ref="responseFilter" position = "FIRST"/>

    <sec:form-login
        login-processing-url="/api/login"
        username-parameter="username"
        password-parameter="password"
        authentication-success-handler-ref="mySuccessHandler"
        authentication-failure-handler-ref="myFailureHandler"/>

    <sec:logout logout-url="/api/logout" />
</http>

<beans:bean id="responseFilter"
            class="my.app.filters.ResponseFilter"/>

<!-- Connect the custom authentication success handler -->

<beans:bean id="mySuccessHandler"
            class="my.app.security.RestAuthenticationSuccessHandler"/>
<!-- Using default failure handler -->
<beans:bean id="myFailureHandler"
  class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"/>

<beans:bean id="bcrypt"
           class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
    <beans:constructor-arg name="strength" value="10"/>
</beans:bean>

<!-- Authentication manager -->
<authentication-manager alias="authenticationManager">
    <authentication-provider>
        <password-encoder ref="bcrypt"/>
        <jdbc-user-service data-source-ref="dataSource"
                           users-by-username-query="
     SELECT username, password, 'true'
     FROM users
     WHERE username=?;"

                           authorities-by-username-query="
    SELECT username, rolename
    FROM users
    WHERE username=?;"
        />

    </authentication-provider>
</authentication-manager>

<!-- Enable the annotations for defining the secure role -->
<global-method-security secured-annotations="enabled"/>

</beans:beans>

0 个答案:

没有答案