2016-08-22 25 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(...)

  • 實現自己的保安過濾器,處理任何你需要的。