【问题标题】:Spring security allow access only users with specific usernameSpring Security 只允许访问具有特定用户名的用户
【发布时间】:2017-12-21 01:43:04
【问题描述】:

我正在开发一个 Spring Boot 应用程序并编写一个 API 供用户阅读消息。其中一个 URL 是:

/users/USER1/messages

现在,我显然只希望经过身份验证的用户能够访问此 get 请求的内容。但是所有经过身份验证的用户是不够的。我还希望只有拥有用户名的用户 - USER1 才能在此处查看真实内容,其余的应该收到 403 状态。我想出了如何在没有弹簧安全配置的情况下做到这一点(在我的服务中,我正在检查登录的用户名并将其与 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 的消息)。这是我的控制器,我在其中添加了 PreAuthorize 注释

@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);
}

EDIT2:与接受答案中的 cmets 一样,@EnableGlobalMethodSecurity(prePostEnabled=true) 需要包含在安全配置中。一旦包含在内,一切正常。

【问题讨论】:

  • 使用将角色分配给经过身份验证的用户的授权方法

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


【解决方案1】:

我认为你需要 Spring Method Security。文档中的示例几乎就是您的情况:

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

...

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

PS:别忘了@EnableGlobalMethodSecurity!看教程here

【讨论】:

  • 使用了您的建议,但遗憾的是没有效果。为了清楚起见,我已经包含了我的控制器。
  • 你有@EnableGlobalMethodSecurity ?
  • 哦不,我会在哪里包含它? RestController 还是我的 SecurityConfig?如果有帮助,我的 SecurityConfig 上有 @EnableWebSecurity
  • 必须首先启用方法安全注释。见spring.io/blog/2013/07/04/…
猜你喜欢
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
相关资源
最近更新 更多