2017-11-22 14 views
1

Spring Initializer、埋め込みTomcat、Thymeleafテンプレートエンジン、およびパッケージを実行可能なJARファイルとして使用してSpringブートWebアプリケーションを生成しました。使用Springブート - inMemoryAuthenticationの使用

技術:

春ブーツ2.0.0.M6、Javaの8、Mavenの私は私のアプリでは、開発段階

にメモリ認証に使用するために、このセキュリティ設定ファイルを持っている

。私は、ユーザーのドメインオブジェクトがあります。私のセキュリティ設定クラスで

import org.springframework.security.core.userdetails.UserDetails; 
public class User implements Serializable, UserDetails { 
.. 
} 

@Autowired 
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
       .inMemoryAuthentication() 
       .withUser(User 
         .withDefaultPasswordEncoder() 
         .username(DEV_USER) 
         .password(DEV_PWD) 
         .roles("ADMIN").build()); 
    } 

しかし、私はSecurityContextHolderからユーザーを取得するとき:

:私はエラーを得た
SecurityContextHolder.getContext(). 
       getAuthentication().getPrincipal() 

org.springframework.security.core.userdetails.User cannot be cast to com.iberia.domain.backend.User 

しかし、 ユーザー==>org.springframework.security.core.userdetails.User

SimpleGrantedAuthority ==>org.springframework.security.core.authority.SimpleGrantedAuthority

その後:

UserDetails 
          .withDefaultPasswordEncoder() 
          .username(DEV_USER) 
          .password(DEV_PWD) 
          .roles("ADMIN").build() 
+0

あなたは試しました オブジェクトプリンシパル= SecurityContextHolder.getContext()。getAuthentication()。getPrincipal(); if(principal instanceof UserDetails) userName =((UserDetails)プリンシパル).getUsername(); ? – 3vge

+0

[Springセキュリティを使用してInMemoryAuthentication経由でカスタムユーザをログに記録する方法](https://stackoverflow.com/questions/22564532/how-to-get-a-custom-user-logged-via-inmemoryauthentication- with-spring-security) – dur

+0

カスタムユーザーを使用する必要がある場合は、他の質問に記載されているように、独自の 'UserDetailsS​​ervice'を実装する必要があります。カスタムユーザが必要ない場合は、Spring Securityのユーザを使用できます。 – dur

答えて

0

はあなたがorg.springframework.security.core.userdetails.User

String username = DEV_USER; 
String encodedPassword = //encoded password 
List<SimpleGrantedAuthority> authList = getAuthorities("ADMIN"); 

User user = new User(username, encodedPassword, authList); 

を持っ使用することができますtはUserDetailsオブジェクトを構築する方法を見つけますユーザーオブジェクトをorg.springframework.security.core.userdetails.UserDetailsオブジェクトにキャストできます。オブジェクト

関連する問題