- a login page or basic http auth
- some way to specifiy mutiple users, each user having mutiple roles
- role based access for some screens / URls in the web app
- logout url
- automatic redirection of non-authenticated user access to the login page
Hence the need to quicky provide about web app security features without writing a single line of code only through some basic spring security configuration.
Details as below:
1. Download spring security and put the jars in the build and runtime classpath
2. in web.xml add the following filter and filter-mapping entry
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. in web.xml, in the base spring application context, load a spring config file like security-beans.xml with following contents
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/existing-spring-contexts.xml,WEB-INF/security-beans.xml</param-value>
</context-param>
contents of security-beans.xml
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/mvc/admin/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/mvc/general/**" access="hasRole('ROLE_SPITTER')" />
<intercept-url pattern="/**" access="isFullyAuthenticated()" />
</http>
<user-service id="userService">
<user name="all" password="all" authorities="ROLE_REGULAR_USER,ROLE_ADMIN" />
<user name="gan" password="gan" authorities="ROLE_REGULAR_USER" />
<user name="admin" password="admin" authorities="ROLE_ADMIN" />
</user-service>
<authentication-manager>
<authentication-provider user-service-ref="userService" />
</authentication-manager>
Explanation
Here the auto-config=true gives us a ready-made(stock) login page, which can be overriden with our own custom login page
login url: http://localhost:8081/MyWebAppContext/j_spring_security_login
logout url: http://localhost:8081/MyWebAppContext/j_spring_security_logout
userService bean allows us to specify sample userids, and their roles, accessible throughout our application through standard j2ee apis and also spring security tags on jsps
<security:authentication property="principal.username" />
<security:authorize access="hasRole('ROLE_ADMIN')">
<h2>Admin Area keep Off!</h2>
</security:authorize>
Through entry like <intercept-url pattern="/mvc/admin/**" access="hasRole('ROLE_ADMIN')" />
we can very welll control access to certain URLs in the web application for specific users and roles
Summary
Thus without writing a single line of code using spring security config we can impart quick web security to our POCs
Please refer spring security documentation for further details
http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
No comments:
Post a Comment