我正在使用spring security进行身份验证。我创建了一个从User
扩展的自定义用户,然后我在我的customServiceDetails(UserDetailsService
的实现)中使用它,我希望能够获得我的自定义用户,所以我尝试这样做:< / p>
public class MyUser extends User implements Serializable {
private static final long serialVersionUID = 1L;
private String uuid;
public MyUser(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities);
}
public MyUser(String username, String password, String uuid,
boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities);
this.uuid = uuid;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
我试图通过这样做来获得当前用户,但它无法正常工作:
(MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
我想知道是否有任何建议?
答案 0 :(得分:1)
试试这个
16.3.3定义@RequestMapping处理程序方法
http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/mvc.html
java.security.Principal
包含当前经过身份验证的用户。
@Secured({"ROLE_REGULAR_USER","ROLE_ADMIN"})
@RequestMapping(value = "/context")
public ModelAndView get(Pricipal principal) {
String username = principal.getName();
// Continue processing...
return null;
}
答案 1 :(得分:0)
我正在使用Zk框架,所以解决方案是这样的:
MyUser user =(MyUser)((UsernamePasswordAuthenticationToken) Executions.getCurrent().getUserPrincipal()).getPrincipal();
我从UsernamePasswordAuthenticationToken