Tag Archives: Spring-security

Json Web Token: How to Secure Spring Boot REST API

In this post, I will show how to secure your spring boot based REST API. It has been more of a trend to secure REST APIs to avoid any unnecessary calls to public APIs. We will be using some Spring boot features for Spring security along with JSON WebTokens for authorization. You can learn more about basic authentication here.

User flow in this case is

  1. User logs in
  2. We validate user credentials
  3. A token is sent back to user agent.
  4. User tries to access a protected resource.
  5. User sends JWT when accessing the protected resource. We validate JWT.
  6. If JWT is valid, we allow the user to access the resource.

JSON WebTokens, known as JWTs are used for forming authorization for users. This helps us to build secure APIs and it is also easy to scale. During authentication, a JSON web token is returned. Whenever the user wants to access a protected resource, the browser must send JWTs in the Authorization header along with the request. One thing to understand here is that it is a good security practice to secure REST API.

Basically, we will show

  1. Verify JSON WebToken
  2. Validate the signature
  3. Check the client permissions

What you will need?

  1. Java 8,
  2. MySQL Database
  3. IntelliJ Editor
  4. Gradle

Note – This won’t be a full-fledged app, but REST APIs based on Spring Boot, and Spring security.

Spring Boot Based REST API

Since I have already shown this before on my blog, I won’t be creating any new APIs. I will be securing REST API for company that I created in this blog post REST API. This API also includes caching. A user will try to access /cachedemo/v1/companies/ and since APIs are protected, he will get a response like below:

Secure REST API - Forbidden

Response from protected API

Now we will implement how to protect this API and how to access it.

Adding User and User Registration

Since we want to add authorization for APIs, we will need where the user is able to log in and send credentials. These credentials will be validated and a token will be generated. This token then will be transmitted in a request to an API call. The token will be validated in the Spring security authorization filter that we will add. If a valid token, the user will be able to access the API.

Create a user model


package com.betterjavacode.models;

import javax.persistence.*;
import java.io.Serializable;

@Entity(name = "User")
@Table(name = "user")
public class User implements Serializable
{
    public User()
    {

    }

    @Id
    @GeneratedValue(strategy =  GenerationType.IDENTITY)
    private long id;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }
}

We will add a controller where a user can register with its details for username and password.


package com.betterjavacode.resources;

