Vous êtes sur la page 1sur 10

Spring Security

Introduction

Security is one of the most critical architectural components of any web-based application.

Review the results of a security audit

1. Inadvertent privilege escalation due to lack of URL protection and general authentication 2. Inappropriate
1. Inadvertent privilege escalation due to lack of URL protection and general authentication
2. Inappropriate or non-existent use of authorization
3. Missing database credential security
4.
Personally-identifiable or sensitive information is easily accessible or unencrypted
5. Insecure transport-level protection due to lack of SSL encryption (using https)
6. Risk level is high
1)
2)
3)
Require a user to log into the system
Display sensitive information, such as names, addresses, credit cards, and orders
Provide functionality to manipulate the overall state of the system or its data

The goal of security audit is to provide clients with an assurance about the integrity and safety of the customer's data and system function. The auditor may test application using industry-specific standards or compliance metrics and may identify the following behavior:

Authentication

Inadvertent privilege escalation due to lack of URL protection and general authentication. Authentication identifies who is attempting to request a resource. The different types of authentications are credential based authentication, Hardware authentication, etc. Unauthenticated (Anonymous) areas do not:

Authorization

Inappropriate or non-existent use of authorization. Authorization (such as roles) uses the information that was validated during authentication to determine if access should be granted to a particular resource.

Database credential security

Database credentials not secured and easily accessible. Database passwords were stored in plain text in the configuration files, making it very easy for a malicious user with access to the server to gain access to the application. Protecting credentials should be a top priority because one point of failure in security does not compromise the entire system.

Sensitive information

Personally identifiable or sensitive information is easily accessible or unencrypted. Significant and sensitive pieces of data were completely unencrypted or masked anywhere in the system.

Transport-level protection

Insecure transport-level protection due to lack of SSL encryption. SSL protection (using https) ensures that communication between the browser client and the web application server are secure against any kinds of tampering and snooping.

Conclusion:

1. Authentication protects application.

2. Authorization protects web pages in application. 3. Https (using certificates) protects data between browser
2. Authorization protects web pages in application.
3. Https (using certificates) protects data between browser and server.
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy </filter-class>

}

Spring Security provides everything we need to implement a top-to-bottom application security solution in a concise and sensible way. Spring Security offers out-of-the-box integration with many common enterprise authentication systems; so it's adaptable to most situations with little effort of the developer.

Spring Security's automatic configuration

Spring Security relies on several servlet filters to provide different security features. Among them we’ll only need to configure one filter in the web.xml file and other filters are automatically registered as a <bean> in the spring application context to take the full advantage of spring’s support for dependency injection. #WEB-INF/web.xml <filter>

</filter>

