2017-08-21 69 views
1

私はSpringブートWebサービスを開発し、アクセス管理にKeycloakを使用しました。 ウェブサイトには、いくつかのユーザーデータがデータベースに保存されています。これらのデータをログインしたユーザーと接続しようとしています。Spring Keycloak:ユーザーIDを取得

現在、私はユーザー名をデータに保存しています。しかし、私はユーザー名の代わりにユーザーIDを保存するのが好きです。どうやってやるの?

私はこれによってSecurityContextが取得してください:

@Bean 
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) 
public KeycloakSecurityContext getKeycloakSecurityContext() { 
    return ((KeycloakPrincipal<KeycloakSecurityContext>) getRequest().getUserPrincipal()).getKeycloakSecurityContext(); 
} 

しかし、私はエラーを取得する:

There was an unexpected error (type=Internal Server Error, status=500). 
Error creating bean with name 'scopedTarget.getKeycloakSecurityContext' 
defined in com.SiteApplication: Bean instantiation via factory method 
failed; nested exception is 
org.springframework.beans.BeanInstantiationException: Failed to 
instantiate [org.keycloak.KeycloakSecurityContext]: Factory method 
'getKeycloakSecurityContext' threw exception; nested exception is 
java.lang.ClassCastException: 
org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken 
cannot be cast to org.keycloak.KeycloakPrincipal 

は、これは正しい方法ですか?何が欠けている?

ありがとうございました!

答えて

0

私はこのコードで同様のことをしました。

public class AuthenticationTokenProcessingFilter extends GenericFilterBean { 

     @Override 
     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 

      if (!(request instanceof HttpServletRequest)) { 
       throw new RuntimeException("Expecting a HTTP request"); 
      } 

      RefreshableKeycloakSecurityContext context = (RefreshableKeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName()); 

      if (context == null) { 
       handleNoSecurityContext(request, response, chain); 
       return; 
      } 

      AccessToken accessToken = context.getToken(); 
      Integer userId = Integer.parseInt(accessToken.getOtherClaims().get("user_id").toString()); 

      chain.doFilter(request, response); 
     } 

} 

あなたがこれを行うことができます前に、keycloakによって発行されたアクセストークンにuser_idを追加する必要があります。下のスクリーンショットに示すように、これをマッパーで行うことができます。

configuration for property mapper

また、アプリケーションのクラスに@Beanメソッドを追加することで、アプリケーションのライフサイクルに上から処理フィルタを追加するのを忘れないでください。

@Configuration 
@EnableAutoConfiguration(exclude = {FallbackWebSecurityAutoConfiguration.class, SpringBootWebSecurityConfiguration.class, DataSourceAutoConfiguration.class}) 
@ComponentScan 
@EnableAsync 
public class MyServiceClass { 

    public static void main(String[] args) { 
     Properties properties = new Properties(); 
     new SpringApplicationBuilder(MyServiceClass.class) 
       .properties(properties) 
       .bannerMode(Banner.Mode.OFF) 
       .run(args); 
    } 


    @Bean 
    public AuthenticationTokenProcessingFilter authFilter() { 
     return new AuthenticationTokenProcessingFilter(); 
    } 

} 
関連する問題