Spring Security is a lightweight security framework that provides authentication and authorization support in order to secure spring-based applications. It integrates well with Spring MVC and comes bundled with popular security algorithm implementations.
Two major areas of application security are “authentication” and “authorization” (or “access-control”). These are the two main areas that Spring Security targets.
"Authentication" is the assurance that the user is actually the user he is claiming to be, for example, when the user logs into any application and gives his credentials, he authenticates himself. At the authentication level, spring supports various authentication models such as Http Basic authentication, Form Based authentication.
"Authorization" is the assurance that the user is allowed to access only those resources that he is authorized to use. For example, in a corporate application, there are some parts of an application where only admin have access and to some parts all the employees have access. These access rules are determined by the access rights given to each user of the system. At the authorization level, spring targets three main areas: authorizing web request, authorizing whether methods can be invoked and authorizing access to individual domain object instances.
Security Namespace Configuration-
To start using the security namespace in your application context, you first need to make sure that the spring-security-config jar is on your classpath. Then all you need to do is add the schema declaration to your application context file:
<beans xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
...
</beans>
web.xml Configuration-
<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>
This provides a hook into the Spring Security web infrastructure. DelegatingFilterProxy is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security(protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc). Note that you should not use this bean name yourself.
We can now configure the security XML for different security related options like authentication model, login page, access denied page etc..
Authentication Model:
Here we decide which authentication model you will use for your web application. Option could be any of the above(LDAP, Open ID..). Once decided same could be configured via “<authentication-manager></authentication-manager>” tag.
1.
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="password" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="user2" password="password" authorities="ROLE_USER" />
</user-service/>
</authentication-provider>
</authentication-manager>
Here user and their roles have been hard coded in XML itself and user will be authenticated and authorized on given basis. Two user has been created with password as “password” and there are roles are “ROLE_USER, ROLE_ADMIN”.
2.
<authentication-manager>
<authentication-provider ref="ldapActiveDirectoryAuthProvider"></authentication-provider>
</authentication-manager>
<bean id="ldapActiveDirectoryAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="abc.xyz.com"/>
<constructor-arg value="ldaps://abc.xyz.com:636"/>
</bean>
Here user will be authenticated and authorized via LDAP server(In current Situation Active Directory).
3.
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource" />
</authentication-provider>
</authentication-manager>
Here user will be authenticated and authorized on the basis of table(USERS & AUTHORIZATION) in DB. datasource will be used to access the given tables in DB. Structure of the tables should be.
<code class="language-css">
CREATE TABLE USERS (USERNAME VARCHAR2, PASSWORD VARCHAR2,ENABLED VARCHAR2);
CREATE TABLE AUTHORITIES(USERNAME VARCHAR2, AUTHORITY VARCHAR2);
</code>
A Minimal <http> Configuration-
We might have to configure login, logout page and role based URL access.
<http auto-config="true">
<intercept-url pattern="/**" access="ROLE_USER" />
</http>
Which says that we want all URLs within our application to be secured, requiring the role ROLE_USER to access them.
The <http> element is the parent for all web-related namespace functionality.
The <intercept-url> element defines a pattern which is matched against the URLs of incoming requests using an ant path style syntax.
The access attribute defines the access requirements for requests matching the given pattern.
With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request.
The prefix "ROLE_" is a marker which indicates that a simple comparison with the user's authorities should be made.
In other words, a normal role-based check should be used. Access-control in Spring Security is not limited to the use of simple roles (hence the use of the prefix to differentiate between different types of security attributes).
The attribute "auto-config=true" defines three elements
<http>
<form-login />
<http-basic />
<logout />
</http>
The default configuration always chooses http-basic authentication model. If the model needs to be changed to the form-login model, then the following configuration is needed.
Login page configure
<form-login login-page='/login.jsp' default-target-url='/home.jsp' always-use-default-target='true' />
Here we have configured login page as “login.jsp” and user will be redirected to “home.jsp” after login(By default-target-url) always-use-default-target is used to set if user will be redirected to “default-target-url” at all time or not?
If true user will be redirected to home.jsp even user was on any other page when session timed-out.
If false user will not be redirected to home.jsp always means user will be on the same page where users session has timed out or on home.jsp when login for the first time.
Role based URL access configure
<intercept-url pattern="/**" access="ROLE_USER" />
Note*: Now all the URl can be accessed by only those who have the authority of “ROLE_USER”. Static part configuration to bypass all security.
<http pattern=”/login.jsp*” security=”none”/>
Access denied page configuration
<access-denied-handler error-page="/accessdenied.jsp" />
Logout page & logout link configuration
<logout logout-url="/logout" logout-success-url="/logoutPage.jsp" />
Session Management Configuration
<session-management>
<concurrency-control max-sessions="1" error-if-maximum-exceeded="false" />
</session-management>
Here we have defined that user can have 1 session at max.
error-if-maximum-exceeded is used to define what should be happend when user tries to create more then one session.
If it is true : User will get error page stating that user can not have more then one session if it already has one active session.
If it is false: User will not get any error while trying to login to application(Creating another session) but other session will get invalidated and user will have only have new session.
The architecture of secured web requests
How requests are processed?
The Spring Security architecture relies heavily on the use of delegates and servlet filters to provide layers of functionality around the context of a web application request.
The automatic configuration attribute(<http auto-config="true">) in the Spring Security XML configuration file sets up a series of 10 servlet filters, which are applied in a sequence through the use of a Java EE servlet filter chain. The filter chain is a Java EE Servlet API concept specified by the javax.servlet.FilterChain interface that allows a web application to direct that a chain of servlet filters should apply to any given request.
Request travel along the chain, being processed by each filter in turn, finally arriving at the destination servlet(dispatcher servlet).
You may also configure the filter chain entirely from scratch. Although this is tedious, as there are many dependencies to wire, it can provide a high level of flexibility in configuration and application suitability matching.
What does auto-config do behind the scenes?
Provides 3 authentication-related functions:
• HTTP basic authentication
• Form login authentication
• Logout
How users are authenticated?
When a user provides credentials in our login form, these credentials must be verified against a credential store in order to proceed any further in our secured system. Verification of the credentials presented involves a series of logical components that are used to encapsulate aspects of the authentication process.
What is spring_security_login and how did we get here?
when you attempted to hit http://localhost:8080/ you were redirected to the URL http://localhost:8080/spring_security_login
The spring_security_login portion of the URL represents a default login page as named in the DefaultLoginPageGeneratingFilter class. We can use configuration attributes to adjust the name of this page to be something unique to our application.
Let's look at the HTML source of this form to figure out what the UsernamePasswordAuthenticationFilter is expecting:
<form name='f' action='/j_spring_security_check' method='POST'>
User:<input type='text' name='j_username' value=''>
Password:<input type='password' name='j_password'/>
<input name="submit" type="submit"/>
<input name="reset" type="reset"/>
</form>
'/j_spring_security_check' This is a special URL that is watched for by the UsernamePasswordAuthenticationFilter to handle form-based login.
Where do the user's credentials get validated?
In our simple three-step configuration file, we used an in-memory credential store to get up and running quickly:
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user authorities="ROLE_USER" name="guest" password="guest"/>
</user-service>
</authentication-provider>
</authentication-manager>
The DaoAuthenticationProvider is an AuthenticationProvider that provides a thin wrapper to implement the AuthenticationProvider interface and then delegates to an implementation of the o.s.s.core.userdetails. UserDetailsService interface. The UserDetailsService is responsible for returning an implementation of o.s.s.core.userdetails.UserDetails.
Exceptions and others propagate up the filter chain, and are typically expected and handled gracefully by request-processing filters, either by redirecting a user to an appropriate page (login or access denied), or by returning appropriate HTTP status codes, such as HTTP 403 (Access Denied).
How requests are authorized?
The final servlet filter in the default Spring Security filter chain, FilterSecurityInterceptor, is the filter responsible for coming up with a decision on whether or not a particular request will be accepted or denied. At this point the FilterSecurityInterceptor filter is invoked, the principal has already been authenticated, so the system knows that they are valid users. Remember that the Authentication interface specifies a method ( List<GrantedAuthority> getAuthorities() ), which returns a list of authorities for the principal. The authorization process will use the information from this method to determine, for a particular request, whether or not the request should be allowed.
Remember that authorization is a binary decision—a user either has access to a secured resource or he does not. There is no ambiguity when it comes to authorization.
Smart object-oriented design is pervasive within the Spring Security framework, and authorization decision management is no exception. Recall from our discussion earlier in the chapter that a component known as the access decision manager is responsible for making authorization determinations.
In Spring Security, the o.s.s.access.AccessDecisionManager interface specifies two simple and logical methods that fit sensibly into the processing decision flow of requests:
Two major areas of application security are “authentication” and “authorization” (or “access-control”). These are the two main areas that Spring Security targets.
"Authentication" is the assurance that the user is actually the user he is claiming to be, for example, when the user logs into any application and gives his credentials, he authenticates himself. At the authentication level, spring supports various authentication models such as Http Basic authentication, Form Based authentication.
"Authorization" is the assurance that the user is allowed to access only those resources that he is authorized to use. For example, in a corporate application, there are some parts of an application where only admin have access and to some parts all the employees have access. These access rules are determined by the access rights given to each user of the system. At the authorization level, spring targets three main areas: authorizing web request, authorizing whether methods can be invoked and authorizing access to individual domain object instances.
Security Namespace Configuration-
To start using the security namespace in your application context, you first need to make sure that the spring-security-config jar is on your classpath. Then all you need to do is add the schema declaration to your application context file:
<beans xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
...
</beans>
web.xml Configuration-
<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>
This provides a hook into the Spring Security web infrastructure. DelegatingFilterProxy is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security(protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc). Note that you should not use this bean name yourself.
We can now configure the security XML for different security related options like authentication model, login page, access denied page etc..
Authentication Model:
Here we decide which authentication model you will use for your web application. Option could be any of the above(LDAP, Open ID..). Once decided same could be configured via “<authentication-manager></authentication-manager>” tag.
1.
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="password" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="user2" password="password" authorities="ROLE_USER" />
</user-service/>
</authentication-provider>
</authentication-manager>
Here user and their roles have been hard coded in XML itself and user will be authenticated and authorized on given basis. Two user has been created with password as “password” and there are roles are “ROLE_USER, ROLE_ADMIN”.
2.
<authentication-manager>
<authentication-provider ref="ldapActiveDirectoryAuthProvider"></authentication-provider>
</authentication-manager>
<bean id="ldapActiveDirectoryAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="abc.xyz.com"/>
<constructor-arg value="ldaps://abc.xyz.com:636"/>
</bean>
Here user will be authenticated and authorized via LDAP server(In current Situation Active Directory).
3.
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource" />
</authentication-provider>
</authentication-manager>
Here user will be authenticated and authorized on the basis of table(USERS & AUTHORIZATION) in DB. datasource will be used to access the given tables in DB. Structure of the tables should be.
<code class="language-css">
CREATE TABLE USERS (USERNAME VARCHAR2, PASSWORD VARCHAR2,ENABLED VARCHAR2);
CREATE TABLE AUTHORITIES(USERNAME VARCHAR2, AUTHORITY VARCHAR2);
</code>
A Minimal <http> Configuration-
We might have to configure login, logout page and role based URL access.
<http auto-config="true">
<intercept-url pattern="/**" access="ROLE_USER" />
</http>
Which says that we want all URLs within our application to be secured, requiring the role ROLE_USER to access them.
The <http> element is the parent for all web-related namespace functionality.
The <intercept-url> element defines a pattern which is matched against the URLs of incoming requests using an ant path style syntax.
The access attribute defines the access requirements for requests matching the given pattern.
With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request.
The prefix "ROLE_" is a marker which indicates that a simple comparison with the user's authorities should be made.
In other words, a normal role-based check should be used. Access-control in Spring Security is not limited to the use of simple roles (hence the use of the prefix to differentiate between different types of security attributes).
The attribute "auto-config=true" defines three elements
<http>
<form-login />
<http-basic />
<logout />
</http>
The default configuration always chooses http-basic authentication model. If the model needs to be changed to the form-login model, then the following configuration is needed.
Login page configure
<form-login login-page='/login.jsp' default-target-url='/home.jsp' always-use-default-target='true' />
Here we have configured login page as “login.jsp” and user will be redirected to “home.jsp” after login(By default-target-url) always-use-default-target is used to set if user will be redirected to “default-target-url” at all time or not?
If true user will be redirected to home.jsp even user was on any other page when session timed-out.
If false user will not be redirected to home.jsp always means user will be on the same page where users session has timed out or on home.jsp when login for the first time.
Role based URL access configure
<intercept-url pattern="/**" access="ROLE_USER" />
Note*: Now all the URl can be accessed by only those who have the authority of “ROLE_USER”. Static part configuration to bypass all security.
<http pattern=”/login.jsp*” security=”none”/>
Access denied page configuration
<access-denied-handler error-page="/accessdenied.jsp" />
Logout page & logout link configuration
<logout logout-url="/logout" logout-success-url="/logoutPage.jsp" />
Session Management Configuration
<session-management>
<concurrency-control max-sessions="1" error-if-maximum-exceeded="false" />
</session-management>
Here we have defined that user can have 1 session at max.
error-if-maximum-exceeded is used to define what should be happend when user tries to create more then one session.
If it is true : User will get error page stating that user can not have more then one session if it already has one active session.
If it is false: User will not get any error while trying to login to application(Creating another session) but other session will get invalidated and user will have only have new session.
The architecture of secured web requests
How requests are processed?
The Spring Security architecture relies heavily on the use of delegates and servlet filters to provide layers of functionality around the context of a web application request.
The automatic configuration attribute(<http auto-config="true">) in the Spring Security XML configuration file sets up a series of 10 servlet filters, which are applied in a sequence through the use of a Java EE servlet filter chain. The filter chain is a Java EE Servlet API concept specified by the javax.servlet.FilterChain interface that allows a web application to direct that a chain of servlet filters should apply to any given request.
Request travel along the chain, being processed by each filter in turn, finally arriving at the destination servlet(dispatcher servlet).
You may also configure the filter chain entirely from scratch. Although this is tedious, as there are many dependencies to wire, it can provide a high level of flexibility in configuration and application suitability matching.
What does auto-config do behind the scenes?
Provides 3 authentication-related functions:
• HTTP basic authentication
• Form login authentication
• Logout
How users are authenticated?
When a user provides credentials in our login form, these credentials must be verified against a credential store in order to proceed any further in our secured system. Verification of the credentials presented involves a series of logical components that are used to encapsulate aspects of the authentication process.
What is spring_security_login and how did we get here?
when you attempted to hit http://localhost:8080/ you were redirected to the URL http://localhost:8080/spring_security_login
The spring_security_login portion of the URL represents a default login page as named in the DefaultLoginPageGeneratingFilter class. We can use configuration attributes to adjust the name of this page to be something unique to our application.
Let's look at the HTML source of this form to figure out what the UsernamePasswordAuthenticationFilter is expecting:
<form name='f' action='/j_spring_security_check' method='POST'>
User:<input type='text' name='j_username' value=''>
Password:<input type='password' name='j_password'/>
<input name="submit" type="submit"/>
<input name="reset" type="reset"/>
</form>
'/j_spring_security_check' This is a special URL that is watched for by the UsernamePasswordAuthenticationFilter to handle form-based login.
Where do the user's credentials get validated?
In our simple three-step configuration file, we used an in-memory credential store to get up and running quickly:
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user authorities="ROLE_USER" name="guest" password="guest"/>
</user-service>
</authentication-provider>
</authentication-manager>
The DaoAuthenticationProvider is an AuthenticationProvider that provides a thin wrapper to implement the AuthenticationProvider interface and then delegates to an implementation of the o.s.s.core.userdetails. UserDetailsService interface. The UserDetailsService is responsible for returning an implementation of o.s.s.core.userdetails.UserDetails.
Exceptions and others propagate up the filter chain, and are typically expected and handled gracefully by request-processing filters, either by redirecting a user to an appropriate page (login or access denied), or by returning appropriate HTTP status codes, such as HTTP 403 (Access Denied).
How requests are authorized?
The final servlet filter in the default Spring Security filter chain, FilterSecurityInterceptor, is the filter responsible for coming up with a decision on whether or not a particular request will be accepted or denied. At this point the FilterSecurityInterceptor filter is invoked, the principal has already been authenticated, so the system knows that they are valid users. Remember that the Authentication interface specifies a method ( List<GrantedAuthority> getAuthorities() ), which returns a list of authorities for the principal. The authorization process will use the information from this method to determine, for a particular request, whether or not the request should be allowed.
Remember that authorization is a binary decision—a user either has access to a secured resource or he does not. There is no ambiguity when it comes to authorization.
Smart object-oriented design is pervasive within the Spring Security framework, and authorization decision management is no exception. Recall from our discussion earlier in the chapter that a component known as the access decision manager is responsible for making authorization determinations.
In Spring Security, the o.s.s.access.AccessDecisionManager interface specifies two simple and logical methods that fit sensibly into the processing decision flow of requests:
No comments:
Post a Comment