【问题标题】:Spring Security secure custom pagesSpring Security 安全自定义页面
【发布时间】:2016-08-07 22:29:17
【问题描述】:

有没有办法配置 Spring Security(使用 Java 配置)以仅保护自定义页面,甚至可以使用 @PreAuthorized 注释?

我的想法是我想保护像 /admin 这样的自定义调用和其他东西(没有在安全配置中对每个调用进行硬编码),它们在控制器中设置在提到的注释下,但其他东西不应该完全使用身份验证。

【问题讨论】:

    标签: java spring security spring-mvc spring-security


    【解决方案1】:

    我很难找到适合我的东西。这样就行了,而且可读性也很好。

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .antMatchers("/admin/**").access("hasRole('ADMIN')")
                .antMatchers("/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin();
    }
    

    以及完整的课程,供那些仍然不在同一页面上的人使用

    package com.your.package.config;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.*;
    
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter
    {
        @Override
        protected void configure(HttpSecurity http) throws Exception
        {
            http.authorizeRequests()
                    .antMatchers("/admin/**").access("hasRole('ADMIN')")
                    .antMatchers("/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
        {
            auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
        }
    }
    

    请注意,不调用 formLogin() 方法会使默认的“/login”返回 404 错误。

    【讨论】:

      【解决方案2】:

      我不确定这是否能回答您的问题,但您可以使用 ant 匹配器来识别某些页面并忽略您的安全配置中的其他页面,如下所示:

      .antMatchers("/**").permitAll()
      

      .antMatcher("/admin/**")
      .authorizeRequests()
      .anyRequest().authenticated() 
      

      【讨论】:

      • stackoverflow.com/questions/35633194/… 在这里您可以找到两个工作示例,也许会有所帮助。
      • 感谢您的回复。第二个版本是我需要的,但这仍然是一个硬代码(“/admin/**”)。但最终结果来自系统的“另一端”——我只是为控制器定义添加了@PreAuthorize("hasRole('ROLE_ANONYMOUS')"),这有助于我从我的那些需要额外的安全措施。
      • 如果你想在你的 java 配置类中完全删除硬编码的值,你可以定义一个带有常量的抽象类,比如 ADMIN_PATH = "/admin/" 并在你的控制器和安全性中使用它配置,甚至更好地在属性文件中定义它。
      • 开始讨厌 Spring Security。在项目重新启动几次后,预定义的 ROLE_ANONUMOUS 停止工作,我不知道为什么。即使在控制器中使用@PreAuthorized 注释,“/”也开始重定向:/login。
      • 很抱歉听到这个消息,我自己不是专家 :-),我会通过添加或删除配置细节来一一测试,直到我完全了解什么可以做和不可以做工作,一步一步做事:-)
      猜你喜欢
      • 2014-10-18
      • 2012-05-21
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 2016-01-17
      • 2020-07-15
      • 1970-01-01
      相关资源
      最近更新 更多