how to add interceptor in spring - java

I am using Spring Security 3.0.3 for a project.My user info is loaded from the database. I have following interceptor
<intercept-url pattern="/admin/**" access="ROLE_ADMIN"/>
<intercept-url pattern="/**" access="ROLE_USER"/>
I want to add interceptor to user data. When I logging with user1(requester as role) he can see only specific user1 data.
http://localhost:7009/Test/requester//30351?menuId=app.requester.new
but when I logging with another user2(requester as role) and Enter above URL in browser.
http://localhost:7009/Test/requester//30351?menuId=app.requester.new.
he can see user1 data.
How can I add interceptor so that it restrict another user data.
Following is scenario
1>
login with user1 and he can see following list of data
101
102
103
when i clicks on 102 data it opens details of 102 data.
http://localhost:7009/Test/requester//102?menuId=app.requester.new.
2> login with user2 and he can see following list of data
104
105
106
when i clicks on 105 data it opens details of 105 data.
http://localhost:7009/Test/requester//105?menuId=app.requester.new.
but when i copy user1 link
http://localhost:7009/Test/requester//102?menuId=app.requester.new.
and paste into browser . user2 can see details of user1 data.

You don't filter everything in the spring security configuration but rather do it in view or controller. Here is a very good tutorial which shows you how to use spring security in your case.
http://static.springsource.org/spring-security/site/petclinic-tutorial.html
If you use JSP for your view, you can use spring security taglib to handle the view of user own data and, for other user's data, you will need to put the filtering logic inside the controller and pass them as model to the view. However, the exact solution depends on your application.

One option to do this is to use the Spring Expression Language and a custom Permission Evaluator. Here's what we did to implement a department/sub-department authorization scheme how to control the user authentication using spring mvc. This will allow you to create custom logic to identify what user1 is allowed to see, etc.
Check out http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html. Take a look at the #PostFilter annotation - if your data set is returned as a collection or an array Spring Security can automatically filter out data elements based on your custom Permission Evaluator.

Related

How to logout user when update role with Spring Security

I am working on an application with several roles. Changing this role to admin user should log out the target user.
My first lead was to set up data tables to retrieve the list of active tokens by taking an example from this site:
https://javadeveloperzone.com/spring-boot/spring-boot-oauth2-jdbc-token-store-example/#3_Source_Code
Except that at the connection, the data information is not saved in my tables.
Is it possible to log out a user "by force"?
Yes, there are several ways how you do it.
At the end of the day it invalidates the Authentication object in Spring's security context.

easiest way to configure 3 roles in spring security 4 / JPA / Hibernate

