[java] Two Page Login with Spring Security 3.2.x

We are brand new to Java, Spring, and Spring Security, but not new to development. We've been able to create a Spring Security-based Thymeleaf login page that uses a JNDI datasource to connect to our SQL Server database using BCrypt encrypted passwords. All of that is working without a hitch. However, the client wants a two-stage login. The first page requests a company ID that then loads a login page with specific graphics and text for that company, which allows the user to know that they are not logging into a phishing site. That login page would then request the user name and password.

We have searched extensively on here and the web as a whole and have not found a solid method for doing this. We believe that we may to have to create a custom UserDetailsService and AuthenticationManager, but still can't see how to implement it so that:

  1. User cannot bypass first login screen and go straight to second screen
  2. SpringSecurity is in control of both pages

We saw one suggestion about using Spring WebFlow with Spring Security, but without some starting point, have no idea how WebFlow works or applies to this scenario. This site helped us greatly in getting to this stage, but now we are stymied. Any help you can provide is greatly appreciated.

This question is related to java spring security spring-mvc spring-security

The answer is


There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).


Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with spring tag:

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type No String-argument constructor/factory method to deserialize from String value ('') Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException Read file from resources folder in Spring Boot RestClientException: Could not extract response. no suitable HttpMessageConverter found The origin server did not find a current representation for the target resource or is not willing to disclose that one exists The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat Spring boot: Unable to start embedded Tomcat servlet container Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start 'Field required a bean of type that could not be found.' error spring restful API using mongodb java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Unsupported Media Type in postman Configure active profile in SpringBoot via Maven How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? MultipartException: Current request is not a multipart request Consider defining a bean of type 'service' in your configuration [Spring boot] UnsatisfiedDependencyException: Error creating bean with name How Spring Security Filter Chain works Spring Boot Java Config Set Session Timeout What is the recommended project structure for spring boot rest projects? Spring @Autowired and @Qualifier Spring security CORS Filter 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE how to use Spring Boot profiles Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Check date between two other dates spring data jpa How to beautifully update a JPA entity in Spring Data? How do I activate a Spring Boot profile when running from IntelliJ? Spring-boot default profile for integration tests Unable to find a @SpringBootConfiguration when doing a JpaTest Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET) Spring Boot @Value Properties Where is the application.properties file in a Spring Boot project? How to return a html page from a restful controller in spring boot? How to set Spring profile from system variable? How to POST form data with Spring RestTemplate? Spring Data and Native Query with pagination Spring Resttemplate exception handling Spring Boot - Loading Initial Data Pass multiple parameters to rest API - Spring org.springframework.web.client.HttpClientErrorException: 400 Bad Request

Questions with security tag:

