-1

我在我的应用程序中使用了Spring Security。我基于角色(ADMIN,USER)对API进行身份验证。 有一个API端点,我想使用作为参数传递给它的变量的值来限制访问。使用类中的变量值进行身份验证的Spring Security

@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的值,我该如何拒绝用户?

回答

0

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

0

也许你可以用spring的全局方法安全性来做这样的授权。

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

@EnableGlobalMethodSecurity(prePostEnabled = true) 

然后使用Spring表达式语言,你的终点适用@PreAuthorize。喜欢的东西..

@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,你会自动连接的控制器,并确定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. 
} 

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

相关问题