Pages

Showing posts with label spring-mvc. Show all posts
Showing posts with label spring-mvc. Show all posts

Thursday, August 29, 2013

Accessing session objects in spring mvc

Yes this is quite simple I know. But I came across a nice article that summarize on how to access session objects spring mvc. The below link explains various methods on how to access session object.

http://www.javaroots.com/2013/08/how-to-get-session-object-in-spring-mvc.html

Tuesday, November 13, 2012

showing and hiding elements based on the user role in spring security


In the previous blog post I showed you how to  provide method level security.  Now let's see how to hide or show elements based on the user role. Well it is quite simple with spring security tag library. just do the following to grant rights to view a specific user role to access some content.

declare the tag lib as follows in the jsp file

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

* Note that in order to use the above library you need to add the spring security tag lib jar file in your class path. you can easily get the dependency from maven repository.

Then go to the element you need to grant rights and surround it with the following block.
<sec:authorize access="hasRole('supervisor')">
</sec:authorize>

Also do not forget to put the following line to your spring security context file.
<beans:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>

Providing method level security

I showed you how to provide basic security in spring mvc with intercept url patterns in here. Now with that knowledge let's see how to provide method level security.

This can be achieved by using @Preauthorize annotation. First you need to enable it. For that you need to add the following line to your dispatcher servlet.


<global-method-security
pre-post-annotations="enabled" />

Then you can use @Preauthorize annotation.
eg : @PreAuthorize("isAuthenticated() and hasRole('ROLE_ADMIN')")

In the above example the method is allowed to execute if the user is authenticated and has the ROLE_ADMIN role.

How ever you can use @Secure annotation as well. For that you need to add the following line to your dispatcher servlet.

<global-method-security secured-annotations="enabled" />

How ever the first method gives you more flexibility to handle the permissions as it is based on expressions.