2017-11-22 4 views
1

Spring Initializer, 임베디드 Tomcat, Thymeleaf 템플릿 엔진 및 패키지를 실행 가능한 JAR 파일로 사용하여 Spring Boot 웹 애플리케이션을 생성했습니다. 사용스프링 부트 - inMemoryAuthentication 사용하기

기술 :

봄 부팅 2.0.0.M6, 자바 8 받는다는 내 응용 프로그램에서 개발 단계

메모리 인증에 사용하기 위해이 보안 설정 파일이

. 나는 사용자 도메인 개체가 : 내 보안 설정 클래스에서

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

시도해 보셨습니까 Object principal = SecurityContextHolder.getContext(). getAuthentication(). getPrincipal(); if (principal instanceof UserDetails) userName = ((UserDetails) principal) .getUsername(); ? – 3vge

+0

[스프링 보안을 사용하여 InMemoryAuthentication을 통해 기록 된 커스텀 사용자를 얻는 방법] (https://stackoverflow.com/questions/22564532/how-to-get-a-custom-user-logged-via-inmemoryauthentication- with-spring-security) – dur

+0

사용자 지정 사용자를 사용해야하는 경우 다른 질문에서 설명한대로 사용자가 직접 UserDetailsService를 구현해야합니다. 커스텀 사용자가 필요 없다면 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 객체로 전송할 수 있습니다.

관련 문제