在 hasPermission 表达式中传递 HttpServletRequest

pass HttpServletRequest in a hasPermission expression

在我的 spring 安全配置中,我有以下设置:

    @Override
      protected void configure(HttpSecurity http) throws Exception
      {
          http
        .authorizeRequests()  
            .antMatchers("/login.htm", "/signup.htm").permitAll()
            .antMatchers("/page1.htm", "/page2.htm", "/page3.htm").access("@permission.hasPermission(principal.username))
    ....
    }

包含方法hasPermission 的@permission 是一个@Component bean,它决定主体用户名是否可以访问页面。在 bean 中,我使用我的 dao 方法来确定这一点。但是,我需要更多的知识才能做出决定,因为它不是一个页面。例如,有没有办法知道用户请求的页面并将其传递到 hasPermission 方法中?换句话说,我想做类似的事情:

 .antMatchers("/page1.htm", "/page2.htm", "/page3.htm").access("@permission.hasPermission(principal.username, HttpServletRequest http))

参见方法的第二个参数。这是请求页面的 http 请求,所以我会知道用户请求的是 page1、page2 还是 page3.. 或者,如果我不能将其作为参数传递,我如何在 hasPermission 方法的实现中获取当前请求的页面?

您应该可以使用以下方式访问它:

  @Override
  protected void configure(HttpSecurity http) throws Exception
  {
      http
        .authorizeRequests()  
            .antMatchers("/login.htm", "/signup.htm").permitAll()
            .antMatchers("/page1.htm", "/page2.htm", "/page3.htm").access("@permission.hasPermission(principal.username,request))
....
}

这是因为 WebSecurityExpressionRoot.request 属性 作为 public 最终变量公开