Spring Web应用程序中的授权:自定义筛选器与Servelt筛选器和AccessDecisionVoter

时间:2017-01-05 14:33:57

标签: java spring web-applications spring-security servlet-filters

我正在尝试使用Spring保护应用程序的Web资源,并注意到有多种方法可以完成。所有这些工作都按照我的预期做了我需要的工作。

但我想知道这些之间有什么不同,哪一个是最佳实践来在Spring网络应用中进行授权。我无法找到春天的差异documentation(如果有更好的方法可以做到这一点,我愿意学习它们。)

来自javax.servlet.Filter DelegatingFilterProxy +春天web.xml

TestFilter.java

public class TestFilter implements Filter {
    ...
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
    if(someCondition())
        chain.doFilter(req, res);
    else
        ((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "unauthorized!");
    }
    ...
}

web.xml

<filter>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetBeanName</param-name>
        <param-value>testFilter</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>TestFilter</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>

2-自定义过滤器:在TestFilter.java

中将http添加到custom-filter标记applicationContext-web-security.xml
<http pattern="/**" auto-config="true" use-expressions="true" >
        ...
        <custom-filter after="BASIC_AUTH_FILTER" ref="myTestFilter" />
</http>

<beans:bean id="myTestFilter" class="org.myapp.api.auth.TestFilter"/>

3- AccessDecisionVoter:

public class TestDecisionVoter implements AccessDecisionVoter<Object> {
    ...
    @Override
    public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
        if(someCondition())
            return ACCESS_GRANTED;
        else
            return ACCESS_DENIED;
    }
    ...
}

applicationContext-web-security.xml

<http pattern="/**" auto-config="true" use-expressions="true" access-decision-manager-ref="accessDecisionManager" >
        ...
</http>

<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
    <beans:constructor-arg>
        <beans:list>
            <beans:bean
                class="org.springframework.security.web.access.expression.WebExpressionVoter" />
            <beans:bean
                class="org.springframework.security.access.vote.AuthenticatedVoter" />
            <beans:ref bean="roleVoter" />
            <beans:bean
                class="org.myapp.api.auth.TestDecisionVoter" />
            <beans:bean
    </beans:constructor-arg>
</beans:bean>

0 个答案:

没有答案