用户在Spring应用程序中授权后如何添加自定义过滤器 [英] How to add custom filter after user authorize in spring application

查看:178
本文介绍了用户在Spring应用程序中授权后如何添加自定义过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring Security 3的新手.我正在使用角色让用户登录.

I am a newbie to Spring Security 3. I am using roles for users to login.

我想在用户被授权进入应用程序后添加一些会话值.也许我需要一些过滤器,以便将其重定向到添加一些会话值的方法.我已经配置了security.xml文件,但是不确定是否在做正确的事情.朝这个方向的任何例子都会有所帮助.我应该使用哪个过滤器类?我应该如何配置security.xml文件?

I want to add some session value after a user is authorized into the application. Maybe I need some filter so that it redirects to my method which adds some session value. I have configured my security.xml file but I am not sure whether I am doing right things. Any examples in that direction would help. Which Filter Class should I use? How should I configure security.xml file?

<custom-filter ref="authenticationFilter" after="FORM_LOGIN_FILTER "/>

<beans:bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
    <beans:property name="filterProcessesUrl" value="/j_spring_security_check" />
    <beans:property name="authenticationManager" ref="authenticationManager" />
    <beans:property name="authenticationSuccessHandler" ref="successHandler" />
</beans:bean> 

<beans:bean id="successHandler" class="org.dfci.sparks.datarequest.security.CustomAuthorizationFilter"/>

我的过滤器类方法需要添加一些会话值.

My filter class method I need to add some session value.

public class CustomAuthorizationFilter implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication
                .getAuthorities());
        if (roles.contains("ROLE_USER")) {
            request.getSession().setAttribute("myVale", "myvalue");
        }
    }
}

修改代码

我已经修改了security.xml文件和类文件

I have modified my security.xml file and class file

<custom-filter ref="authenticationFilter" after="FORM_LOGIN_FILTER "/>  

public class CustomAuthorizationFilter extends GenericFilterBean {

    /*
     * ServletRequestAttributes attr = (ServletRequestAttributes)
     * RequestContextHolder.currentRequestAttributes(); HttpSession
     * session=attr.getRequest().getSession(true);
     */
    @Autowired
    private UserService userService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        try {
            chain.doFilter(request, response);

                    HttpServletRequest req = (HttpServletRequest) request;
                    HttpSession session = req.getSession(true);
                    Authentication authentication = SecurityContextHolder
                            .getContext().getAuthentication();
                    Set<String> roles = AuthorityUtils
                            .authorityListToSet(authentication.getAuthorities());
                    User user = null;                   
                        if (true) {
                            session.setAttribute("Flag", "Y");
                        } 
            }

        } catch (IOException ex) {
            throw ex;
        }
    }

}

哪个调用每个URL.用户通过身份验证后,仅调用一次过滤器方法有什么选择吗?

Which invokes each and every URL. Is it any alternative to call filter method only once when a user is authenticated?

推荐答案

最后,我能够解决我的问题.我没有使用过滤器,而是添加了仅用于成功登录的处理程序.

Finally I was able to resolved my problem. Instead of using filter I have added handler which only invokes for successful login.

在security.xml中添加了以下行

Following line is added in security.xml

<form-login login-page="/" authentication-failure-url="/?login_error=1" default-target-url="/" always-use-default-target="false"  
        authentication-success-handler-ref="authenticationSuccessHandler"/>
        <logout />

<beans:bean id="authenticationSuccessHandler" class="security.CustomSuccessHandler"/>

我还添加了一个自定义处理程序,用于添加会话属性.

Also I have added one custom handler which add session attribute.

package security;

import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

public class CustomSuccessHandler extends
            SavedRequestAwareAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(final HttpServletRequest request,
            final HttpServletResponse response, final Authentication authentication)
            throws IOException, ServletException {
        super.onAuthenticationSuccess(request, response, authentication);

        HttpSession session = request.getSession(true);

        try {
            if (CurrentUser.isUserInRole("USER")) {
                session.setAttribute("Flag", "user");
            } 
        } catch (Exception e) {
            logger.error("Error in getting User()", e);
        } 
    }

}

这篇关于用户在Spring应用程序中授权后如何添加自定义过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