Home  > Resources  > Blog

How to Secure a Web Application using Spring Security?

January 30, 2020 by Bibhas Bhattacharya
Categories: Architecture , SOA & Web Services

This tutorial is adapted from Web Age course  Technical Introduction to Microservices.

1.1 Securing Web Applications with Spring Security 3.0

 Spring Security (formerly known as Acegi) is a framework extending the traditional JEE Java Authentication and Authorization Service (JAAS). It can work by itself on top of any Servlet-based technology. It does however continue to use Spring core to configure itself.  It can integrate with many back-end technologies like OpenID, CAS, LDAP, Database. It uses a servlet-filter to control access to all Web requests. It can also integrate with AOP to filter method access. This gives you method-level security without having to actually use EJB.

Featured Upcoming
Free Webinars and Whitepapers! 

Join our community of 80,000 IT professionals by registering today.


Do Stakeholders Understand You? Three Fatal
Signs It’s Time to Add Archimate to Your Toolbox

Friday, October 29web age training
12:00  to 1:00 PM ET


Three Way to Implement
Data Analytics on Azure

DATE TO BE CONFIRMEDweb age training
11:00 AM to 12:00 PM ET


Data Engineering & Data Analytics
Upskilling Trends in 2021

Complimentary White Paperweb age solutions training
10 Minute Guide

1.2 Spring Security 3.0

Because it is based on a servlet-filter, it can also work with SOAP based Web Services, RESTful Services, any kind of Web Remoting, and Portlets. It can even be integrated with non-Spring web frameworks such as Struts, Seam, and ColdFusion. Single Sign On (SSO) can be integrated through CAS, the Central Authentication Service from JA-SIG. This gives us access to authenticate against X.509 Certificates, OpenID (supported by Google, Facebook, Yahoo, and many others), and LDAP. WS-Security and WS-Trust are built on top of these. It can integrate into WebFlow. There’s support for it in SpringSource Tool Suite.

1.3 Authentication and Authorization

Authentication answers the question “Who are you?” . It includes a User Registry of known user credentials.. It includes an Authentication Mechanism for comparing the user credentials with the User Registry. Spring Security can be configured to authenticate users using various means or to accept the authentication that has been done by an external mechanism. Authorization answers the question “What can you do?” Once a valid user has been identified, a decision can be made about allowing the user to perform the requested function. Spring Security can handle the authorization decision. Sometimes this may be very fine-grained. For example, allowing a user to delete their own data but not the data of other users.

1.4 Programmatic v Declarative Security

Programmatic security allows us to make fine grained security decisions but requires writing the security code within our application. The security rules being applied may be obscured by the code being used to enforce them. Whenever possible, we would prefer to declare the rules for access and have a framework like Spring Security enforce those rules. This allows us to focus on the security rules themselves and not writing the code to implement them. With Spring Security we have a DSL for security that enables us to declare the kinds of rules we would have had to code before. It also enables us to use EL in our declarations which gives us a lot of flexibility.  This can include contextual information like time of access, number of items in a shopping cart, number of previous orders, etc.

1.5 Getting Spring Security Gradle or Maven

Spring 3.0 split many different packages into different modules so you can use just what you need. The following will almost always be used

  • Core – Core classes
  • Config – XML namespace configuration
  • Web – filters and web-security infrastructure

The following will be used if the appropriate features are required

  • JSP Taglibs
  • LDAP – LDAP authentication and provisioning
  • ACL – Specialized domain object ACL implementation
  • CAS – Support for JA-SIG.org Central Authentication Support
  • OpenID – ‘OpenID for Java’ web authentication support

Getting Spring Security from Gradle