DelegatingFilterProxy is a special servlet filter that, by itself, doesn’t do much. Instead, it delegates FilterChainProxy, which is an implementation of javax.servlet.Filter. The FilterChainProxy is automatically registered as a <bean> in the spring application context with the bean id always as springSecurityFilterChain. Hence the <filter-name> in web.xml file must be always springSecurityFilterChain. public class DelegatingFilterProxy implements Filter { void doFilter(request, response, filterChain) { Filter delegate = applicationContet.getBean("springSecurityFilterChain") delegate.doFilter(request,response,filterChain);

}

Note: Spring Security will automatically register FilterChainProxy if and only if we add <http> in spring security configuration file (security.xml).

Spring Security XML configuration file

Spring security configuration file is required to get our application secured. This configuration file uses spring security name space (http://www.springframework.org/schema/security). The following file provides: A default login page, a default logout page, authenticate the user, and require the logged-in user to be associated to ROLE_USER. #WEB-INF/spring/security.xml <?xml version="1.0" encoding="UTF-8"?> <bean:beans xmlns:bean="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">

<http auto-config="true"> <intercept-url pattern="/**" access="ROLE_USER"/>

</http> <authentication-manager> <authentication-provider> <user-service> <user name="user@java2aspire.com" password="user" authorities="ROLE_USER"/> </user-service> </authentication-provider> </authentication-manager> </bean:beans>

The <authentication-manager> element is how Spring Security authenticates the user. In this instance, we utilize an in-memory data store to compare a username and password.

<http>

The <http> element automatically creates FilterChainProxy and registered as a <bean> in the spring application context with the bean id ‘springSecurityFilterChain’. The FilterChainProxy chains together with one or more additional filters. Hence developers need not to configure all these filter beans (including chain filters) explicitly in spring configuration file. The following table contains attributes of <http> element:

Attribute name

Description

security

When set to ‘none’, no security filters will be created and <http> element should be empty, with no children.

auto-config

If set to "true" then automatically registers a login form, BASIC authentication, anonymous authentication, logout services, remember-me. The default value is "false".

use-expressions

Enables the SPring Expression Language (SPEL). The default value is “false”.

The following table contains sub elements of <http> element: Sub element name Description <form-login>
The following table contains sub elements of <http> element:
Sub element name
Description
<form-login>
Sets up a form login configuration for authentication with a username and
password.
<http-basic>
When the user of the application is another application (in case of RESTFul),
prompting for login with a form just won’t do. HTTP Basic authentication is
a way to authenticate a user to an application directly in the HTTP request
itself.
<logout>
Incorporates a logout processing filter.
<form-login>
Sets up a form login configuration for authentication with a username and password.
The following table contains attributes of <form-login> element:
Attribute name
Description
‘login-page’
The URL for the login page. If no login URL is specified, Spring Security
will automatically create a login URL at ‘/spring_security_login’
‘login-processing-url’
The URL that the login form is posted to.
Default value is ‘/j_spring_security_check’
‘username-parameter’
Form field name in login page.
Default value is ‘j_username’
‘password-parameter’
Form field name in login page.
Default value is ‘j_password’
‘authentication-failure-url’
The URL for the login failure page.
If no login failure URL is specified, Spring Security will automatically
create a failure login URL at ‘/spring_security_login?login_error’
<logout>
Incorporates a logout processing filter.
The following table contains attributes of <logout> element:
Attribute name
Description
‘logout-url’
Specifies the URL that will cause a logout.
Spring Security will initialize a filter that responds to this particular URL.
Defaults to ‘/j_spring_security_logout’ if unspecified.

<http auto-config="true"> <intercept-url pattern="/**" access="ROLE_USER"/> </http> The above configuration internally becomes:

<http auto-config="true"> <form-login login-page="/spring_security_login" login-processing-url="/j_spring_security_check"

username-parameter="j_username" password-parameter="j_password" authentication-failure-url="/spring_security_login?login_error"/> <http-basic/> <logout logout-url="/j_spring_security_logout" /> <intercept-url pattern="/**" access="ROLE_USER"/> </http>

/WEB-INF/spring/i18n.xml /WEB-INF/spring/security.xml </param-value> </context-param>
/WEB-INF/spring/i18n.xml
/WEB-INF/spring/security.xml
</param-value>
</context-param>
<listener>
</listener>
<version>3.1.0.RELEASE</version>

The security.xml should be configured in web.xml file. #web.xml <web-app> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/services.xml

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</web-app>

Update the Maven pom.xml file with necessary Spring Security .jar files. #pom.xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId>

</dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId>

<version>3.1.0.RELEASE</version>

</dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId>

<version>3.1.0.RELEASE</version>

</dependency>

Customize the login page

The default login page provided by Spring Security may not suit to our project look and feel. Hence it is good to add customized login page with our projects look and feel. <http auto-config="true"> <form-login login-page="/login/form" login-processing-url="/login" username-parameter="username" password-parameter="password" authentication-failure-url="/login/form?error" /> <logout logout-url="/logout" logout-success-url="/login/form?logout"/> <intercept-url pattern="/**" access="ROLE_USER" />

…

</http>

The login/formpath should be defined in controller class:

//WebMVCConfig.java @Override public void addViewControllers(ViewControllerRegistry registry) { super.addViewControllers(registry); registry.addViewController("/login/form").setViewName("login");

}

The InternalViewResolver maps loginview name with /WEB-INF/views/login.jsp #login.jsp <jsp:include page="./includes/header.jsp" /> <c:url value="/login" var="loginUrl" /> <form action="${loginUrl}" method="post"> <c:if test="${param.error != null}"> <div class="alert alert-error"> Failed to login. <c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">

Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />

</div>

</c:if>

</c:if> <c:if test="${param.logout != null}">

<div class="alert alert-success">You have been logged out.</div>

</c:if>

<label for="username">Username</label> <input type="text" id="username" name="username" />

<label for="password">Password</label> <input type="password" id="password" name="password" />

<div class="form-actions"> <input id="submit" class="btn" name="submit" type="submit" value="Login" />

</div> </form> <jsp:include page="./includes/footer.jsp" />

The following changed made in header.jsp to add Logoutlink:

#header.jsp <div id="nav-account" class="nav-collapse pull-right"> <ul class="nav"> <c:url var="logoutUrl" value="/logout" /> <li><a id="navLogoutLink" href="${logoutUrl}">Logout</a></li>

</div>

</ul> 1. CSS, and JavaScript do not need to use Spring Security. Example: <http
</ul>
1.
CSS, and JavaScript do not need to use Spring Security.
Example:
<http pattern="/resources/**" security="none"/>
2.

Allow anonymous users to access the Welcome, Login, and Logout pages. <intercept-url pattern="/" access="ROLE_ANONYMOUS, ROLE_USER" /> <intercept-url pattern="/login/*" access="ROLE_ANONYMOUS, ROLE_USER" /> <intercept-url pattern="/logout" access="ROLE_ANONYMOUS, ROLE_USER" />

The customized login page accessed using http://localhost:9090/chapter02.01-calendar/login/form The Firefox browser displays The Page isnt redirecting properlyerror because Spring Security is no longer rendering the login page, we must allow everyone (not just ROLE_USER) access to the login page.

Authorization and URL Protection

The authorization is used to allow more granular control over how resources (i.e., pages) can be accessed. In the following configuration, Spring Security will:

Completely ignore any request that starts with /resources/. This is beneficial, since our images,

3. Only allow administrators access to the All Events page. <intercept-url pattern="/events/" access="ROLE_ADMIN" />

4. Add an administrator that can access the All Events page.

<user name="admin@java2aspire.com" password="admin" authorities="ROLE_USER, ROLE_ADMIN"/>

Rules:

1)

