2016-08-22 47 views
1

我使用的是最新的Spring引导+弹簧引导入门的安全一个简单的代理应用程序。目标是用一个单一的途径/方法启动该应用程序:修改春季安全配置,在运行时

@RequestMapping(value = "/api/register", 
    method = RequestMethod.POST, 
    produces = MediaType.APPLICATION_JSON_VALUE) 
@Timed 
public ResponseEntity<?> register(Registration registration) { 

随着安全配置:

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    this.http = http 
     .authorizeRequests() 
     .antMatchers("/api/register").hasAuthority(AuthorityConstants.ADMIN) 
    .and(); 
} 

public HttpSecurity getHttpSecurity() { 
    return http; 
} 

的应用程序的目标将是接受表单的注册请求:

{ 
    "route":"/api/foo/bar", 
    "proxy_location": "http://back-end-server/path/to/resource", 
    "role": "some-authority" 
} 

然后应用程序将与预先定义的方法添加/api/foo/bar路由将代理(向前)未来后端服务的要求。

我知道这是一个愚蠢的一点,真正的用例涉及的WebSockets和动态创建主题。

我现在面临的问题是,我似乎无法更新安全配置SecurityConfigurer完成后。

在代码示例上面,我是缓存给我SecurityConfigurerHttpSecurity对象,然后尝试再次使用该对象来配置一个新的路线:

@Inject 
private SecurityConfigurer security; 

@RequestMapping(value = "/api/register", 
    method = RequestMethod.POST, 
    produces = MediaType.APPLICATION_JSON_VALUE) 
@Timed 
public ResponseEntity<?> allowGetAccounts(Registration registration) { 
    try { 
     security.getHttpSecurity() 
      .authorizeRequests() 
      .antMatchers(registration.getRoute()).hasAuthority(registration.getRole()); 

     ... 

    } catch (Exception e) { 
     log.error("Updating security failed!", e); 
    } 

    return new ResponseEntity<>(null, HttpStatus.OK); 
} 

有什么办法来更新安全配置在运行时动态?

此外,如果任何人有创造的WebSocket主题的任何注释动态,将太感激!

+0

最终目标是向用户的权限列表中添加角色,是否正确? – slambeth

+0

最终目标是向安全配置添加路由,基本上为具有已定义角色的用户打开其他路径。 –

+0

您是否确实收到异常,或者您根本没有看到应用的安全更改? – slambeth

回答

0

您有几种选择:

  • 使用antchMatcher("/some/path").access("@someBean.hasAccess(authentication)")。这使您可以基本上使用应用程序上下文中的任何bean来应用所需的验证。

  • 使用@PreAuthorize("@someBean.hasAccess(authentication)")RequestMapping注释的方法。和以前一样,但作为终端本身的拦截器。

  • 实施您自己的SecurityExpressionHandler并将其插入http.authorizeRequests().expressionHandler(...)

  • 实现自己的保安过滤器,处理任何你需要的。