spring - 如何配置 Spring Boot Security 以便仅允许用户更新自己的配置文件

标签 spring spring-boot spring-security

我已经实现了基本的 Spring Boot Security 内容,以保护我的 Web 服务。我知道您可以仅向某些用户角色授予对某些服务的访问权限,但是是否也可以向指定用户授予访问权限(用户可以是动态的)?

假设我们有一个社交应用程序,每个用户都有自己的个人资料。通过以下休息服务,他们应该是唯一能够编辑配置文件的人:

@RestController
public class UserController {
    @RequestMapping(method = RequestMethod.PUT, path = "/user/{userId}", ...)
    public UserDetails updateUserDetails(@PathVariable("userId") String userId) {
        // code for updating the description for the specified user
    }}
}

如何使用 Spring Security 确保只有用户本身才能更新他的个人资料?任何其他用户都应被拒绝。有没有一种优雅的方式来配置此行为?

我尝试在 WebSecurityConfig 中找到一种方法,但没有成功。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    // configure authorization for urls
                    .authorizeRequests()
                    // grant access to all users for root path and /home
                    //.antMatchers("/", "/home").permitAll()
                    // here i would like to grant access in the way, that only the user is allowed to perform this request by calling url with his userId
                    .antMatchers(HttpMethod.PUT,"/user/<userId>").and().httpBasic();
      }

实现这种行为的好方法是什么?

最佳答案

我认为实现这样的事情的最佳方法是注入(inject) Principal (包含为此请求登录的用户的对象)进入 Controller ,然后检查用户 ID 或用户名是否匹配。

@RestController
public class UserController {
    @RequestMapping(method = RequestMethod.PUT, path = "/user/{userId}", ...)
    public UserDetails updateUserDetails(@PathVariable("userId") String userId, Principal principal) {

        CustomUserDetails userDetails = (CustomUserDetails) principal;
        if (userDetails.getUserId().equals(userId)) {
            // Update the user
        }
    }}
}

请注意,如果您想添加用户 ID,您将需要一个自定义的 UserDetails 接口(interface),因为默认情况下它仅提供用户名。检查这个question如果你想知道怎么做。

关于spring - 如何配置 Spring Boot Security 以便仅允许用户更新自己的配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45536894/

相关文章:

java - Spring Boot |使用动态 keystore /信任库

java - spring boot 初始化报​​错

ssl - 使用 j_username 和 j_password 作为输入字段名称是否存在安全风险

grails - Spring Security和Grails-自定义URL

java - Spring Boot MVC 不在 JSP 中使用模型值

java - 如何验证具有不同属性要求不同方法调用的spring模型对象?

java - 将系统属性传递给 spring boot

JAVAX JSR 356 Websocket 与 Spring Boot

java - 如何在 Java 中使用 Spring security OAuth2 在资源服务器中动态配置 Httpsecurity?

spring - gradle-aspectj:编织和ajc编译器选项在编译时起作用,但在测试任务中不起作用