2)

3)

4)

? matches a single character. * matches zero or more characters, excluding /. ** matches zero or more directories in a path. The pattern "/events/**" matches "/events", "/events/", "/events/1", and "/events/1/form?test=1"; it does not match "/events123". The pattern "/events*" matches "/events", and "/events123"; it does not match "/events/" or "/events/1". The pattern "/events*/**" matches "/events", "/events/", "/events/1","/events123", "/events123/456", and "/events/1/form?test=1".

5)

6) SpEL Spring Security's JSP library Security is add on to business class hence it
6)
SpEL
Spring Security's JSP library
Security is add on to business class hence it is an aspect. The security aspect is automatically provided by
Spring Security. The Spring Security is a security framework which provides declarative security.
Spring Security provides authentication and authorization at both web request level and method
invocation level.
Spring Security 2.0 released security specific namespace (spring-security-3.2.xsd) to reduce
configuration file size.
Spring Security 3.0 added SpEL (Spring Expression Language) to reduce configuration file size even more.
Spring Security 3.2 tackles security from 2 angles:
1. To secure web requests and restrict access at the URL level, Spring Security uses servlet filters.
2. Spring Security can also secure method invocations using Spring AOP, proxying objects and
applying advice to ensure that the user has the proper authority to invoke secured methods.
Spring security contains 11 modules:
Core
Provides the essential Spring Security library.
Configuration
Contains support for configuring Spring Security with XML and Java.
Tag Library
Spring Security’s JSP tag library.
Web
Provides Spring Security’s filter-based web security support.
Cryptography
Provides support for encryption and password encoding.
Aspects
Providing support for AspectJ-based aspects instead of standard Spring AOP when
using Spring Security annotations.

