Spring MVC Customized User Login Logout Implementation Example

This post describes how to implement a customized user access to an Spring MVC web application (login logout). As a prerequisite, readers are advised to read this post which introduces several Spring Security concepts.

The code example is available from Github in the Spring-MVC-Login-Logout directory. It is derived from the Spring MVC with annotations example.

Customized Authentication Provider

In order to implementation our own way of accepting user login requests, we need to implement an authentication provider. The following let’s users in if their id is identical to their passwords:

public class MyAuthenticationProvider implements AuthenticationProvider {

    private static final List<GrantedAuthority> AUTHORITIES
        = new ArrayList<GrantedAuthority>();

    static {
        AUTHORITIES.add(new SimpleGrantedAuthority('ROLE_USER'));
        AUTHORITIES.add(new SimpleGrantedAuthority('ROLE_ANONYMOUS'));

    public Authentication authenticate(Authentication auth)
        throws AuthenticationException {

        if (auth.getName().equals(auth.getCredentials())) {
            return new UsernamePasswordAuthenticationToken(auth.getName(),
                auth.getCredentials(), AUTHORITIES);

        throw new BadCredentialsException('Bad Credentials');


    public boolean supports(Class<?> authentication) {
        if ( authentication == null ) return false;

        return Authentication.class.isAssignableFrom(authentication);



We need to create a security.xml file:

<beans:beans xmlns='http://www.springframework.org/schema/security'




        <intercept-url pattern='/*' access='ROLE_ANONYMOUS'/>
            always-use-default-target='true' />
        <anonymous />
        <logout />

    <authentication-manager alias='authenticationManager'>
      <authentication-provider ref='myAuthenticationProvider' />

    <beans:bean id='myAuthenticationProvider'
      class='com.jverstry.LoginLogout.Authentication.MyAuthenticationProvider' />

The above makes sure all users have the anonymous role to access any page. Once logged in, they are redirected to the main page. If they don’t log in, they are automatically considered as anonymous users. A logout function is also declared. Rather than re-implementing the wheel, we use items delivered by Spring itself.

Main Page

We implement a main page displaying the name of the currently logged in user, together with login and logout links:

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<!doctype html>
<html lang='en'>
  <meta charset='utf-8'>
  <title>Welcome To MVC Customized Login Logout!!!</title>
    <h1>Spring MVC Customized Login Logout !!!</h1>
    Who is currently logged in? <c:out value='${CurrPrincipal}' /> !<br />
    <a href='<c:url value='/spring_security_login'/>'>Login</a> 
    <a href='<c:url value='/j_spring_security_logout'/>'>Logout</a>


We need to provide the currently logged in user name to the view:

public class MyController {

    @RequestMapping(value = '/')
    public String home(Model model) {


        return 'index';



Running The Example

Once compile, one can start the example by browsing: http://localhost:9292/spring-mvc-login-logout/. It will display the following:

Log in using the same id and password:

The application returns to the main and displays:

More Spring related posts here.

Happy coding and don’t forget to share!

Reference: Spring MVC Customized User Login Logout Implementation Example from our JCG partner Jerome Versrynge at the Technical Notes blog.

Related Whitepaper:

Introduction to Web Applications Development

Kick start your web apps development with this introductory ebook!

This 376 page eBook 'Introduction to Web Applications Development', starts with an introduction to the internet, including a brief history of the TCT/IP protocol and World Wide Web. It defines the basic concepts for web servers and studies the case of Apache, the most used webserver, while other free software webservers are not forgotten. It continues with webpage design focusing on HTML and JavaScript. XML Schemas, their validation and transformation are covered as well as dynamic webpages built with CGI, PHP or JSP and database access.

Get it Now!  

One Response to "Spring MVC Customized User Login Logout Implementation Example"

  1. I need an interface for AuthenticationProvider

Leave a Reply

five − = 4

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books