【问题标题】:Spring Security configure httpsecuritySpring Security 配置 httpsecurity
【发布时间】:2016-08-08 10:35:37
【问题描述】:

我第一次尝试使用 Spring Security 并且真的被困在这样一个任务上:我有一个默认网页,它应该是默认未经过身份验证的,并且我有一批控制器调用,我想要使用 PreAuthorized 注释确保安全。基本思想是,我想禁用默认的“重定向到登录页面”,但仍然有机会操作 Spring Security 的方法安全复合体。

我正在使用 java 配置,如下所示:

@Configuration
@EnableWebSecurity
public class SpringWebSecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/res/**"); // #3
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();        
    }
}

我知道(或似乎理解)此时我的所有电话都应该被允许(过去两天一直坐在这个上面,显然没有想法)。

我想要保护的控制器的方法是:

@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value="/admin", method = RequestMethod.GET)
public String getAdminPage(Model model){
    return "admin";
}

我知道我可以使用antMatcher添加“/**/admin”并授权对特定url的调用,但总体思路是:

  1. 禁用根目录上的“转到登录页面”(和其他随机控制器映射)。
  2. 从 ajax 下拉菜单(或其他)执行基于 ajax 的手动身份验证。
  3. 当一个随机的未经授权的用户碰到一个在控制器上有一个@PreAuthorized 的页面时,只有这样,他才应该被重定向。

UPD:基本问题是仅在访问被拒绝的情况下调用重定向到登录页面,允许基本站点视图和调用的匿名角色。

【问题讨论】:

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


    【解决方案1】:

    回答我自己的问题(可能不像看起来那么干净)。

    1. 您可以配置 Spring Security Http Security,这样它就不会要求在每个页面上登录:

      @Override
      protected void configure(HttpSecurity http) throws Exception {
      
      http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
      
    2. 要启用方法安全性(PreAuthorize("hasRole('ADMIN')") 等),您需要添加一个注解:

      @EnableGlobalMethodSecurity(prePostEnabled = true)
      

    之后,您需要向 HttpSecurity 对象添加一些内容以捕获“拒绝访问和等”的异常(在其他一些 stackoverflow 问题线程中找到):

        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
    
                @Override
                public void commence(HttpServletRequest request, HttpServletResponse response,
                        AuthenticationException authException) throws IOException, ServletException {
                    if (authException != null) {
                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        response.getWriter().print("Unauthorizated....");
                    }
                }
            });
    

    现在您可以使用@PreAutherized 保护您的控制器和其他组件。希望这会对某人有所帮助。

    但仍然存在一件事 - 当用户未经授权并且我尝试访问某个预授权页面时,将调用上述异常处理程序,返回“未经授权...”消息。但是当用户被授权并且我尝试使用不同的 preAuthorized 角色的页面时,我得到默认的 403 Access Denied。

    【讨论】:

      猜你喜欢
      • 2020-03-04
      • 2017-10-18
      • 2021-06-29
      • 1970-01-01
      • 2016-03-14
      • 2017-09-21
      • 2021-07-04
      • 2023-01-17
      • 2021-12-15
      相关资源
      最近更新 更多