Spring Security comes with a security-specific namespace (spring-security-3.2.xsd) that greatly simplifies security configuration in Spring.

The DelegatingFilterProxy is a special servlet filter which delegates to an implementation of javax.servlet.Filter that’s registered as a <bean> in the Spring application context. <filter>

<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <http
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_USER" />
<form-login/>
<http-basic/>
<logout/>
<intercept-url pattern="/admin**" access="ROLE_USER" />

<filter-name>springSecurityFilterChain</filter-name>

</filter> The bean name should be same as filter-name. Spring security will automatically create several filter beans (such as SpringSecurityFilterChain) when we configure <http> element as given below:

</http> The auto-config=”true” gives a free login page, support for http basic authentication and support for logging out. Hence above configuration is equivalent to:

<http>

</http>

We can get auto generated login form via the path: http://localhost:9090/spring-security-helloworld- xml/spring_security_login Note: To put our own login page in place, we’ll need to configure a <form-login> element to override the default behavior. <intercept-url pattern="/**" access="ROLE_USER" /> In this case, we’ve set the pattern attribute to /**, indicating that we want all requests, regardless of the URL, to require ROLE_USER access. The /** has a broad reach, but we can be more specific. <intercept-url pattern="/admin/**" access="ROLE_ADMIN"/> This <intercept-url> restricts access to the /admin branch of the site’s hierarchy to users with ROLE_ADMIN authority. We can use as many <intercept-url> entries as we like to secure various paths in our web application. But it’s important to know that the <intercept-url> rules are applied top to bottom. Therefore, this new <intercept-url> should be placed before the original one or else it’ll be eclipsed by the broad scope of the /** path. <intercept-urlpattern="/admin/**"access="ROLE_ADMIN"/> <intercept-url pattern="/**" access="ROLE_USER" />

Spring Security also supports SpEL (Spring Expression Language) for declaring access requirements. To enable it, we must set the use-expressions attribute of <http> to true:

<http auto-config="true" use-expressions="true">

</http>

Now we can start using SpEL expressions in the access attribute. Here’s how to use a SpEL expression to require ROLE_ADMIN access for the /admin/** URL pattern:

<intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>

It is always recommended to encrypt and send sensitive information over HTTPS. The <intercept-url> element’s requires-channel attribute shifts the responsibility for channel enforcement into the Spring Security configuration. <intercept-url pattern="/form" requires-channel="https"/> The home page doesn’t require HTTPS, so we can declare that it always should be sent over HTTP:

1. In-memory (Spring-configured) user repositories 2. JDBC-based user repositories 3. LDAP-based user repositories 4.
1. In-memory (Spring-configured) user repositories
2. JDBC-based user repositories
3. LDAP-based user repositories
4.
OpenID decentralized user identity systems
5. Central Authentication System (CAS)
6. X.509 certificates
7. JAAS-based providers

<intercept-urlpattern="/home" requires-channel="http"/> Spring Security comes with a JSP tag library, which includes very few tags such as <s:authentication>, <s:authorize> and <s:accesscontrollist>. To use the JSP tag library, we’ll need to declare it in the JSP files where it’s used:

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

Spring Security is flexible to use any repository to authenticate. Spring Security can authenticate against following repositories:

One of the easiest authentication options available is to declare the user details directly in the Spring configuration. <authentication-manager> <authentication-provider> <user-service> <user name="aspire" password="aspire1234" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager>