-1

我在我的应用程序中使用 Spring Security。我正在根据角色(管理员、用户)对 API 进行身份验证。有一个 API 端点,我想使用作为参数传递给它的变量的值来限制访问。

我有

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {

    httpSecurity.csrf().disable().exceptionHandling().authenticationEntryPoint(this.unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers("/api/**").authenticated()
            .anyRequest().permitAll();

    httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}

我有一个电话

@PostMapping("/something")
public ResponseEntity<BotResponse> handleRequest(@Valid @RequestBody SomeClass someClass) {
        // if someClass.getSomeValue() is not present in the User permissions, then it should give an unauthorized response.
        return value(someClass);
}

Spring Security 中的用户是:

public Class User {
    String userId;
    String userName;
    String authorities;
    List<String> someList;
    //Getters and setters for variables
}

使用的 SomeClass 是:

public Class SomeClass {
    String someValue;
    String userName;
    ...
    // Getters and Setters
}

如何根据用户的 someList 中是否存在 someClass.getSomeValue 的值来不允许用户?

4

2 回答 2

0

根据您的问题,一种方法是获取存储在 Spring Security Authentication Context 中的 UserDetails,然后根据作为参数传递的值检查此上下文对象中的相关数据。我假设您在安全上下文中存储了所有必需的值。
此检查可以在端点代码本身中完成(如果您有少量此类 API)。如果有多个 API 需要相同的逻辑,您将必须实现仅过滤这些 API 的过滤器(配置可以写在 web.xml 中)或切入点(通过 AOP)。

于 2017-12-18T11:18:45.963 回答
0

也许您可以使用 Spring 的全局方法安全性进行此类授权。

要使用方法级别授权,您需要将以下注释添加到您的安全配置类。

@EnableGlobalMethodSecurity(prePostEnabled = true)

然后@PreAuthorize使用 Spring Expression Language 应用到您的终点。就像是..

@PostMapping("/something")
@PreAuthorize("@someService.checkUserAccess(principal, #someClass)")
public ResponseEntity<BotResponse> handleRequest(@Valid @RequestBody SomeClass someClass) {
        // if someClass.getSomeValue() is not present in the User permissions, then it should give an unauthorized response.
        return value(someClass);
}

@someService是一个 Bean,您将在 Controller 中自动装配并在此定义 checkUserAccess() 方法。就像是 ..

public boolean checkUserAccess(Pricipal principal, SomeClass someClass) {
      // here you can fetch your full user object from db or session (depending on your application architecture)
      // apply what ever logic you want to apply, return true if user has access and false if no.
}

注意/建议- 如果您的应用程序设计允许,您可以将此checkUserAccess()方法添加到您现有的用户服务中,并在控制器中自动连接用户服务。

于 2017-12-18T11:58:24.513 回答