我想在每个页面上显示全名。我正在使用弹簧安全。但我只能显示用户名。这是代码。
public ModelAndView indexController(ModelMap model)
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
model.addAttribute("fullname", user.getUsername());
return new ModelAndView("index", model);
}
我只能在这里显示用户名,即电子邮件。如何在每个页面上显示全名。
答案 0 :(得分:3)
您可以扩展spring的User
类或在您自己的某个实体中实现UserDetails
接口,并在成功进行身份验证后将该实体的实例放入SecurityContextHolder
。假设您拥有User
实体(不要与春天org.springframework.security.core.userdetails.User
混淆),那么您可以实现UserDetails
界面,如下所示:
@Entity
@Table(name = "users")
public class User implements UserDetails {
private String username;
private String password;
private String firstName;
private String lastName;
private Set<String> roles = new HashSet<>();
public User() {}
public User(String username, String password, Collection<GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.roles = authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
}
@Id
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@ElementCollection
@CollectionTable(name = "roles")
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
@Override
@Transient
public Collection<GrantedAuthority> getAuthorities() {
return roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
}
@Override
@Transient
public boolean isAccountNonExpired() {
return true;
}
@Override
@Transient
public boolean isAccountNonLocked() {
return true;
}
@Override
@Transient
public boolean isCredentialsNonExpired() {
return true;
}
@Override
@Transient
public boolean isEnabled() {
return true;
}
}
然后,您可以定义UserDetailsService
以根据username
搜索用户,并在可能的情况下返回User
实体的实例。如下所示:
@Override
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(username -> {
User user = userRepository.findByUsername(username);
if (user == null) throw new UsernameNotFoundException("Invalid user");
return user;
});
}
最后,当您使用SecurityContextHoler
时,您可以将主体投射到具有User
和firstName
属性的lastName
实体:
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
model.addAttribute("fullname", user.getFirstName() + " " + user.getLastName());