The exact syntax of how you add the above Spring Security modules using Maven will differ depending on if you get them from:
Maven Central – http://search.maven.org/
SpringSource Enterprise Bundle Repository (EBR) – http://ebr.springsource.com/repository/
The following is an example of getting them from the Maven Central:
group ‘com.shaneword’
version ‘1.0-SNAPSHOT’
apply plugin: ‘java’
sourceCompatibility = 1.7
repositories {
dependencies {
testCompile group: ‘junit’, name: ‘junit’, version: ‘4.11’

Getting Spring Security from Maven

The exact syntax of how you add the above Spring Security modules using Maven will differ depending on if you get them from:
Maven Central – http://search.maven.org/
SpringSource Enterprise Bundle Repository (EBR) – http://ebr.springsource.com/repository/
The following is an example of getting them from the SpringSource EBR:

1.6 Spring Security Configuration

If Spring Security is on the classpath, then web applications will be setup with “basic” authentication on all HTTP endpoints. There is a default AuthenticationManager that has a single user called ‘user’ with a random password.  The password is printed out during application startup. Override the password with ‘security.user.password’ in ‘application.properties’.  To override security settings, define a bean of  type ‘WebSecurityConfigurerAdapter’ and plug it into the configuration.

1.7 Spring Security Configuration Example

public class ApplicationSecurity
extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http)
throws Exception {
public void configure(AuthenticationManagerBuilder auth)
throws Exception {

8.8 Authentication Manager

The AuthenticationManager class provides user information.  You can use multiple <authentication-provider> elements and they will be checked in the declared order to authenticate the user. In the example above, the WebSecurityConfigurerAdapter’s ‘configure()’ method gets called with an AuthenticationManagerBuilder. We can use this to configure the AuthenticationManager using a “fluent API”,  auth.jdbcAuthentication().dataSource(ds).withDefaultSchema()

1.9 Using Database User Authentication

You can obtain user details from tables in a database with the jdbcAuthentication() method. This will need a reference to a Spring Data Source bean configuration auth.jdbcAuthentication().dataSource(ds).withDefaultSchema(). If you do not want to use the database schema expected by Spring Security you can customize the queries used and map the information in your own database to what Spring Security expects
.usersByUsernameQuery(“SELECT username, password,
‘true’ as enabled FROM member WHERE username=?”)
member.username, member_role.role as authority
FROM member, member_role WHERE member.username=?
AND member.id=member_role.member_id”);

Using Database User Authentication

The configuration of the ‘securityDatabase’ Data Source above is not shown but it is just like Spring database configuration.
The queries that Spring Security uses by default are:
SELECT username, password, enabled FROM users WHERE username = ?
SELECT username, authority FROM authorities WHERE username = ?
The default statements above assume a database schema similar to:
Notice in the custom queries defined in the slide the ‘enabled’ part of the query is mapped as ‘true’ since it is assumed the table referenced does not have this column but Spring Security expects it. If the table does have some column similar to ‘enabled’ it should map to a boolean type (like a ‘1’ for enabled and ‘0’ for disabled).
The custom queries above would work with a database schema of:

1.10 LDAP Authentication

It is common to have an LDAP server that stores user data for an entire organization. The first step in using this with Spring Security is to configure how Spring Security will connect to the LDAP server with the ldapAuthentication builder.
.managerDn(“cn=Directory Admin”)
You can also use a “embedded” LDAP server in a test environment by not providing the ‘url’ attribute and instead providing ldif files to load
.managerDn(“cn=Directory Admin”)

LDAP Authentication

The ‘manager-dn’ and ‘manager-password’ attributes of <ldap-server> are used for how to authenticate against the LDAP server to query user details. If using the embedded LDAP server the default for the ‘root’ will be “dc=springframework,dc=org” if you do not supply a value.
In order to configure Spring Security there are a number of attributes related to LDAP that have various defaults that may affect how your LDAP configuration behaves. This slide is meant to simply introduce the feature. One step you should take when attempting to use Spring Security with LDAP is to avoid configuring everything at once. Start with an embedded list of users to test the other configuration settings and then switch to using LDAP. Also try using the embedded LDAP server with an ldif file exported from your LDAP server with a few sample users.

1.11 What is Security Assertion Markup Language (SAML)?

Security Assertion Markup Language (SAML) is an open standard that allows identity providers (IdP) to pass authorization credentials to service providers (SP). It’s a security protocol similar to OpenId, OAuth, Kerberos etc. SAML is the link between the authentication of a user’s identity and the authorization to use a service. SAML adoption allows IT shops to use software as a service (SaaS) solutions while maintaining a secure federated identity management system.  SAML enables Single-Sign On (SSO), which means users can log in once, and those same credentials can be reused to log into other service providers.

1.12 What is a SAML Provider?

A SAML provider is a system that helps a user access a service they need. There are two primary types of SAML providers, service provider, and identity provider. A service provider needs the authentication from the identity provider to grant authorization to the user. An identity provider performs the authentication that the end user is who they say they are and sends that data to the service provider along with the user’s access rights for the service.  Microsoft Active Directory or Azure are common identity providers. Salesforce and other CRM solutions are usually service providers, in that they depend on an identity provider for user authentication.

1.13 Spring SAML2.0 Web SSO Authentication

This diagram from wikipedia explains how SAML works:



Pic source- CC BY-SA 3.0, Link

1. User hits the Service Provider URL Service provider discovers the IDP to contact for authentication
2. Service provider redirects to the corresponding IDP
3. User hits the IDP and identifies the user
4. IDP redirects to the Login form
5. Redirect to Service provider Assertion consumer URL (the URL in Service provider that accepts SAML assertion)
6. SP initiates redirect to target resource
7. Browser requests for the target resource
8. Service provider responds with the requested resource

1.14 Setting Up an SSO Provider

For SAML authentication to work we need an identity provider (IdP). There are various providers, such as Active Directory, Azure, AWS, Google, Microsoft, Facebook, Onelogin, etc. Obtain the domain name and fully qualified domain name of the Active Directory server. To enable SSO on Active Directory, the following steps are typically performed:

  • Ensure that LDAP is configured on the Active Directory (AD) server.
  • From the AD Server, run ldp.
  • From the Connections menu, click Connect, and configure Server name, port, and select SSL option.
  • When the LDAP is properly configured, the external domain server details are displayed in the LDP window. Otherwise, an error message
    appears indicating that a connection cannot be made using this feature.
  • When the LDAP is properly configured, the external domain server details are displayed in the LDP window. Otherwise, an error message
    appears indicating that a connection cannot be made using this feature.

1.15 Adding SAML Dependencies to a Project

 Here are the dependencies in Gradle
◊ compile group: ‘org.springframework.security’, name: ‘spring-securitycore’, version: “4.2.3.RELEASE”
◊ compile group: ‘org.springframework.security’, name: ‘spring-securityweb’, version: “4.2.3.RELEASE”
◊ compile group: ‘org.springframework.security’, name: ‘spring-securityconfig’, version: “4.2.3.RELEASE”
◊ compile group: ‘org.springframework.security.extensions’ , name:
‘spring-security-saml2-core’ , version : “1.0.2.RELEASE”

1.16 Dealing with the State

Microservices are stateless to achieve scalability and high availability. But you need to keep state in order to maintain position in the client-server conversation, reduce chattiness of the conversation by minimizing client-server round trips. State is maintained either within a client-server session or within a cross-session conversation. State may not need to be maintained outside the established session duration and can be expired.

1.17 How Can I Maintain State?

 You have two options. One is to maiintain state on the service’s side. You can use a caching solution or durable store. Here, you may want to configure TTL for session / state to be expired (e.g. for abandoned sessions, timed-out sessions, etc.). Other option is to have the client send its state as part of the request, ie. cookies, custom HTTP headers, part of the request URL (query strings), as part of the payload.

1.18 SAML vs. OAuth2

OAuth is a slightly newer standard that was co-developed by Google and Twitter to enable streamlined internet logins. OAuth uses a similar methodology as SAML to share login information. SAML provides more control to enterprises to keep their SSO logins more secure, whereas OAuth is better on mobile and uses JSON. Facebook and Google are two OAuth providers that you might use to log into other internet sites. 

1.19 OAuth2 Overview

OAuth is an authorization method to provide access to resources over the HTTP protocol.  It can be used for authorization of various applications or manual user access. It is commonly used as a way for internet users to grant websites or applications access to their information on other websites without giving them the passwords. This mechanism is used by companies, such as Google, Facebook, Microsoft, Twitter, and DropBox, to permit the users to share information about their accounts with third party applications or websites. It allows an application to have an access token . Access token represents a user’s permission for the client to access their data. The access token is used to authenticate a request to an API endpoint.

1.20 OAuth – Facebook Sample Flow

Although, the diagram below is for Facebook, but it’s similar for any other provider.

1.21 OAuth Versions

There are two versions of OAuth authorization, OAuth 1 – HMAC-SHA signature strings and OAuth 2 – tokens over HTTPS. OAuth2 is not backwards compatible with OAuth 1.0. OAuth2 provides specific authorization flows for web applications, desktop applications, mobile phones, and living room devices.

1.22 OAuth2 Components

Resource server is the API server which contains the resources to be accessed. Authorization server provides access tokens. It can be the same as the API server. Resource owner access tokens are provided by the resource owner, i.e. the user, when resources are accessed. Client / consumer is an application using the credentials.

1.23 OAuth2 – End Points

The token Endpoint is used by clients to get an access token from the authorization server. It can also optionally refresh the token.

1.24 OAuth2 – Tokens

There are  two token types involved in OAuth2 authentication. Access Token is used for authentication an authorization to get access to the resources from the resource server. Refresh Token is sent together with the access token. It is used to get a new access token, when the old one expires. It allows for having a short expiration time for access tokens to the resource server and a long expiration time for access to the authorization server. Access tokens also have a type which defines how they are constructed. Bearer Tokens uses HTTPS security and the request is not signed or encrypted. Possession of the bearer token is considered authentication. MAC Tokens are more secure than bearer tokens. MAC tokens are similar to signatures, in that they provide a way to have partial cryptographic verification of the request.

1.25 OAuth – Grants

Methods to get access tokens from the authorization server are called grants. The same method used to request a token is also used by the resource server to validate a token. There are 4 basic grant types:

  • Authorization Code – When the resource owner allows access, an authorization code is then sent to the client via browser redirect, and the authorization code is used in the background to get an access token. Optionally, a refresh token is also sent. This grant flow is used when the client is a third-party server or web application, which performs the access to the protected resource.
  • Implicit – It is similar to authorization code, but instead of using the code as an intermediary, the access token is sent directory through a browser redirect. This grant flow is used when the user-agent will access the protected resource directly, such as in a rich web application or a mobile app.
  • Resource Owner Credentials – The password / resource owner credentials grant uses the resource owner password to obtain the access token. Optionally, a refresh token is also sent. The password is then authenticated.
  • Client Credentials – The client’s credentials are used instead of the resource owner’s. The access token is associated either with the client itself, or delegated authorization from a resource owner. This grant flow is used when the client is requesting access to protected resources under its control

1.26 Authenticating Against an OAuth2 API

Most OAuth2 services use the /oauth/token URI endpoint for handling all OAuth2 requests. The first step in authenticating against an OAuth2 protected API service is exchanging your API key for an Access Token.

 It can be done by performing these steps:

  • Create a POST request
  • Supply grant_type=client_credentials in the body of the request

Let’s say the API key has two components

  • ID:xxx
  • Secret: yyy

cURL could be used to get an Access Token like this:
curl –user xxx:yyy –data grant_type=client_credentials -X

POST https://api.someapi.com/oauth/token

1.27 OAuth2 using Spring Boot – Dependencies

Gradle dependencies

compile “org.springframework.boot:spring-boot-startersecurity:*”
compile “org.springframework.security.oauth.boot:springsecurity-

1.28 OAuth2 using Spring Boot – application.yml

  •  src/main/resources/application.yml requires security configuration
  • Note: This example uses the Facebook provider.

clientId: 233668646673605
clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
tokenName: oauth_token
authenticationScheme: query
clientAuthenticationScheme: form
userInfoUri: https://graph.facebook.com/me

1.29 OAuth2 using Spring Boot – Main Class

public class DemoApplication extends WebSecurityConfigurerAdapter {
public Principal user(Principal principal) {
return principal;
protected void configure(HttpSecurity http) throws Exception {
.antMatchers(“/”, “/login**”, “/webjars/**”)

1.30 OAuth2 using Spring Boot – SPA Client

The sample code below uses AngularJS, but you can use similar concepts with or without client-side framework
angular.module(“app”, []).controller(“home”, function($http) {
var self = this;
self.logout = function() {
$http.post(‘/logout’, {}).success(function() {
self.authenticated = false;
}).error(function(data) {
console.log(“Logout failed”)
self.authenticated = false;
$http.get(“/user”).success(function(data) {
self.user = data.userAuthentication.details.name;
self.authenticated = true;
}).error(function() {
self.user = “N/A”;
self.authenticated = false;

1.31 JSON Web Tokens

They are replacement for standard/traditional API keys. They are an open standard.  They allow fine-grained access control via “claims”. A claim is any data a client “claims” to be true. It typically includes “who issued the request” and “when it was issued”. JSON Web Tokens are Cross-Domain capable (cookies are not), Compact (compared with XML based security), Encoded (URL-Safe), Signed (to prevent tampering). OAuth and JWT are not the same. JWT is a specific protocol for a security access token. OAuth is a broader security framework for the interaction of different actors (end users, back-end APIs, authorization servers) for the generation and distribution of security access tokens.

1.32 JSON Web Token Architecture

There are three sections in JSON Web Token -Header,  Payload and Signature. Header and Payload are base64 encoded. Signature is calculated from the encoded header and payload. Sections are separated by a period.

1.33 How JWT Works

JWT works as a two way protocol where a request is made and the response is generated from a server.

The browser makes the request for JWT encoded data. The server generates the signed token and return to the client. The token can be sent over the http request for every other request that needs authentication on the server. The server then validates the token and, if it’s valid, returns the secure resource to the client.

1.34 JWT Header

Declares the signature algorithm and type
The algorithm shown here (HMAC SHA-256) will be used to create the signature. The type “JWT” stands for JSON Web Token. When base64 encoded it looks like this:

1.35 JWT Payload

The payload contains “Claims”. Claims come in several types as Registered, Public and Private. Examples of Registered claims include

  • iss: use to define who issuedthe token
  • sub: the subject of the token
  • exp: token expiration time

Public claims  use URI schemes to prevent name collision i.e. https:/corpname.com/jwt_claims/is_user. Private claims are used inside organizations. They can use simple naming conventions  i.e. “department”.

1.36 JWT Example Payload

“iss”: “corpname.com”,
“aud”: “corpname.com/rest/product”,
“sub”: “jdoe”,
“Email”: “jdoe@corpname.com”
 After base64 encoding:

1.37 JWT Example Signature

The signature is created from the header and body like this:
content = base64UrlEncode(header)
+ “.”
+ base64UrlEncode(payload);
signature = HMACSHA256(content);
Completed signature:

1.38 How JWT Tokens are Used

 Client requests token sends credentials to Authentication server. Server returns a JWT token. Client adds token to HTTP request via the Authentication header. A JWT token can be cached on the browser and returned on every request to the server to ensure the user has access to the resources on every request without authentication on every request. The downside of this is that the user will have access for the duration of the token unless there is a blacklist each service checks against.  Client sends the request. API receives request. It reads the JWT from the Authentication header, unpacks the payload, checks claims, allows or denies access.

1.39 Adding JWT to HTTP Header

After obtaining a JWT token the client adds it to an HTTP request as an HTTP header
◊ Header Name: Authorization
◊ Type: Bearer

1.40 How The Server Makes Use of JWT Tokens

The RESTful web service needs to validate JWT tokens when it receives requests.
◊ Unpack token
◊ Validate that signature matches header and payload
◊ Validates claims (has token expired?)
◊ Compares scopes
◊ If required it makes call to ACL (access control list) server.
◊ Grants or denies access
This process can be coded into JEE Servlet filters or added directly to the web service code

1.41 What are “Scopes”?

 The payload area of a JSON web token contains a “claim” named “scope”. The value for the “scope” field is an array.

 Technically scope strings can include any text. In practice scope strings are limited to those defined by an organization. Scope strings refer to specific operations on a specific API endpoints.

1.42 JWT with Spring Boot – Dependencies

Add JWT dependencies
compile “org.springframework.boot:spring-boot-startersecurity:*”
compile “io.jsonwebtoken:jjwt:0.9.0”

1.43 JWT with Spring Boot – Main Class

public class SecurityTokenConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {

// Add a filter to validate the tokens with every request
.addFilterAfter(new JwtTokenAuthenticationFilter(jwtConfig),
// authorization requests config
// allow all who are accessing “auth” service
.antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()
// must be an admin if trying to access admin area
(authentication is also required here)
.antMatchers(“/gallery” + “/admin/**”).hasRole(“ADMIN”)
// Any other request must be authenticated

1.44 Summary

  • Spring Security has many features that simplify securing web applications.
  • Making use of many of these features only requires configuration in a Spring configuration file.
  • Spring Security can work with many different sources of user and permission information.

Follow Us

Blog Categories