Java 如何使用Spring安全性保护URL?

Java 如何使用Spring安全性保护URL?,java,spring,url,spring-mvc,spring-security,Java,Spring,Url,Spring Mvc,Spring Security,我正在使用Spring MVC+Spring Security开发一个web应用程序,我有以下URL: /*this URL should be accessible by any User, i.e. users should be able to see other users' profiles*/ /users/someUserId/profile /* all the following URLs should be accessed only by the current auth

我正在使用Spring MVC+Spring Security开发一个web应用程序,我有以下URL:

/*this URL should be accessible by any User, i.e. users should be able to see other users' profiles*/
/users/someUserId/profile

/* all the following URLs should be accessed only by the current authenticated user */
/users/someUserId/profile/edit
/users/someUserId/picture/edit
/users/someUserId/notifications
/users/someUserId/friends
我需要像前面描述的那样保护它们

我的配置方法如下所示:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .regexMatchers("/users/[\\w]+/profile").authenticated()
                .antMatchers("/users/[\\w]/**").access("principal.name == regexGroupMatch")
                .anyRequest().authenticated()               
            .and()
                .jee().mappableRoles("Admin", "User");
    }
我想知道是否有可能实现这样的目标:

.antMatchers("/heroes/[\\w]/**").access("principal.name == regexGroupMatch")
通过这样做,我只希望用户user1能够访问URL:

/users/user1/profile/edit
/users/user1/picture/edit
/users/user1/notifications
因此,user2必须不能访问前面提到的URL,但必须能够访问: /用户/user1/profile/edit /用户/user1/图片/编辑 /用户/user1/通知

以及:

/users/user1/profile
/users/user2/profile
/users/user3/profile
etc...

使用Spring安全性可以实现这一点吗?

Spring安全性将确保访问这些端点的客户端经过身份验证,但由您来确保端点只返回允许用户查看的数据。想想看——Spring Security如何知道每个用户都可以看到应用程序中的哪些数据

您可能已经有了一个如下所示的控制器方法:

@RequestMapping(value = "/users/{user}/profile/edit", method = RequestMethod.GET)
public ModelAndView edit(
    HttpServletRequest request, 
    @PathVariable("user") String,
    EditRequest edit) {

    // Accept or reject the request if the user variable and authenticated
    // user match up as required.
}
这里,您需要以编程方式区分经过身份验证的用户(可从请求对象检索)和上下文声明的用户。如果上下文中的用户是经过身份验证的用户,您可能会接受该请求,因为用户可能被允许修改自己的配置文件。否则,您可以抛出某种授权异常——或者更好的是,返回一个很好的视图,解释为什么该页面不可访问


请注意,这也可以重写为筛选器,因为您没有使用请求正文中的任何信息。这个过滤器确实可以插入到Spring Security中。

不,没有在正则表达式中提取匹配组并将其与用户名进行比较的功能。另外,请注意,ant模式根本不支持正则表达式

在任何情况下,依赖复杂的URL模式都不是一个好主意。对于这种情况,最好在控制器级别或某些服务接口上使用方法安全性,在这些接口上,您可以按名称引用方法参数。例如,启用方法安全表达式后,您可以编写

@PreAuthorize("#user.name == authentication.name")
public void editUser(User user) {
  ....
}

或者,正如Misha所说,您可以直接编写规则,如果事情变得比简单的表达式更复杂,这一点更可取。

您读过文档吗?是的@chrylis,我读过文档。我相信我可以通过
.antMatcher(url)
实现这一点,但我不知道应该使用哪种方法,以便只允许当前用户查看自己的个人资料。顺便说一句,你读过吗?嗯,为了简化它,我更改了我的url模式。正如您所建议的,保护服务层也是一个好主意。