使用方法级别安全性在Spring安全性中授权请求

时间:2019-02-21 06:07:36

标签: spring spring-security authorization

我正在使用spring和hibernate进行Web应用程序开发。要求是使用方法级安全性实现基于角色的授权。

我的应用程序分为两部分-

  • 登录API -登录API基本使用数据库提供了用户名/密码身份验证,并将生成令牌。
  • 主API -该API负责所有其他功能。

来自客户端的第一个和最后一个(登录/注销)请求将由login-api处理,其余请求将进入main-api。 为了对main-api中的请求进行身份验证,我在main-api中有一个拦截器,该拦截器最终将调用login-api方法来对请求进行身份验证。 因此在main-api上,身份验证是通过login-api完成的,但是我想基于数据库中定义的自定义角色来授权main-api上的每个请求。

以下是我在main-api中的示例控制器

@RestController
public class HealthController {

@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(path = "/health", method = {RequestMethod.GET, RequestMethod.POST})
public ResponseEntity<String> getHealth() {
    System.out.println("HealthController");
    return new ResponseEntity<String>("Hello User!", HttpStatus.OK);
}
}

我真的不知道如何定义自定义角色并基于该角色授权请求。

以下是我在Google上找到的示例WebSecurityConfiguration类。我看到用户名/密码和角色都在此处进行了硬编码。 在我的情况下,我有userId,因此我必须从数据库中获取角色并检查授权。

我希望我的要求是可能的。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication()
            .withUser("greg").password("turnquist").roles("ADMIN").and()
            .withUser("ollie").password("gierke").roles("USER", "ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .httpBasic().and()
    .authorizeRequests()
    .antMatchers("/health").hasRole("ADMIN")
    .antMatchers("/employees/**").hasRole("ADMIN")
    .antMatchers("/employees/**").hasRole("ADMIN").and()
    .csrf().disable();
}
}

0 个答案:

没有答案