I already have the spring security working for user and admin. Access is granted only for authenticated users, with some pages allowed only for admin. But that's nearly the default configuration.
Now I want to add a third role (let's name it crip) in spring security. The 3 roles are like russian nesting dolls : user has access to 3 pages, crip has access to theses 3 pages + 2 others and the admin is a super user so he has access to everything.
On the hibernate/ JPA side, is it better to use a set of roles for a user with onetomany relation between autorities and user table or just one Role ? This role would be defined hierarchical : Admin > crip > user.
If the definition of roles is the best way to do this, on the spring security side, how do I configure the role inclusion : Admin > crip > user?
I've found #manytoone and #manytomany relationship between users and roles, that's why I'm asking this.
From your question I understood, you already have basic configuration and got it working.
so just add this to intercept url list
if you want to allow access for roles - Admin, crisp or user
<intercept-url pattern="/pagesForCrispAndAdminAndUser**" access="hasAnyAuthority('Admin', 'crisp', 'user')" />
Allow only Admin
<intercept-url pattern="/pagesForAdmin**" access="hasAuthority('Admin')" />
Allow Admin and user
<intercept-url pattern="/pagesForAdminAndUser**" access="hasAnyAuthority('Admin', 'user')" />
documentation here

How to display the username in an additional secured webflow in CAS?

I'm working with a cas implementation and want to extend it by adding a separate spring-webflow. The webflow will be used to manage user specific data that is hosted in a separate web-service. This webflow will be restricted such that a user must first be authenticated in order to access it.
I've added a new flow to cas-servlet.xml as follows:
<webflow:flow-registry id="flowRegistry" flow-builder-services="builder">
...
<webflow:flow-location id="profile" path="/WEB-INF/profile-webflow.xml" />
...
</webflow:flow-registry>
The first state in my profile-webflow.xml is a view to a page that should display the users username ...
<view-state id="accessView" view="profileAccessView" />
The profileAccessView refers to profileAccessView.jsp which I want to display the username of the CAS authenticated user.
<h2>USERNAME</h2>
Is there a way to display the logged in users username here?
I've tried accessing and binding the user info via spring, but I get a null result, i.e. ...
SecurityContextHolder.getContext().getAuthentication()
In the CAS server, users are not authenticated by Spring Security. This question has been asked several times on the CAS mailing lists, I advice you to seek through them, like this one : https://groups.google.com/forum/#!searchin/jasig-cas-dev/username/jasig-cas-dev/-vMzR51b5S0/wbjpdMItHLMJ.

How to ensure the user is logged into the system at the controller level?

I'm using spring MVC, and I have a custom authentication/security system that I had to build.
NOTE: I know of spring security, but my requirements were to do this in a custom way so please not looking for suggestions about using spring's security modules.
When the user logs into the system, it creates a session cookie. When the user visits a page, a interceptor looks for the existance of that cookie, and looks up the session guid in mysql and if it is present that it loads some data and stores it in the request's attributes.
Now for pages where the user has to be logged in, how can I restrict access at the controller level?
I could do this in an interceptor:
if url.contains("projects/") ...
If I want to restrict access to only logged in users in the ProjectController, but this isn't really something I want to do.
But I am looking for maybe a annotation I could add at the controller level, or maybe somehow create a BaseController that all controllers that require a loggedin user will inherit from.
What are my options for something like this?
In ASP.NET, I created a baseController, and the controller has an event cycle, and in the before-action fired event I checked to see if the user was logged in.
So looking for suggestions for spring mvc?
Update
For example, in ASP.NET you have 2 methods, 1 that fires just before the controller's action method and one that fires after:
Controller.OnActionExecuting
Controller.OnActionExecuted
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuting.aspx
So in the OnActionExecuting, I can actually see exactly which controller I am in, and which action is about to get called in a programatic way, not by looking at the request URL and then doing string compares to see if it is a particular controller etc.
So in this event, I can simply check for things in cookies or in my request attributes etc.
This is a much more stable way to do it, does spring have anything similiar?
If you need this at the controller level, you could:
1) declare a java.security.Principal parameter in the controller method signature, which Spring will fill in with a Principal object, or
2) implement a PermissionEvaluator, which can be called on a controller method using the #PreAuthorize annotation, and which would have access to a Authentication object.
Similar to what you did in ASP.NET, you can take advantage of OncePerRequestFilter and chain it to the chain of filters you have in web.xml or Spring application context. The good point about this filter is that it's independent of the MVC approach that you take and no need for a "base controller".
On the other hand, if you're also using Spring security module, you can use a custom filter configuration and place it in the correct place that it should be.
If the check fails, then you'd probably want to raise exceptions or redirect user to the correct navigation.
Based on the last comment, you can also use mapped interceptors:
<mvc:interceptors>
<mvc:interceptor>
<mapping path="/myFirstPath/*"/>
<mapping path="/mySecondPath/*"/>
<bean class="org.example.SomeInteceptor" />
</mvc:interceptor>
<mvc:interceptor>another one</mvc:interceptor>
</mvc:interceptors>

Customized Spring Security without Spring MVC

I am using my own MVC implementation and I am not sure, whether the Spring Security isn't designed specifically for the Spring MVC implementation. Is it still okay to use it?
It is not clear to me, which parts of Spring Security I should use and which I don't need to. I suppose I don't need the URL filters as I need to validate the access specifically on the URL parameters in my controllers (for instance to check whether User is the owner of the Article). Something like:
if (request.getUser().isAllowedTo("EditArticle", 27)) {...}
if (request.getUser().isAllowedTo("CategoryManager", 123)) {...}
if (request.getUser().isInRole("Admin")) {...}
I could not find some clear way of users logging in/out programmatically. I've implemented my UserDetails and UserDetailsService classes to handle the users with JPA, but I don't see a way, how I can proceed with login and logout in my controllers.
EDIT:
I don't see a way how to put the <form> in my Freemarker templates - the only way of creating the form I found is with:
<http pattern="/login.htm*" security="none"/>
<form-login login-page="/login.htm" default-target-url="/home.htm"/>
</http>
How can I configure the structure of the login form? Can I create it by myself?
What I would like the most is to be able to handle the login by myself (for example with DWR) and not to use the magic j_security_checks...
It would be great, if I could handle the login request by myself and ask the auth service to login the user by myself (so I could easily use Direct Web Remoting (DWR)):
if (user.username.ok() and user.password.ok()) {
authService.setUser(user);
authService.setLoggedIn(true);
}
Spring security is not limited to spring mvc and can be used with your own framework implementation. It provides handy services for authentication and session management.
Spring is very convenient to use to leverage access by certain URLs but not limited to. You will be able to get which roles the current user has at the moment from the spring context and all the custom info you would include in your UserDetails object. There are number of ways to restrict access to certain actions by certain roles. However the code like if (request.getUser().isAllowedTo("EditArticle", 27)) {...} I think it will be simplier to check by yourself.
Login and logout are done by calling specific urls. For login: /j_spring_security_check. For logout: /j_spring_security_logout.

Categories