Spring Security Tutorial For Beginner
Before getting start with Spring security implementation, you must know what is Spring Security Framework? What are the basic term of Spring Security? How Spring Security works? Lets know about Spring Security Framework ans its security Implementation.
What is Spring Security?Before getting start with Spring security implementation, you must know what is Spring Security Framework? What are the basic term of Spring Security? How Spring Security works? Lets know about Spring Security Framework ans its security Implementation.
Spring Security provides comprehensive security services for J2EE-based enterprise software applications.
There is a particular emphasis on supporting projects built using The Spring Framework, which is the leading J2EE solution for enterprise software development.
There is a particular emphasis on supporting projects built using The Spring Framework, which is the leading J2EE solution for enterprise software development.
As you probably know two major areas of application security are “authentication” and “authorization” (or “access-control”). These are the two main areas that Spring Security targets.
Authentication: “Authentication” is the process of establishing a principal is who they claim to be (a “principal” generally means a user, device or some other system which can perform an action in your application).
Authorization: “Authorization” refers to the process of deciding whether a principal is allowed to perform an action within your application.
Authorization: “Authorization” refers to the process of deciding whether a principal is allowed to perform an action within your application.
At an authentication level, Spring Security supports a wide range of authentication models as below:
1) HTTP BASIC authentication headers (an IETF RFC-based standard)
2) HTTP Digest authentication headers (an IETF RFC-based standard)
3) HTTP X.509 client certificate exchange (an IETF RFC-based standard)
4) LDAP (a very common approach to cross-platform authentication needs, especially in large environments)
5) Form-based authentication (for simple user interface needs)
6) OpenID authentication
7) Authentication based on pre-established request headers (such as Computer Associates Siteminder)
8) JA-SIG Central Authentication Service (otherwise known as CAS, which is a popular open source single sign-on system)
9) Transparent authentication context propagation for Remote Method Invocation (RMI) and HttpInvoker (a Spring remoting protocol)
10) Automatic "remember-me" authentication (so you can tick a box to avoid re-authentication for a predetermined period of time)
11) Anonymous authentication (allowing every unauthenticated call to automatically assume a particular security identity)
12) Run-as authentication (which is useful if one call should proceed with a different security identity)
13) Java Authentication and Authorization Service (JAAS)
14) JEE container autentication (so you can still use Container Managed Authentication if desired)
15) Kerberos
16) Java Open Source Single Sign On (JOSSO) *
17) OpenNMS Network Management Platform *
18) AppFuse *
19) AndroMDA *
20) Mule ESB *
21) Direct Web Request (DWR) *
22) Grails *
23) Tapestry *
24) JTrac *
25) Jasypt *
26) Roller *
27) Elastic Path *
28) Atlassian Crowd *
29) Your own authentication systems (see below)
(* Denotes provided by a third party)
Many independent software vendors (ISVs) adopt Spring Security because of this significant choice of flexible authentication models. Doing so allows them to quickly integrate their solutions with whatever their end client’s need, without undertaking a lot of engineering or requiring the client to change their environment.
If none of the above authentication mechanisms suit your needs, Spring Security is an open platform and it is quite simple to write your own authentication mechanism
Irrespective of the authentication mechanism, Spring Security provides a deep set of authorization capabilities. There are three main areas of interest -
1) Authorizing web requests,
2) Authorizing whether methods can be invoked,
3) Authorizing access to individual domain object instances.
History
Spring Security began in late 2003 as “The Acegi Security System for Spring”. Acegi Security became an official Spring Portfolio project towards the end of 2007 and was rebranded as “Spring Security”.
Core Components
v SecurityContextHolder, to provide access to the SecurityContext.
v SecurityContext, to hold the Authentication and possibly request-specific security information.
v Authentication, to represent the principal in a Spring Security-specific manner.
v GrantedAuthority, to reflect the application-wide permissions granted to a principal.
v UserDetails, to provide the necessary information to build an Authentication object from your application's DAOs or other source of security data.
v UserDetailsService, to create a UserDetails when passed in a String-based username (or certificate ID or the like).
Authentication managers
The first of the security interceptor’s tumblers to be tripped is the authentication manager. The authentication manager is responsible for determining who you are. It does this by considering your principal (typically a username) and your credentials (typically a password).
Access decisions managers
Once Spring Security has determined who you are, it must decide whether you are authorized to access the secured resource. An access decision manager is the second tumbler of the Spring Security lock to be tripped. The access decision manager performs authorization, deciding whether to let you in by considering your authentication information and the security attributes that have been associated with the secured resource.
For example, the security rules may dictate that only supervisors should be allowed access to a secured resource. If you have been granted supervisor privileges then the second and final tumbler, the access decision manager, will have been tripped and the security interceptor will move out of your way and let you gain access to the secured resource.
Run-as managers
If you’ve gotten past the authentication manager and the access decision manager then the security interceptor will be unlocked and the door is ready to open. But before you twist the knob and go in, there’s one more thing that the security interceptor might do. Even though you’ve passed authentication and been granted access to a resource, there may be more security restrictions behind the door. For example, you may be granted the rights to view a web page, but the objects that are used to create that page may have different security requirements than the web page. A run-as manager can be used to replace your authentication with an authentication that allows you access to the secured objects that are deeper in your application.
After-invocation managers
Spring Security’s after-invocation manager is a little different from the other security manager components. Whereas the other security manager components perform some form of security enforcement before a secured resource is accessed, the after-invocation manager enforces security after the secured resource is accessed.
Design of the Namespace
The namespace is designed to capture the most common uses of the framework and provide a simplified and concise syntax for enabling them within an application. The design is based around the large-scale dependencies within the framework, and can be divided up into the following areas:
v Web/HTTP Security - the most complex part. Sets up the filters and related service beans used to apply the framework authentication mechanisms, to secure URLs, render login and error pages and much more.
v Business Object (Method) Security - options for securing the service layer.
v AuthenticationManager - handles authentication requests from other parts of the framework.
v AccessDecisionManager - provides access decisions for web and method security. A default one will be registered, but you can also choose to use a custom one, declared using normal Spring bean syntax.
v AuthenticationProviders - mechanisms against which the authentication manager authenticates users. The namespace provides supports for several standard options and also a means of adding custom beans declared using a traditional syntax.
v UserDetailsService - closely related to authentication providers, but often also required by other beans.
Spring Security Implementation
Two main interface used in acegi security are Authentication and AuthenticationManager .
Authentication interface holds three main objects. First the Principal which identifies the caller user. The second object is credential of the caller and the third is authorities. When a request comes from some user, authentication object is populated which initially doesn’t contain authorities. Authorities are later assigned using AuthenticationManager.
The user request is intercepted using chain of filters. Filters must be configured properly for efficient use. There are few request where we generally don’t need authentication e.g. images, css. By avoiding filters on such request we can improve application performance significantly. We store this information web.xml
1. <filter>
2. <filter-name>security</filter-name>
3. <filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
4. <init-param>
5. <param-name>targetClass</param-name>
6. <param-value>org.acegisecurity.util.FilterChainProxy</param-value>
7. </init-param>
8. </filter><filter-mapping>
9. <filter-name>security</filter-name>
10. <url-pattern>/*</url-pattern>
11. </filter-mapping>
The above entry tells that we want to enable security for all the requests coming to the server.
Class FilterChainProxy
Delegates Filter requests to a list of Spring-managed beans. The FilterChainProxy is loaded via a standard FilterToBeanProxy declaration in web.xml. FilterChainProxy will then pass init(FilterConfig), destroy() and doFilter(ServletRequest, ServletResponse, FilterChain) invocations through to each Filter defined against FilterChainProxy.
FilterChainProxy is configured using a standard FilterInvocationDefinitionSource. Each possible URI pattern that FilterChainProxy should service must be entered. The first matching URI pattern located by FilterInvocationDefinitionSource for a given request will be used to define all of the Filters that apply to that request. NB: This means you must put most specific URI patterns at the top of the list, and ensure all Filters that should apply for a given URI pattern are entered against the respective entry. The FilterChainProxy will not iterate the remainder of the URI patterns to locate additional Filters. The FilterInvocationDefinitionSource described the applicable URI pattern to fire the filter chain, followed by a list of configuration attributes. Each configuration attribute’s ConfigAttribute.getAttribute() corresponds to a bean name that is available from the application context.
We have entry for FilterChainProxy bean in contextConfig file e.g (security.xml).
1. <bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
2. </bean>
3. <property name="filterInvocationDefinitionSource">
4. <value>
5. CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
6. PATTERN_TYPE_APACHE_ANT
7. /**=httpSessionContextIntegrationFilter,logoutFilter,
8. authenticationProcessingFilter,securityContextHolderAwareRequestFilter,
9. rememberMeProcessingFilter,anonymousProcessingFilter,
10. exceptionTranslationFilter, filterInvocationInterceptor
11. </value>
12. </property>
Filters are passed with the help of filterInvocationDefinitionSource property. Each filter will be executed in the same order as they appeared this conf file.HttpSessionContextIntegrationFilterPopulates the SecurityContextHolder with information obtained from the HttpSession.The HttpSession will be queried to retrieve the SecurityContext that should be stored against the SecurityContextHolder for the duration of the web request. At the end of the web request, any updates made to the SecurityContextHolder will be persisted back to the HttpSession by this filter.
No HttpSession will be created by this filter if one does not already exist. If at the end of the web request the HttpSession does not exist, a HttpSession will only be created if the current contents of the SecurityContextHolder are not Object.equals(java.lang.Object) to a new instance of setContext(Class). This avoids needless HttpSession creation, but automates the storage of changes made to the SecurityContextHolder. There is one exception to this rule, that is if the forceEagerSessionCreation property is true, in which case sessions will always be created irrespective of normal session-minimisation logic (the default is false, as this is resource intensive and not recommended).
1. <bean id="httpSessionContextIntegrationFilter"
2. class="org.acegisecurity.context.HttpSessionContextIntegrationFilter"></bean>
LogoutFilter
LogoutFilter performs Logout functionality. You use a constructor argument to provide the URL that LogoutFilter redirects to after successful logout. Another constructor argument specifies a list of handlers that execute as a part of logout functionality. Generally you will want to call logout handlers TokenBasedRememberMeServices and SecurityContextLogoutHandler (in that order).
1. <bean id="logoutFilter" class="org.acegisecurity.ui.logout.LogoutFilter">
2. <constructor-arg value="/index.html"/>
3. <constructor-arg>
4. <list>
5. <ref bean="rememberMeServices"/>
6. <bean class="org.acegisecurity.ui.logout.SecurityContextLogoutHandler"/>
7. </list>
8. </constructor-arg>
9. </bean>
AuthenticationProcessingFilter
Its job it to process user login form. Login form must present user name and password to this filter. Filter also takes list for arguments.
1. AuthenticationManager: This is a wrapper around list of one or more AuthenticationProviders provided to the class. During the authentication process the wrapper class iterate through all the AuthenticationProviders until a valid provider is found. Authenticate method of this provider is called to fully populate Authentication object or throws and AuthenticationException. The combined result from all the providers is returned from the wrapper.
2. AuthenticationFailureUrl: In case of failed authentication user will be redirected to this url.
3. defaultTargetUrl: Where to redirect the browser to if authentication is successful but ACEGI_SAVED_REQUEST_KEY is null
4. filterProcessesUrl: The URL destination that this filter intercepts and processes (usually something like ‘/j_acegi_security_check’)
5. RememberMeServices: remeberMeService bean if this option is used.
2. AuthenticationFailureUrl: In case of failed authentication user will be redirected to this url.
3. defaultTargetUrl: Where to redirect the browser to if authentication is successful but ACEGI_SAVED_REQUEST_KEY is null
4. filterProcessesUrl: The URL destination that this filter intercepts and processes (usually something like ‘/j_acegi_security_check’)
5. RememberMeServices: remeberMeService bean if this option is used.
1. <bean id="authenticationProcessingFilter"
2. class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
3. <property name="authenticationManager">
4. <ref bean="authenticationManager"/>
5. </property>
6. <property name="authenticationFailureUrl">
7. <value> /index.html</value>
8. </property>
9. <property name="defaultTargetUrl">
10. <value>/login</value>
11. </property>
12. <property name="filterProcessesUrl">
13. <value> /j_acegi_login</value>
14. </property>
15. <property name="rememberMeServices">
16. <ref local="rememberMeServices"/>
17. </property>
18. </bean>
RememberMeProcessingFilter
Detects if there is no Authentication object in the SecurityContext, and populates it with a remember-me authentication token if a RememberMeServices implementation so requests.
1. <bean id="rememberMeServices"
2. class="org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices">
3. <property name="userDetailsService"><ref local="jdbcDaoImpl"/></property>
4. <property name="tokenValiditySeconds" value="1209600"></property>
5. <property name="key"><value>Spring rocks all over world</value></property>
6. </bean>
SecurityContextHolderAwareRequestFilter
A Filter which populates the ServletRequest with a new request wrapper. Several request wrappers are included with the framework. The simplest version is SecurityContextHolderAwareRequestWrapper. A more complex and powerful request wrapper is SavedRequestAwareWrapper. The latter is also the default.
1. <bean id=" securityContextHolderAwareRequestFilter "
2. class=" org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter ">
ExceptionTranslationFilter
The Exception Translation Filter handles exceptions during the authentication and authorization procedure, such as when authorization fails. In these exceptional cases, ETF decides what to do.
1. <bean id="exceptionTranslationFilter"
2. class="org.acegisecurity.ui.ExceptionTranslationFilter">
3. <property name="authenticationEntryPoint"><
4. ref local="authenticationProcessingFilterEntryPoint"/></property>
5. <property name="accessDeniedHandler">
6. <bean class="org.acegisecurity.ui.AccessDeniedHandlerImpl">
7. <property name="errorPage" value="/index.html"/>
8. </bean>
9. </property>
10. </bean>
FilterInvocationInterceptor
Acegi’s interceptor filters are used to make authorization decisions. You need to configure interceptor filters to act after Authentication Processing Filter (APF) has performed a successful authentication. Interceptors use your application’s access control policy to make authorization decisions.
1. <bean id="filterInvocationInterceptor"
2. class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
3. <property name="authenticationManager"><ref bean="authenticationManager"/></property>
4. <property name="accessDecisionManager"><ref local="httpRequestAccessDecisionManager"/></property>
5. <property name="objectDefinitionSource">
6. <value>
7. CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
8. PATTERN_TYPE_APACHE_ANT
9. /images/**=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR
10. /css/**=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR
11. /ws/**=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR
12. /test/**=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR
13. /lib/**=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR
14. /j_acegi_login=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR
15. /j_acegi_logout=ROLE_ANONYMOUS,ROLE_OWNER,ROLE_ADMINISTRATOR
16. </value>
17. </property>
18. </bean>
References:
No comments:
Post a Comment