Spring Security 的自定义访问规则 [英] Custom Access Rules for Spring Security

查看:74
本文介绍了Spring Security 的自定义访问规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常您会定义一些拦截 url 模式来配置对具有 Spring 安全性的页面的访问

Typically you define some intercept-url patterns to configure access to pages with spring security

<http use-expressions="true">
    <intercept-url pattern="/**/secure/**" access="hasRole('ROLE_SECURE_USER')" />
    ...
</http>

我们现在有一些带有事先未知的 url 的页面.但是我们可以编写一段代码来决定是否应该保护特定页面,即如果必须保护页面,我们可以提供返回 true 的服务.所以我们想做的是这样的:

We now have pages with url's that are not known beforehand. But we can write a piece of code to decide whether a specific page should be protected or not, i.e. we can provide a service that returns true if the page has to be protected. So what we'd like to do is something like this:

<http use-expressions="true">
    <intercept decide="@service.mustProtect()" access="hasRole('ROLE_SECURE_USER')" />
    ...
</http>

如何使用 Spring 实现这一点?我们是否必须编写自定义过滤器?您将如何实现这样的过滤器?

How can this be achieved with Spring? Do we have to write a custom filter? How would you implement such a filter?

推荐答案

实际上,通过在 FilterSecurityInterceptor 之前注入自定义过滤器,很容易解决我们的问题.然后,您可以在过滤器的 doFilter 方法中抛出一个 AccessDeniedException 以触发身份验证.

Actually, it was quite easy to solve our problem by injecting a custom filter just before the FilterSecurityInterceptor. You can then throw an AccessDeniedException in the filter's doFilter method to trigger authentication.

Spring 安全配置:

Spring security config:

<http use-expressions="true">
    <custom-filter before="FILTER_SECURITY_INTERCEPTOR" ref="accessFilter"/>
    ...
</http>

<beans:bean id="accessFilter" class="xyz.AccessFilter" />

过滤器:

public class AccessFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!currentUserCanAccessPage(request)) {
            throw new AccessDeniedException();
        }
        chain.doFilter(request,response)
    }

    private boolean currentUserCanAccessPage(ServletRequest request) {
        //implement
    }
}

这篇关于Spring Security 的自定义访问规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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