【发布时间】:2018-05-06 04:15:59
【问题描述】:
我使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎生成了一个 Spring Boot Web 应用程序,并将其打包为可执行 JAR 文件。
使用的技术:
Spring Boot 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
但我找不到构造 UserDetails 对象的方法:
UserDetails
.withDefaultPasswordEncoder()
.username(DEV_USER)
.password(DEV_PWD)
.roles("ADMIN").build()
【问题讨论】:
-
你尝试过 Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) userName = ((UserDetails)principal).getUsername(); ?
-
如果您需要使用自定义用户,您必须实现自己的
UserDetailsService,如另一个问题中所述。如果不需要自定义用户,可以使用 Spring Security 的用户。
标签: java spring spring-mvc spring-boot spring-security