获取当前用户';thymeleaf sec标记与spring security合作提供的额外信息
我在我的项目中使用了带有spring security的thymeleaf-extras-springsecurity4。问题是我无法通过使用获取当前用户';thymeleaf sec标记与spring security合作提供的额外信息,spring,spring-security,thymeleaf,Spring,Spring Security,Thymeleaf,我在我的项目中使用了带有spring security的thymeleaf-extras-springsecurity4。问题是我无法通过使用获取用户的额外字段(这意味着数据库中除用户名、密码、启用等由用户详细信息提供的用户信息) 以下是我的简单代码: UserEntity(实现UserDetails) 用户存储库 SecurityService(扩展UserDetailService) SecurityConfig(扩展WebSecurity配置适配器) index.html(使用thymel
获取用户的额外字段(这意味着数据库中除用户名
、密码
、启用
等由用户详细信息
提供的用户信息)
以下是我的简单代码:
UserEntity(实现UserDetails)
用户存储库
SecurityService(扩展UserDetailService)
SecurityConfig(扩展WebSecurity配置适配器)
index.html(使用thymeleaf extras springsecurity)
()。我认为我的结构不是一个好的设计,但我不知道确切的原因。对我的课堂设计有什么评论吗
谢谢
如果我的问题太模糊,请让我知道,然后我会更具体地更新此内容。为了在
Thymeleaf
中使用用户数据中包含的其他字段,您必须完成以下步骤
loadUserByUsername
,以便返回您的自定义用户${authentication.getPrincipal()}
,而不是sec
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
// Our own implementation of the Spring Security User.
public class MyUser extends User {
// Here we add the extra fields of our users.
private String phone;
private static final long serialVersionUID = 1L;
public MyUser(String username,
String password,
Collection<GrantedAuthority> authorities,
String phone) {
super(username, password, authorities);
this.phone = phone;
}
public String getPhone() {
return realName;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
import org.springframework.security.core.GrantedAuthority;
导入org.springframework.security.core.userdetails.User;
导入java.util.Collection;
//我们自己实现的Spring安全用户。
公共类MyUser扩展了用户{
//这里我们添加了用户的额外字段。
私人电话;
私有静态最终长serialVersionUID=1L;
公共MyUser(字符串用户名,
字符串密码,
收集当局,
(电话线){
超级(用户名、密码、权限);
this.phone=电话;
}
公共字符串getPhone(){
返回实名;
}
公用无效设置电话(字符串电话){
this.phone=电话;
}
}
步骤2
@Override
public MyUser loadUserByUsername(String userName)
throws AuthenticationException {
// Fetch the user.
UserDetails user = userService.loadUserByUsername(username);
// For each user's authority, add it into our authorities' collection.
Collection<GrantedAuthority> grantedAuthorities = new LinkedList<GrantedAuthority>();
if (user.getAuthorities().size() > 0){
for (Authority authority : user.getAuthorities()) {
// Add a new GrantedAuthority for each user's authorities.
grantedAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
}
}
return new MyUser(user.getUsername(), user.getPassword(), grantedAuthorities, user.getPhone());
}
@覆盖
公共MyUser loadUserByUsername(字符串用户名)
抛出AuthenticationException{
//获取用户。
UserDetails user=userService.loadUserByUsername(用户名);
//对于每个用户的权限,将其添加到我们的权限集合中。
Collection GrantedAuthories=新建LinkedList();
if(user.getAuthories().size()>0){
for(权限:user.getAuthorities()){
//为每个用户的权限添加新的GrantedAuthority。
grantedAuthority.add(新的SimpleGrantedAuthority(authority.getAuthority());
}
}
返回新的MyUser(user.getUsername(),user.getPassword(),grantedAuthority,user.getPhone());
}
步骤3
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
org.thymeleaf.extras
thymeleaf-extras-springsecurity4
步骤4
<th:block th:with="auth=${#authentication.getPrincipal()}">
<p th:text="${auth ? auth.phone : 'NULL'}">Phone</p>
</th:block>
电话
我认为您也可以使用sec
代替authentication.getPrincipal()
像这样
@Service
public class SecurityService implements UserDetailsService {
private UserService userService;
@Autowired
public SecurityService(UserService userService) {
this.userService = userService;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails user = userService.loadUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
return user;
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private SecurityService securityService;
@Autowired
public SecurityConfig(SecurityService securityService) {
this.securityService = securityService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/user/login").anonymous()
.antMatchers("/**").hasAnyRole("ADMIN", "USER")
.and()
.formLogin()
.loginPage("/user/login")
.defaultSuccessUrl("/")
.and()
.logout()
.logoutUrl("/user/logout")
.logoutSuccessUrl("/")
.and()
.exceptionHandling()
.accessDeniedPage("/error/403");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
auth.userDetailsService(securityService).passwordEncoder(passwordEncoder);
}
}
<!DOCTYPE html>
<html lang="ko"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
layout:decorator="layout/base">
<th:block layout:fragment="content">
<h1>Main Page</h1>
<p sec:authentication="principal.username">Username</p>
<p sec:authentication="principal.phone">Phone</p>
</th:block>
@Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
UserInfo activeUserInfo = userInfoDAO.getActiveUser(userName);
GrantedAuthority authority = new SimpleGrantedAuthority(activeUserInfo.getRole());
UserDetails userDetails = (UserDetails)new User(activeUserInfo.getUserName(),
activeUserInfo.getPassword(), Arrays.asList(authority));
return userDetails;
}
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
// Our own implementation of the Spring Security User.
public class MyUser extends User {
// Here we add the extra fields of our users.
private String phone;
private static final long serialVersionUID = 1L;
public MyUser(String username,
String password,
Collection<GrantedAuthority> authorities,
String phone) {
super(username, password, authorities);
this.phone = phone;
}
public String getPhone() {
return realName;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
@Override
public MyUser loadUserByUsername(String userName)
throws AuthenticationException {
// Fetch the user.
UserDetails user = userService.loadUserByUsername(username);
// For each user's authority, add it into our authorities' collection.
Collection<GrantedAuthority> grantedAuthorities = new LinkedList<GrantedAuthority>();
if (user.getAuthorities().size() > 0){
for (Authority authority : user.getAuthorities()) {
// Add a new GrantedAuthority for each user's authorities.
grantedAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
}
}
return new MyUser(user.getUsername(), user.getPassword(), grantedAuthorities, user.getPhone());
}
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<th:block th:with="auth=${#authentication.getPrincipal()}">
<p th:text="${auth ? auth.phone : 'NULL'}">Phone</p>
</th:block>