Home » Java » Enterprise Java » Spring MVC Customized User Login Logout Implementation Example

About Jerome Versrynge

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'));
    }

    @Override
    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');

    }

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

        return Authentication.class.isAssignableFrom(authentication);
    }

}


Security.xml

We need to create a security.xml file:

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

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

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

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

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'>
<head>
  <meta charset='utf-8'>
  <title>Welcome To MVC Customized Login Logout!!!</title>
</head>
  <body>
    <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>
  </body>
</html>


Controller

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

@Controller
public class MyController {

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

        model.addAttribute('CurrPrincipal',
            SecurityContextHolder.getContext()
                .getAuthentication().getName());

        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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

One comment

  1. I need an interface for AuthenticationProvider

Leave a Reply

Your email address will not be published. Required fields are marked *

*


− four = 4

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close