Monitoring the Full Disclosure mailinglist Two Page Login with Spring Security 3.2.x How to prevent a browser from storing passwords JWT authentication for ASP.NET Web API How to use a client certificate to authenticate and authorize in a Web API Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How does Content Security Policy (CSP) work? How to prevent Screen Capture in Android Default SecurityProtocol in .NET 4.5 JWT refresh token flow If you can decode JWT, how are they secure? JWT (JSON Web Token) automatic prolongation of expiration Explanation of polkitd Unregistered Authentication Agent SecurityError: Blocked a frame with origin from accessing a cross-origin frame SSL Error: unable to get local issuer certificate How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source? How to create a laravel hashed password Docker and securing passwords Node.js https pem error: routines:PEM_read_bio:no start line iptables LOG and DROP in one rule How to make a machine trust a self-signed Java application SPA best practices for authentication and session management ASP.NET Identity's default Password Hasher - How does it work and is it secure? Why is it common to put CSRF prevention tokens in cookies? XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP best practice to generate random token for forgot password Is it possible to decrypt SHA1 How to allow http content within an iframe on a https site Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox? How do I generate a SALT in Java for Salted-Hash? Disable cross domain web security in Firefox Can local storage ever be considered secure? Disable firefox same origin policy How do you Encrypt and Decrypt a PHP String? Best practices when running Node.js with port 80 (Ubuntu / Linode) Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running" Java Error: "Your security settings have blocked a local application from running" Spring Test & Security: How to mock authentication? encrypt and decrypt md5 C - The %x format specifier How to find the privileges and roles granted to a user in Oracle? What are good ways to prevent SQL injection? Found 'OR 1=1/* sql injection in my newsletter database How to avoid reverse engineering of an APK file? OAuth2 and Google API: access token expiration time? How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data How to securely save username/password (local)? SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application Securely storing passwords for use in python script

Questions with spring-mvc tag:

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET) How to upload a file and JSON data in Postman? Load different application.yml in SpringBoot Test What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot Pass multiple parameters to rest API - Spring How to configure Spring Security to allow Swagger URL to be accessed without authentication What is username and password when starting Spring Boot with Tomcat? Failed to load ApplicationContext (with annotation) How to return a custom object from a Spring Data JPA GROUP BY query When to use Spring Security`s antMatcher()? Difference between Interceptor and Filter in Spring MVC Using env variable in Spring Boot's application.properties Spring RequestMapping for controllers that produce and consume JSON Spring CORS No 'Access-Control-Allow-Origin' header is present How to pass List<String> in post method using Spring MVC? Http Post request with content type application/x-www-form-urlencoded not working in Spring Spring Boot @autowired does not work, classes in different package Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap Thymeleaf using path variables to th:href Spring Boot application can't resolve the org.springframework.boot package How to set base url for rest in spring boot? Difference between Spring MVC and Spring Boot How to return JSON data from spring Controller using @ResponseBody WARNING: Exception encountered during context initialization - cancelling refresh attempt How return error message in spring mvc @Controller CORS with spring-boot and angularjs not working Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call This application has no explicit mapping for /error Spring Boot Adding Http Request Interceptors When do I use path params vs. query params in a RESTful API? Spring MVC - How to return simple String as JSON in Rest Controller Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups Spring MVC 4: "application/json" Content Type is not being set correctly How to disable spring security for particular url Spring Boot Configure and Use Two DataSources Trying to use Spring Boot REST to Read JSON String from POST Convert a object into JSON in REST service by Spring MVC Spring boot - Not a managed type How does the Spring @ResponseBody annotation work? @Autowired - No qualifying bean of type found for dependency at least 1 bean "Could not find acceptable representation" using spring-boot-starter-web

Questions with spring-security tag:

Two Page Login with Spring Security 3.2.x Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized Unsupported Media Type in postman How Spring Security Filter Chain works Spring security CORS Filter How to configure CORS in a Spring Boot + Spring Security application? Failed to load ApplicationContext (with annotation) disabling spring security in spring boot app When to use Spring Security`s antMatcher()? How to manage exceptions thrown in filters in Spring? How do I enable logging for Spring Security? Remove "Using default security password" on Spring Boot How to disable spring security for particular url How to disable 'X-Frame-Options' response header in Spring Security? How to use OAuth2RestTemplate? Serving static web resources in Spring Boot & Spring Security application Spring boot Security Disable security Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session Spring Security exclude url patterns in security annotation configurartion How To Inject AuthenticationManager using Java Configuration in a Custom Filter Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN' Handle spring security authentication exceptions with @ExceptionHandler Difference between Role and GrantedAuthority in Spring Security Is it possible to decrypt SHA1 How to use new PasswordEncoder from Spring Security Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security) An Authentication object was not found in the SecurityContext - Spring 3.2.2 My Application Could not open ServletContext resource Spring Security redirect to previous page after successful login How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles? RESTful Authentication via Spring How to get active user's UserDetails Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security] Spring Security with roles and permissions Get UserDetails object from Security Context in Spring MVC controller How to manually set an authenticated user in Spring Security / SpringMVC How to check "hasRole" in Java Code with Spring Security? Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security] How do I get the Session Object in Spring? Unit testing with Spring Security When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?