Java Spring security只允许具有特定用户名的用户访问

Java Spring security只允许具有特定用户名的用户访问,java,spring,spring-mvc,spring-boot,spring-security,Java,Spring,Spring Mvc,Spring Boot,Spring Security,我正在开发一个SpringBoot应用程序,并编写一个API,让用户能够阅读消息。其中一个URL是: /users/USER1/messages 现在,我显然只希望经过身份验证的用户能够访问这个get请求的内容。但是,只有所有经过身份验证的用户是不够的。我还希望只有用户名为USER1的用户才能在这里查看真正的内容,其余的用户应该收到403个状态。我知道了如何在没有spring安全配置的情况下实现这一点(在我的服务中,我正在检查登录的用户名并将其与URL中的参数进行比较,只有当它们相等时才继续)

我正在开发一个SpringBoot应用程序,并编写一个API,让用户能够阅读消息。其中一个URL是:

/users/USER1/messages
现在,我显然只希望经过身份验证的用户能够访问这个get请求的内容。但是,只有所有经过身份验证的用户是不够的。我还希望只有用户名为USER1的用户才能在这里查看真正的内容,其余的用户应该收到403个状态。我知道了如何在没有spring安全配置的情况下实现这一点(在我的服务中,我正在检查登录的用户名并将其与URL中的参数进行比较,只有当它们相等时才继续),但我认为应该有一种更简单的方法使用SecurityConfiguration?我当前的配置如下所示:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers(HttpMethod.GET, "/users/**").authenticated()
            .antMatchers("/h2-console/*").permitAll()
                .anyRequest().authenticated()
            .and()
                .formLogin();

        http.csrf().disable();
        http.headers().frameOptions().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("superman").password("superman").roles("USER")
                .and()
                .withUser("admin").password("admin").roles("ADMIN");
    }
}
编辑:下面的答案建议使用方法安全表达式,但它似乎仍然不起作用(如果我作为USER2进行身份验证,我仍然可以读取USER1的消息)。这是我的控制器,我在其中添加了预授权注释

@RequestMapping(method = RequestMethod.GET, value = "/messages", produces = {"application/json"})
@ResponseBody
@PreAuthorize("#userHandle == authentication.name")
public List<Message> getMessages(@PathVariable("userHandle") String userHandle,
                        @RequestParam(value="search", defaultValue="") String search) {
    //todo: change to return DTO not model
    return messageFacade.getMessages(userHandle, search);
}
@RequestMapping(method=RequestMethod.GET,value=“/messages”,products={“application/json”})
@应答器
@预授权(“userHandle==authentication.name”)
公共列表getMessages(@PathVariable(“userHandle”)字符串userHandle,
@RequestParam(value=“search”,defaultValue=“”)字符串搜索){
//todo:更改为将数据返回到not模型
返回messageFacade.getMessages(userHandle,search);
}
EDIT2:正如在accepted answer@EnableGlobalMethodSecurity(Prespenabled=true)中的注释一样,需要在安全配置中包括。一旦包括在内,一切正常。

我想你需要弹簧。文档中的示例几乎就是您的案例:

import org.springframework.data.repository.query.Param;

...

@PreAuthorize("#n == authentication.name")
Contact findContactByName(@Param("n") String name);

注:别忘了
@EnableGlobalMethodSecurity
!请参阅教程

使用授权方法,在该方法中,您将角色分配给经过身份验证的用户使用您的建议,但遗憾的是没有效果。为了清晰起见,我已经包括了我的控制器。您有
@EnableGlobalMethodSecurity
?哦,不,我应该在哪里包括它?RestController还是我的SecurityConfig?我的SecurityConfig上有@EnableWebSecurity,如果必须首先启用该帮助方法安全注释。看见