Grails with SpringSecurity, check if the current user can access controller / action

前端 未结 8 2254
轮回少年
轮回少年 2021-02-15 13:57

I\'m currently developing a menu for my application that should be able to display only the controllers that the current user can access (requestmap defined in the database).

8条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-15 14:25

    I'm not sure about in Groovy, but in Java (so I assume Groovy too...) you could do (minus NPE checks):

    GrantedAuthority[] authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    boolean isAdmin = false;
    for(GrantedAuthority authority : authorities) {
        String role = authority.getAuthority();
        if(role != null && role.equals("ROLE_ADMIN")) {
            isAdmin = true;
            break;
        }
    }
    

    As for knowing whether or not the action is supported, you'd have to call the RequestMap service to get the roles for the mapping and see if it contains the found user role.

提交回复
热议问题