简体   繁体   中英

Spring security - Access to a controller method based on an attribute

I'm configuring Spring Security across all my controllers. I want some method executions to start only when "my system is enabled". This information is accessible from all over the controllers via a specific static method (I can make it non-static). My point is that I want to avoid making an explicit check in java code at the beginning of every method. How can I get there via Spring Security?

One approach is to use a handler interceptor .

Here is general idea:

(1) Configure url patterns which you want to block:

<util:list id="sysEnableCheckUrlPatterns" value-type="java.lang.String">
    <beans:value>/module1/**</beans:value>
    <beans:value>/module2/**</beans:value>
</util:list>

(2) Write an interceptor:

    public class SysEnableCheckInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {


            /* 
                If system enabled then return true. Otherwise return false (and optionally write something in response)

            */
    }
}

(3) Configure that interceptor. In 3.1 you can do it as follows:

    @Configuration
public class AppConfig extends WebMvcConfigurerAdapter {

    @Resource(name="sysEnableCheckUrlPatterns")
    /* or use @Autowired or @Inject if you like */
    private String[] sysEnableCheckUrlPatterns;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

    registry.addInterceptor(new SysEnableCheckInterceptor()).addPathPatterns(sysEnableCheckUrlPatterns);

    }

}

You can use SPEL (Spring Expression Language) in a security annotation.

See http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM