java - Thymeleaf sec:身份验证标签不显示角色
问题描述
我正在尝试使用 sec:authentication="principal.authorities" 标签访问用户在 Thymeleaf 中的角色和权限,以便我可以控制向用户显示的内容。我的目标是检索“ROLE_ADMIN”或“ROLE_USER”,但它似乎是检索与该角色关联的三个权限,“[CHANGE_PASSWORD_PRIVILEGE, READ_PRIVILEGE, WRITE_PRIVILEGE]”。
我希望有人可以帮助我进一步理解 Principal 对象和从 springframework 实现 UserDetails 的 User 类。我对权限属性以及如何从中检索用户的“角色”特别感兴趣。这是我第一次实现这一点,所以我相信我还有更多需要学习的东西。任何帮助是极大的赞赏!
注意*这是我的第一篇文章,所以看起来我的图片有限。我现在会尽量用文字做我最好的。
当前结果和实施
这是在我的 profile.html 页面上呈现的内容。
当前用户角色:[CHANGE_PASSWORD_PRIVILEGE, READ_PRIVILEGE, WRITE_PRIVILEGE]
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security" layout:decorator="layout">
<head>
<title>Profile</title>
</head>
<body>
<h1 layout:fragment="header">Profile</h1>
<div layout:fragment="content" class="container">
Current user name:
<span sec:authentication="principal.username">User</span>
<br/>
Current user name 2:
<span sec:authentication="name">User</span>
<br/>
<br/>
Current user roles:
<span sec:authentication="principal.authorities">[ROLE_USER, ROLE_ADMIN]</span>
<br/>
<div sec:authorize="hasRole('ROLE_ADMIN')">
Current user roles 2:
<span sec:authentication="authorities">[ROLE_USER, ROLE_ADMIN]</span>
</div>
</div>
</body>
</html>
@Service
@Transactional
public class MyUserDetailsService implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserRepository userRepository;
@Autowired
private LoginAttemptService loginAttemptService;
@Autowired
private HttpServletRequest request;
public MyUserDetailsService() {
super();
}
@Override
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException {
try {
final User user = userRepository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException("No user found with username: " + email);
}
log.info("User: " + user.getEmail() + " Password: " + user.getPassword() + "Role: " + user.getRoles());
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), true, true, true, true, getAuthorities(user.getRoles()));
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
private Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roles) {
return getGrantedAuthorities(getPrivileges(roles));
}
private List<String> getPrivileges(Collection<Role> roles) {
final List<String> privileges = new ArrayList<>();
final List<Privilege> collection = new ArrayList<>();
for (final Role role : roles) {
collection.addAll(role.getPrivileges());
}
for (final Privilege item : collection) {
privileges.add(item.getName());
}
return privileges;
}
private List<GrantedAuthority> getGrantedAuthorities(List<String> privileges) {
final List<GrantedAuthority> authorities = new ArrayList<>();
for (String privilege : privileges) {
authorities.add(new SimpleGrantedAuthority(privilege));
}
return authorities;
}
}
这是我从 loadUserByName 方法记录 user.getRole() 时显示的内容。“[角色 [id=4,名称=ROLE_ADMIN]]”
马文
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
用户类
* @param authorities the authorities that should be granted to the caller if they
* presented the correct username and password and the user is enabled. Not null.
*
* @throws IllegalArgumentException if a <code>null</code> value was passed either as
* a parameter or as an element in the <code>GrantedAuthority</code> collection
*/
public User(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
if (((username == null) || "".equals(username)) || (password == null)) {
throw new IllegalArgumentException(
"Cannot pass null or empty values to constructor");
}
this.username = username;
this.password = password;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
}
解决方案
您正在将 传递给Privileges
构造SimpleGrantedAuthority
函数,而您应该传递Roles
.
检查您传入的实际 String 值SimpleGrantedAuthority
,这应该与您在<div sec:authorize="hasRole('ADMIN')">
or中使用的内容匹配<div sec:authorize="hasAuthority('ROLE_ADMIN')">
(如果您需要前缀,则存在差异ROLE_
)
推荐阅读
- excel - 如何使用谷歌表格中的公式 countif () 获取包含该值的特定行号
- python - aiogram bot 如何请求用户的位置?
- python - 我想将字典列表写入 txt 文件
- firebase - ASP.NET Core 更新 HttpContext.User
- python - 如何在 Appium 的多个测试之间保持登录状态?
- python - 使用 Pytorch 库主机名的 Deepspeed -I 错误
- python - 如何捕获 DynamoDB ResourceInUseException Python?
- asyncapi - AsyncAPI 中的关联 ID 是什么?
- javascript - 使用纯 JavaScript 从 URL 获取部分 JSON
- c# - AutoMapper - 整数列表到对象列表