【问题标题】:Spring Security permitAll() for one URL under some patternSpring Security permitAll() 用于某种模式下的一个 URL
【发布时间】:2016-12-30 13:41:34
【问题描述】:

我有 /my-app/login url,我想为这个 URL 设置 permitAll()。但是这个页面在 /my-app/** 模式下,只允许注册用户访问。

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http

                .csrf().disable()
                .authorizeRequests()
                    .antMatchers("/my-app/**").access("hasRole('USER')")
                    .and()
                .httpBasic()
                .authenticationEntryPoint(entryPoint());
    }

怎么做?

【问题讨论】:

    标签: spring spring-security basic-authentication


    【解决方案1】:

    .antMatchers("/my-app/**")... 之前添加 .antMatchers("/my-app/login").permitAll() 。请求匹配器存储在一个列表中(按定义它们的顺序排序),Spring 安全性将使用匹配器与当前请求匹配的第一个规则。所以把最具体的放在前面,然后把通用的规则放在后面。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
    
                .csrf().disable()
                .authorizeRequests()
                    .antMatchers("/my-app/login").permitAll()
                    .antMatchers("/my-app/**").access("hasRole('USER')")
                    .and()
                .httpBasic()
                .authenticationEntryPoint(entryPoint());
    }
    

    如果 my-app 是您的应用程序的名称,因此您的应用程序服务器 (Tomcat) 将 url 映射到应用程序的 url,那么您必须在 antMatcher 中省略它,因为antMatcher 仅由应用程序相关 url 配置:/my-app/login 变为 /login/my-app/** 变为 /**

    .anyRequest().permitAll() 添加为authorizeRequests() 的最后一个“匹配器”

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
    
                .csrf().disable()
                .authorizeRequests()
                    .antMatchers("/my-app/**").access("hasRole('USER')")
                    .anyRequest().permitAll()
                    .and()
                .httpBasic()
                .authenticationEntryPoint(entryPoint());
    }
    

    但老实说:您使用了某种黑名单(允许除某些黑名单之外的所有 URL)——这不是推荐的方式(从某些安全角度来看)。因为如果您忘记添加或拼错应该保护的 URL,那么每个主体都可以访问它。更安全的方法是拒绝每个 url,只允许一些(白名单)。

    【讨论】:

    • 添加 .and().authorizeRequests().antMatchers("/my-app/login").permitAll()" 用于登录并添加denyAll() 不是很好吗结束了吗?
    • @amant:你是对的,我以错误的方式理解了这个问题。所以我改变了答案。
    猜你喜欢
    • 2019-03-08
    • 2019-03-10
    • 2016-02-16
    • 2019-04-26
    • 2020-08-21
    • 2022-10-19
    • 2021-11-01
    • 2018-01-31
    • 2019-09-27
    相关资源
    最近更新 更多