如何在春季安全编写自定义过滤器? [英] How to write a custom filter in spring security?

查看:185
本文介绍了如何在春季安全编写自定义过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望每个请求都能得到一些信息,所以我认为不是每个请求都有一个函数,而是分别从请求中获取这些信息,所以最好有一个过滤器。

所以每一个请求应通过该过滤器,我得到我想要的。



问题是:如何编写自定义过滤器?

假设它不像任何预定义的弹簧安全过滤器,并且它是全新的。

可以使用标准的Java过滤器。只需将其放置在web.xml中的认证过滤器之后(这意味着它将在后面的过滤器链中并在安全过滤器链之后被调用)。

  public class CustomFilter implements Filter {
$ b $ @Override
public void destroy(){
//什么都不做

$ b @Override $ b $ public void doFilter(ServletRequest req,ServletResponse res,
FilterChain链)throws IOException,ServletException {

HttpServletRequest请求=(HttpServletRequest)req;

身份验证身份验证= SecurityContextHolder.getContext()。getAuthentication();

Set< String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if(roles.contains(ROLE_USER)){
request.getSession()。setAttribute(myVale,myvalue);
}

chain.doFilter(req,res);


$ b @Override
public void init(FilterConfig arg0)throws ServletException {
//什么也不做
}


b

$ b

web.xml片段:

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

<! - 您的过滤器定义 - >
< filter>
< filter-name> customFilter< / filter-name>
< filter-class> com.yourcompany.test.CustomFilter< / filter-class>
< / filter>
< filter-mapping>
< filter-name> customFilter< / filter-name>
< url-pattern> /VacationsManager.jsp< / url-pattern>
< / filter-mapping>

您也可以添加处理程序,在成功登录后调用(您需要扩展SavedRequestAwareAuthenticationSuccessHandler )。 看这里如何做到这一点。我认为这是一个更好的主意。






更新:

或你可以在你的安全过滤器的末尾安装这个过滤器,如下所示:

 < security:filter-chain-映射> 
< sec:filter-chain pattern =/ **
filters =
ConcurrentSessionFilterAdmin,
securityContextPersistenceFilter,
logoutFilterAdmin,
usernamePasswordAuthenticationFilterAdmin,
basicAuthenticationFilterAdmin,
requestCacheAwareFilter,
securityContextHolderAwareRequestFilter,
anonymousAuthenticationFilter,
sessionManagementFilterAdmin,
exceptionTranslationFilter,
filterSecurityInterceptorAdmin,
MonitoringFilter/> <! - 最后的过滤器 - >
< / security:filter-chain-map>

有了你的过滤器,你可以使用这个:

  public class MonitoringFilter extends GenericFilterBean {
@Override $ b $ public void doFilter(ServletRequest request,ServletResponse response,
FilterChain chain)抛出IOException,ServletException {
//实现这个函数让你的过滤器工作

$ / code $ / pre

I want to receive some information per request, so I think instead of having a function for each request and obtaining those information from requests separately, it's better to have a filter.
So every request shall pass that filter and I gain what I want.


The question is: How can I write a custom filter?
Suppose it is not like any predefined spring security filters and it is totally new.

解决方案

You can use the standard Java filter. Just place it after authentication filter in web.xml (this means that it will go later in the filter chain and will be called after security filter chain).

public class CustomFilter implements Filter{

    @Override
    public void destroy() {
        // Do nothing
    }

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

            HttpServletRequest request = (HttpServletRequest) req;

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
            if (roles.contains("ROLE_USER")) {
                request.getSession().setAttribute("myVale", "myvalue");
            }

            chain.doFilter(req, res);

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // Do nothing
    }

}

Fragment of web.xml:

<!-- The Spring Security Filter Chain -->
<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>

<!-- Your filter definition -->
<filter>
    <filter-name>customFilter</filter-name>
    <filter-class>com.yourcompany.test.CustomFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>customFilter</filter-name>
    <url-pattern>/VacationsManager.jsp</url-pattern>
</filter-mapping>

Also you can add handler that will be invoked after successfull login (you need to extend SavedRequestAwareAuthenticationSuccessHandler). Look here how to do this. And I think that this is even better idea.


UPDATED:
Or you can have this filter at the end of your security filters like this:

<security:filter-chain-map>
    <sec:filter-chain pattern="/**"
            filters="
        ConcurrentSessionFilterAdmin, 
        securityContextPersistenceFilter, 
        logoutFilterAdmin, 
        usernamePasswordAuthenticationFilterAdmin, 
        basicAuthenticationFilterAdmin, 
        requestCacheAwareFilter, 
        securityContextHolderAwareRequestFilter, 
        anonymousAuthenticationFilter, 
        sessionManagementFilterAdmin, 
        exceptionTranslationFilter, 
        filterSecurityInterceptorAdmin,
        MonitoringFilter"/> <!-- Your Filter at the End -->
</security:filter-chain-map>

And to have your filter, you may use this:

public class MonitoringFilter extends GenericFilterBean{
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    //Implement this Function to have your filter working
}

这篇关于如何在春季安全编写自定义过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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