2017-06-10 28 views
0

我正在尋找正確的方式來添加基於角色的身份驗證,我從JWT中提取角色。Spring過濾器添加角色到令牌請求

理想情況下,我想在驗證發生後從JWT中提取角色。這將通過檢查Web令牌的某些與我們從認證系統獲得的角色相關的字段,keycloak來工作。

我的問題是:是否可以將角色追加到請求中,然後使用http配置來要求這些提取的角色之一?

下面是一些有助於解釋我在做什麼的相關代碼。

在我的WebSecurityConfigurer中,我使訪問令牌可用,其範圍爲每個請求。

@Bean 
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) 
public AccessToken accessToken() { 
    try { 
     HttpServletRequest request = 
      ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) 
       .getRequest(); 
     return ((KeycloakSecurityContext) ((KeycloakAuthenticationToken) request 
      .getUserPrincipal()) 
      .getCredentials()).getToken(); 
    } catch (Exception exc) { 
     return null; 
    } 
} 

然後我重寫了configure方法中http的一些配置。

http 
// Disable session management 
.sessionManagement() 
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
.and() 
// Allow calls to OPTIONS 
.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll() 
.and() 
// Authenticate every other call 
.authorizeRequests().anyRequest().authenticated() 
.and() 
.csrf().disable(); 

理想情況下,我想實現的是一樣的東西:

http.antMatchers("/foo").hasRole("jwt_extracted_role") 

我目前正在創建從令牌中提取角色,然後檢查是否有正確的角色自定義過濾器,但是這是可能比它需要更麻煩。

任何指向哪些配置類的方法,我應該重寫以從請求中提取角色並將它們添加到請求中?

回答

0

我最終解決了這個問題,覆蓋了KeycloakAuthenticationProvider並在WebSecurityConfig中提供了我的覆蓋類作爲bean。我的類是下面:

public class ResourceAwareAuthenticationProvider extends KeycloakAuthenticationProvider { 
    @Override 
    public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
      ... here I add granted authorities from the token's credentials ... 
    } 
} 

然後在我的class WebSecurityConfigurer extends KeycloakWebSecurityConfigurerAdapter我重寫的AuthenticationProvider:

@Bean 
@Override 
public AuthenticationManager authenticationManagerBean() throws Exception { 
    return new ProviderManager(Lists.newArrayList(new ResourceAwareAuthenticationProvider())); 
} 

這讓我做的配置,如:

http.authorizeRequests() 
    .antMatchers("/**").hasAuthority("my-resource-authority") 
+0

出於好奇你是怎麼從錯過Keycloak彈簧安全適配器?開箱即用,你已經可以做'.antMatchers(「/ products *」)。hasRole(「user」)' –

+0

Spring抓住的角色是不完整的。在我的'ResourceAwareAuthenticationProvider'類中,我添加了比框架提供的更多的角色。 – Cramja