百里香sec:authentication tag 不显示角色

0s0u357o  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(257)

我正在尝试使用sec:authentication=“principal.authorities”标记,以便我可以控制向用户显示的内容。我的目标是检索“role\u admin”或“role\u user”,但似乎是检索与该角色关联的三个权限,“[更改\u password\u privilege,读取\u privilege,写入\u privilege]”。
我希望有人能帮助我进一步理解主体对象和从springframework实现userdetails的用户类。我特别感兴趣的是authorities属性以及如何从中检索用户的“角色”。这是我第一次实现这一点,所以我相信有更多的我要学习。非常感谢您的帮助!
注*这是我的第一篇文章,所以我似乎只限于图片。我现在会尽力用文字。
当前成果和执行情况
这是在my profile.html页面上呈现的内容。
当前用户角色:[更改密码权限、读取权限、写入权限]

<!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>

这是myuserdetailsservice实现userdetailsservice

@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,name=role\u admin]]
Maven

<dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    </dependency>

用户.class


* @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));
}
ttisahbt

ttisahbt1#

你正在通过考试 Privileges 进入 SimpleGrantedAuthority 构造函数,而您应该传入 Roles .
检查传入的实际字符串值 SimpleGrantedAuthority ,这应该与您在中使用的内容相匹配 <div sec:authorize="hasRole('ADMIN')"> 或者 <div sec:authorize="hasAuthority('ROLE_ADMIN')"> (如果您需要前缀 ROLE_ (是否)

相关问题