spring security + thymeleaf 判斷登入使用者的許可權
阿新 • • 發佈:2018-12-30
spring security的UserDetailService是我自己定義的。
@Component public class MyUserDetailsService implements UserDetailsService {@Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) { // Get user and his authority from userRepository
user = userRepository.getUserByUsername(username);
Set<GrantedAuthority> authorities = new HashSet<>(); user.getPermissions().forEach(r -> authorities.add(new SimpleGrantedAuthority(r.getValue())));MyUser myUser = new MyUser (username, ....); return myUser;}} MyUser.java,扒的User.java
public class MyUser implementsUserDetails, CredentialsContainer {...}
index.html:
<script th:inline="javascript"> /*<![CDATA[*/ var username = /*[[${name}]]*/ ''; var isAnonymous = [[${#authorization.expression('hasRole(''ROLE_ANONYMOUS'')')}]]; var isSomeAuth = [[${#authorization.expression('hasRole(''SOME_AUTH'')')}]]; var s = [[${#authorization.expression('hasRole(''ROLE_SOME_AUTH'')')}]];
從資料庫獲取的使用者Permission,在前端怎麼都拿不到,返回的結果一直false,但是通過${authentication.principal}列印的結果卻能夠看到。
debug發現expression方法會呼叫org.springframework.security.access.expression.SecurityExpressionRoot的方法hasAnyRole,這個方法會將hasRole()裡的字串加上ROLE_與UserDetails的GrantedAuthority逐個比較,因此,最簡單的方法就是把資料庫中許可權用ROLE_開頭