Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access role in JSP using spring security?

I want to print a user role in JSP? I know there is a spring -security tag called as <sec:authentication property="principal.username"/> Using this tag I can access the user name..but how to access and print the current role in jsp?

like image 579
Rajesh Avatar asked Feb 23 '12 13:02

Rajesh


People also ask

How do I check my Spring Security role?

The first way to check for user roles in Java is to use the @PreAuthorize annotation provided by Spring Security. This annotation can be applied to a class or method, and it accepts a single string value that represents a SpEL expression.

Can we use JSP with spring?

properties, Spring MVC will look for view-books. jsp inside the /WEB-INF/jsp/ directory. The above example shows us how to use the JSTL <c:url> tag to link to external resources such as JavaScript and CSS. We normally place these under the ${project.

Which code snippet in Spring Security configure that user page is accessible by the user role?

“/userPage” is used by USER Role to access and perform Normal user activities. “/adminPage” is used by ADMIN Role to access and perform Admin user activities. ADMIN role can access “/userPage” URL too.


2 Answers

Since principal refers to your UserDetails object, if you inspect that object the roles are stored under public Collection<GrantedAuthority> getAuthorities() { .. }.

That said, if you merely want to print the roles on the screen, do this:-

<sec:authentication property="principal.authorities"/>
like image 146
limc Avatar answered Oct 22 '22 10:10

limc


Use getAuthorities or write your own implementation of userdetails and create a convenience method.

or :

<sec:authorize access="hasRole('supervisor')">
 This content will only be visible to users who have
 the "supervisor" authority in their list of <tt>GrantedAuthority</tt>s.
</sec:authorize>

from here .

like image 21
NimChimpsky Avatar answered Oct 22 '22 12:10

NimChimpsky