import com.betterjavacode.models.User;
import com.betterjavacode.repositories.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/cachedemo/v1/users")
public class UserController
{
    private UserRepository userRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserController(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder)
    {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @PostMapping("/signup")
    public void signUp(@RequestBody User user)
    {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

}

Now when we POST a request to /cachedemo/v1/users/signup , a user will be saved in the database. Password for the user will be saved in encrypted format as we are using BCryptPasswordEncoder. We will show how a user can log in to create a token.

User Login

To handle user login, we will add an AuthenticationFilter which will get added in FilterChain and Spring boot will handle the execution of it appropriately. This filter will look like below:


package com.betterjavacode.SpringAppCache;


import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter
{
    private AuthenticationManager authenticationManager;

    public AuthenticationFilter(AuthenticationManager authenticationManager)
    {
        this.authenticationManager = authenticationManager;
        setFilterProcessesUrl("/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException
    {
        try
        {
            com.betterjavacode.models.User creds = new ObjectMapper().readValue(request.getInputStream(), com.betterjavacode .models.User.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword(),new ArrayList<>()));
        }
        catch(IOException e)
        {
            throw new RuntimeException("Could not read request" + e);
        }
    }

    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Authentication authentication)
    {
        String token = Jwts.builder()
                .setSubject(((User) authentication.getPrincipal()).getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + 864_000_000))
                .signWith(SignatureAlgorithm.HS512, "SecretKeyToGenJWTs".getBytes())
                .compact();
        response.addHeader("Authorization","Bearer " + token);
    }
}

Basically, a user will send credentials in a request to URL ending with /login . This filter will help to authenticate the user, if there is successful authentication, a Token will be added in response header with the key Authorization.

Token Validation and Authorization

We add another filter AuthorizationFilter to validate the token that we passed through AuthenticationFilter earlier. This filter will look like below:


package com.betterjavacode.SpringAppCache;

import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;


public class AuthorizationFilter extends BasicAuthenticationFilter
{
    public AuthorizationFilter(AuthenticationManager authenticationManager)
    {
        super(authenticationManager);
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException
    {
        String header = request.getHeader("Authorization");
        if(header == null || !header.startsWith("Bearer"))
        {
            filterChain.doFilter(request,response);
            return;
        }

        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request)
    {
        String token = request.getHeader("Authorization");
        if(token != null)
        {
            String user = Jwts.parser().setSigningKey("SecretKeyToGenJWTs".getBytes())
                    .parseClaimsJws(token.replace("Bearer",""))
                    .getBody()
                    .getSubject();
            if(user != null)
            {
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
            }
            return null;
        }
        return null;
    }
}

If the validation of the token is successful, the application returns a user and assigns it to a security context.

To enable Spring security, we will add a new class WebSecurityConfiguration with annotation @EnableWebSecurity. This class will extend the standard WebSecurityConfigurerAdapter . In this class, we will restrict our APIs and also add some whitelisted URLs that we will need to access without any authorization token. This will look like below:


package com.betterjavacode.SpringAppCache;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter
{
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private UserDetailsService userDetailsService;

    private static final String[] AUTH_WHITELIST = {
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"
    };

    public WebSecurityConfiguration(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder)
    {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.userDetailsService = userDetailsService;
    }


    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()
                .antMatchers(HttpMethod.POST, "/cachedemo/v1/users/signup").permitAll()
                .anyRequest().authenticated()
                .and().addFilter(new AuthenticationFilter(authenticationManager()))
                .addFilter(new AuthorizationFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception
    {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource()
    {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

In method configure we have restricted most APIs, only allowing Swagger URLs and signup URL. We also add filters to HttpSecurity. We will add our own UserDetailsServiceImpl class to validate user credentials.


package com.betterjavacode.services;

import com.betterjavacode.models.User;
import com.betterjavacode.repositories.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class UserDetailsServiceImpl implements UserDetailsService
{
    private UserRepository userRepository;

    public UserDetailsServiceImpl(UserRepository userRepository)
    {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        User user = userRepository.findByUsername(username);
        if(user == null)
        {
            throw new UsernameNotFoundException(username);
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.emptyList());
    }
}

Demo

With all the code changes, now we are ready to create a user, login and access secured REST APIs. From the image above, a user gets Access Denied error for accessing secured APIs. To demo this, I have already registered a user with username `test1` and password test@123.

This POST request will give us Authorization token in response as shown above. Now using this token in our GET request to retrieve companies data. This GET request will look like below:

In this way, we showed how to secure REST API using JSON web token.

I will be launching the book “Simplifying Spring Security“. Do you want to get updates on launch? Sign up

References

  1. Implementing JWTs Authentication on Spring Boot API – JWT Authentication
  2. How to secure REST APIs – Secure REST APIs

HTTP Security Headers – XFrame Options and Content Security Policies

Have you ever traced an HTTP request in a browser or fiddler? You must have seen these HTTP security headers in the request or response header?

X-Frame-Options SAMEORIGIN

OR

Content-Security-Policy:frame-ancestors 'none'

Do you know what are these headers about? In this post, I will show why we use these headers. These security headers often come up when you are rendering an application within iframes.  Conclusively, these headers are important if you are loading applications with an iframe inside the main iframe.

Why are these headers required?

These headers help in avoiding clickjacking attacks. You can read more about clickjacking here. To defend against clickjacking, we implement frame-breaking using two methods.

   1. X-Frame-Options –

This header is used in response header to indicate whether or not a browser can be allowed to render a web page in a <frame> or <iframe>.

Possible values for this header:

  1. DENY – The recommended value for X-Frame-Options and it prevents any domain to frame the content.
  2. SAMEORIGIN – This allows only the current site to frame the content.
  3. ALLOW-FROM URI – This allows the specified URI to frame the content.

   2. Content-Security-Policy –

Similarly, X-Frame-Options is used by the browser to allow to render a page in a frame or iframe, the same way Content-Security-Policy header is used. Accordingly, some browsers support X-Frame-Options and some Content-Security-Policy. Nevertheless, one key feature between these two headers (X-Frame-Options and Content-Security-Policy) is that Content-Security-Policy can allow the listing of multiple domains to load the content from.

Possible values for this header are:

  • Content-Security-Policy: frame-ancestors ‘none’ – This prevents any domain to render the content.
  • Content-Security-Policy: frame-ancestors ‘self’ – This only allows the current site to frame the content.
  • Option of Content-Security-Policy: frame-ancestors ‘self’, ‘*.betterjavacode.com’, ‘https://www.mytest.com’ – This allows the current site, any subdomain of betterjavacode.com or the web page at www.mytest.com to load the page. Single quotes are important here.

Spring-Security

Likewise, Spring-security offers a feature to enable the X-Frame-Options and Content-Security-Policy directive.

http.headers().frameOptions().disable();

http.headers().frameOptions().sameOrigin();

Conclusion

In conclusion, I showed why and how to use HTTP security headers X-Frame-Options and Content-Security-Policy. Hence, if you enjoyed this post, subscribe to my blog here. You can find more details about X-Frame-Options and Content-Security-Policy headers on this page.

References

  1. Clickjacking cheat sheet – Clickjacking
  2. Clickjacking – Clickjacking-2

 

How to use Spring Security in web application – Part VIII

In this post, we will show how to use Spring Boot Security to login, authorization based on user role, log out, and error handling.

We will be discussing the following use case

  1. A user accesses a home page for an application.
  2. A user enters credentials
  3. If correct credentials, we create a session and verifies the user role. User with USER role sees the user profile page. User with ADMIN role sees the list of users page.
  4. Incorrect credentials, the user will see the login screen once again to enter credentials.
  5. A user clicks on logout, the session is deleted and the user is redirected to the login page.
  6. If a user (of any role) tries to login after logout, the user should be redirected to the appropriate page
  7. In a scenario where a user is neither USER nor ADMIN, he is redirected to the error page
  8. Handling of CSRF token

To completely understand this post, make sure you have gone through my other posts on the Spring Boot series.

  1. Spring Boot REST CRUD API
  2. Swagger Documentation
  3. User Interface using AngularJS

 

Database changes

Since this post involves authorization for users, we have to do some database changes. We will add a couple of tables and respective model classes in our REST API modification.

  • Table role
  • Table user_role

create table role (id int(11) auto_increment primary key not null, role varchar(255) )

create table user_role (user_id int(11) primary key not null, role_id int(11) primary key not null))

user_role the table helps to maintain a many-to-many relationship between the user and role table. We will have only two roles for demo purposes, USER and ADMIN.

Another change we have done in table user is that we have added a field called password_hash to store password set by user/administrator for a user to login. We will be storing a hash password value of the original password that the user will set.

Dependencies

Since we will be using Spring-security for authentication and authorization purposes, we will add the dependency for spring security as follows:

<dependency>   

<groupId>org.springframework.boot</groupId>   

<artifactId>spring-boot-starter-security</artifactId>

</dependency>

Controllers and Web Layer

Other than those changes mentioned, we will demonstrate this post in top-down fashion rather than bottom-up fashion.

So for the web layer, we will define a new controller LoginController and modify our existing MainController.

package com.betterjavacode.benefits.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.betterjavacode.benefits.entities.User;
import com.betterjavacode.benefits.interfaces.UserManager;

/**
*
* @author Yogesh Mali
*
*/
@Controller
public class LoginController {

public static final Logger LOGGER = LogManager.getLogger(LoginController.class);

@Autowired
UserManager userManager;

/**
*
* @param model
* @return
*/
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String userpage(Model model) 
{
  LOGGER.info(" Enter >> userpage() ");
  Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  String name = auth.getName();
  User user = userManager.findUserByEmail(name);
  model.addAttribute("name", user.getFirstname());
  model.addAttribute("userid", user.getId());
  LOGGER.info(" Exit << userpage() ");
  return "user";
}

/**
*
* @return
*/
@RequestMapping(value = { "/login" })
public String login() {
  return "login";
}

/**
*
* @return
*/
@RequestMapping(value = "/403", method = RequestMethod.GET)
public String Error403() {
  return "403";
}
}

As shown in this controller, we have defined a user page, a login page, and an error page (403). A user with the role of either USER or ADMIN or both can access a user page which shows that logged in user’s profile.

Every user irrespective of roles will see the login page for authentication. If there are any errors during authentication or authorization, the user will see an error page displaying access denied page (403).

Source code for login page is as below:

<!DOCTYPE html><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head> <title>Benefits Application</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" th:href="@{/css/login.css}" />  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></head>
<body>
<div class="container"> <form th:action="@{/login}" method="POST" class="form-signin">
<h3 class="form-signin-heading" th:text="Welcome"></h3>
<input type="text" id="email" name="username"  th:placeholder="Email" class="form-control" style="width:350px"/>
<input type="password"  th:placeholder="Password" id="password" name="password" class="form-control" style="width:350px"/>
<div align="center" th:if="${param.error}">
<p style="font-size: 20; color: #FF1C19;">Email or Password invalid, please verify</p>

</div>
<button class="btn btn-lg btn-primary btn-block" name="Submit" value="Login" type="Submit" th:text="Login" style="width:350px"></button> </form></div>
</body></html>

This login page shows a simple form to input username (email) and password and process that authentication using spring-security database authentication method.

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String homepage(Model model) 
{
  LOGGER.info(" Enter >> homepage() ");
  Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  String name = auth.getName();
  User user = userManager.findUserByEmail(name);
  model.addAttribute("name", user.getFirstname());
  LOGGER.info(" Exit << homepage() ");
  return "index";
}

Changes in MainController are about an authenticated user and passing that user’s first name to model to display in HTML page. UserManager in the service layer has been enhanced to return a user based on username (which is email). We have also added an email to be unique as a constraint in the database.

User page for a user with role USER is nothing but a user profile information that he can edit and update any time.

<html ng-app="benefitApp"><html ng-app="benefitApp"><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Benefit Application</title><script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="/css/bootstrap.css" /><script src="https://code.angularjs.org/1.6.1/angular.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-resource.js"></script><script type="text/javascript" src="./js/app.js"></script></head><body ng-controller="UserCtrl">Hello
<p th:text="${name}"></p>

<div>
<ul class="menu">
<li><a th:href="@{'userProfile/' + ${userid}}">Profile</a></li>
</ul>
<div ng-view="ng-view"></div>
</div>
<div class="input-group">
<div class="controls">    <a ng-click="logout()" class="btn btn-small">Logout</a></div>
</div>
</body></html>

Authentication

Now we have the application ready with all the required backend details for adding the authentication part. Remember we are using spring-security for authentication and authorization of an application.

package com.betterjavacode.benefits;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@ComponentScan("com.betterjavacode.benefits.services")
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

public static final Logger LOGGER = LogManager.getLogger(SecurityConfig.class);

@Autowired
private SimpleAuthenticationSuccessHandler loginSuccess;

@Autowired
private LogoutSuccess logoutSuccess;

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

@Autowired
private DataSource dataSource;

@Value("${spring.queries.users-query}")
private String usersQuery;

@Value("${spring.queries.roles-query}")
private String rolesQuery;

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
LOGGER.info(" Enter >> configureGlobal() ");
auth.jdbcAuthentication()
.usersByUsernameQuery("select email,password_hash,enabled from user where email=?")
.authoritiesByUsernameQuery("select u.email,r.role from user u inner join user_role ur on(u.id=ur.user_id) inner join role r on(r.id=ur.role_id) where u.email=?")
.dataSource(dataSource)
.passwordEncoder(bCryptPasswordEncoder);
LOGGER.info(" Exit << configureGlobal() ");
}

/**
* Handle Login - Authentication and Redirection
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/home")
.hasAuthority("ADMIN")
.antMatchers("/user")
.hasAnyAuthority("USER", "ADMIN")
.and()
.formLogin()
.loginPage("/login")
.successHandler(loginSuccess)
.permitAll()
.and()
.logout()
.logoutSuccessHandler(logoutSuccess)
.deleteCookies("JSESSIONID")
.invalidateHttpSession(false)
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/403");

}

/**
* Exclude resources from user-access
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
}

What’s happening in this code?

  • When a user with role ADMIN or USER calls either /home or /user pages respectively, the user will need to log in.
  • Once the user inputs credentials, validation of credentials happens against the JDBC database authentication mechanism provided by spring-security.
  • If a user of the role USER tries to access the ADMIN home page, the user sees an error 403 page. Authentication Success Handler handles the redirection strategy.
  • If the user clicks the LOGOUT button on the page he is on, the session gets deleted and the user logs out of the application. The user will see the login page. All the cookies will be deleted. Logout Success Handler handles the redirection.

 

Changes in AngularJS User Interface Controller

As shown in user.html page, once the user with role USER is logged in, he sees URL for his profile information. If a user clicks this URL, the user sees his or her profile information. This page has a controller called UserCtrl which basically handles the logout on this initial page. User Profile is shown on userprofile.html page which has singleusercontroller. This angular js controller handles updating user profile information or logout. The github repository contains the rest of the code.

Handling CSRF Token

There are two ways we can handle Cross-Site Request Forgery token in the Spring application. The first way is by disabling this token generation. This is not a recommended approach as this put your application to possible CSRF security attacks for hackers. If you are just doing this for demo purposes, you can disable this in SecurityConfig.java by calling http.csrf().disable().

As Spring points out, a request coming through browsers should contain CSRF Protection.

We will be using spring security to handle CSRF token on the server-side rather than on the client-side.  So every request that comes to the server, we will add a CSRF token and then verified. Angular JS verifies the cookie for the CSRF token before a user can post any request.

Add a CSRF Filter Class

We will add a filter that will handle setting of CSRF token in a cookie. Angular JS expects a cookie name to be as XSRF-TOKEN. This class will look like below:

public class CSRFHeaderFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException 
{
  CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
  if (csrf != null) 
  {
    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
    String token = csrf.getToken();
    if (cookie == null || token != null && !token.equals(cookie.getValue())) 
    {
      cookie = new Cookie("XSRF-TOKEN", token);
      cookie.setPath("/");
      response.addCookie(cookie);
    }
  }
  filterChain.doFilter(request, response);
}

}

Now we will enable csrf token in SecurityConfig as shown below

.and()
.csrf()
.csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(new CSRFHeaderFilter(), CsrfFilter.class);

What is csrfTokenRepository?

We tell spring-security to expect CSRF token in the format that Angular wants to send it back , a header called X-XSRF-TOKEN instead of default X-CSRF-TOKEN. With these changes, we don’t have to do anything on client side.

private CsrfTokenRepository csrfTokenRepository() 
{
  HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
  repository.setHeaderName("X-XSRF-TOKEN");
  return repository;
}

Demo

In this post, we showed how to use spring security for authentication and authorization. Now we will show how to run the application. Once the application is built and run from eclipse, access the page https://localhost:8443/home , we will see below screen:

It will be the same screen if you access https://localhost:8443/user. Now if we enter credentials of an admin user, we will see below screen:

User screen will be as below:

If you click logout, it will log the user out and show login screen again. In this way, we showed how we can use spring security for authentication and authorization. Code for this is available at Github repository.

References

  1. Spring Boot Security
  2. Login Page Angular JS and Spring Security