123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255 |
- = Creating a Custom Login Form
- :author: Rob Winch
- :starter-appname: hellomvc-jc
- :completed-appname: form-jc
- :verify-starter-app-include: form-includes/verify-app.asc
- This guide builds off of link:hellomvc.html[Hello Spring MVC Security Java Config] to explain how to configure and use a custom login form with Spring Security Java Configuration.
- include::hello-includes/setting-up-the-sample.asc[]
- = Overriding the default configure(HttpSecurity) method
- As we saw in link:hellomvc.html[Hello Spring MVC Security Java Config], Spring Security's `WebSecurityConfigurerAdapter` provides some convenient defaults to get our application
- up and running quickly. However, our login form does not match the rest of our application. Let's see how we can update our configuration to use a custom form.
- == Default configure(HttpSecurity)
- The default configuration for the configure(HttpSecurity) method can be seen below:
- [source,java]
- ----
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated() <1>
- .and()
- .formLogin() <2>
- .and()
- .httpBasic(); <3>
- }
- ----
- The configuration ensures that:
- <1> every request requires the user to be authenticated
- <2> form based authentication is supported
- <3> HTTP Basic Authentication is supported
- == Configuring a custom login page
- We will want to ensure we compensate for overriding these defaults in our updates. Open up the `SecurityConfig` and insert the configure method as shown below:
- .src/main/java/org/springframework/security/samples/config/SecurityConfig.java
- [source,java]
- ----
- // ...
- @Configuration
- @EnableWebSecurity
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .formLogin()
- .loginPage("/login");
- }
- // ...
- }
- ----
- The line `loginPage("/login")` instructs Spring Security
- * when authentication is required, redirect the browser to */login*
- * we are in charge of rendering the login page when */login* is requested
- * when authentication attempt fails, redirect the browser to */login?error* (since we have not specified otherwise)
- * we are in charge of rendering a failure page when */login?error* is requested
- * when we successfully logout, redirect the browser to */login?logout* (since we have not specified otherwise)
- * we are in charge of rendering a logout confirmation page when */login?logout* is requested
- Go ahead and start up the server and try visiting http://localhost:8080/sample/ to see the updates to our configuration. In many browsers you will see an error similar to *This webpage has a redirect loop*. What is happening?
- == Granting access to unauthenticated users
- The issue is that Spring Security is protecting access to our custom login page. In particular the following is happening:
- * We make a request to our web application
- * Spring Security sees that we are not authenticated
- * We are redirected to */login*
- * The browser requests */login*
- * Spring Security sees that we are not authenticated
- * We are redirected to */login* ...
- To fix this we need to instruct Spring Security to allow anyone to access the */login* URL. We can easily do this with the following updates:
- .src/main/java/org/springframework/security/samples/config/SecurityConfig.java
- [source,java]
- ----
- // ...
- @Configuration
- @EnableWebSecurity
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .formLogin()
- .loginPage("/login")
- .permitAll();
- }
- // ...
- }
- ----
- The `permitAll()` statement instructs Spring Security to allow any access to any URL (i.e. */login* and */login?error*) associated to `formLogin()`.
- NOTE: Granting access to the `formLogin()` URLs is not done by default since Spring Security needs to make certain assumptions about what is allowed and what is not. To be secure, it is best to ensure granting access to resources is explicit.
- Start up the server and try visiting http://localhost:8080/sample/ to see the updates to our configuration. You should now get a 404 error stating that */login* cannot be found.
- = Creating a login page
- Within Spring Web MVC there are two steps to creating our login page:
- * Creating a controller
- * Creating a view
- == Configuring a login view controller
- Within Spring Web MVC, the first step is to ensure that we have a controller that can point to our view. Since our project adds the *messages-jc* project as a dependency and it contains a view controller for */login* we do not need to create a controller within our application. For reference, you can see the configuration below:
- [source,java]
- ----
- // ...
- @EnableWebMvc
- @ComponentScan("org.springframework.security.samples.mvc")
- public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
- // ...
- @Override
- public void addViewControllers(ViewControllerRegistry registry) {
- registry.addViewController("/login").setViewName("login");
- registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
- }
- @Bean
- public InternalResourceViewResolver jspxViewResolver() {
- InternalResourceViewResolver result = new InternalResourceViewResolver();
- result.setPrefix("/WEB-INF/views/");
- result.setSuffix(".jspx");
- return result;
- }
- }
- ----
- == Creating a login view
- Our existing configuration means that all we need to do is create a *login.jspx* file with the following contents:
- .src/main/webapp/WEB-INF/views/login.jspx
- [source,xml]
- ----
- <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
- xmlns:spring="http://www.springframework.org/tags"
- xmlns:c="http://java.sun.com/jsp/jstl/core"
- xmlns:form="http://www.springframework.org/tags/form" version="2.0">
- <jsp:directive.page language="java" contentType="text/html" />
- <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
- <head>
- <title>Please Login</title>
- </head>
- <body>
- <c:url value="/login" var="loginUrl"/>
- <form:form name="f" action="${loginUrl}" method="post"> <1>
- <fieldset>
- <legend>Please Login</legend>
- <c:if test="${param.error != null}"> <2>
- <div class="alert alert-error">
- Invalid username and password.
- </div>
- </c:if>
- <c:if test="${param.logout != null}"> <3>
- <div class="alert alert-success">
- You have been logged out.
- </div>
- </c:if>
- <label for="username">Username</label>
- <input type="text" id="username" name="username"/> <4>
- <label for="password">Password</label>
- <input type="password" id="password" name="password"/> <5>
- <div class="form-actions">
- <button type="submit" class="btn">Log in</button>
- </div>
- </fieldset>
- </form:form>
- </body>
- </html>
- </jsp:root>
- ----
- <1> The URL we submit our username and password to is the same URL as our login form (i.e. */login*), but a *POST* instead of a *GET*.
- <2> When authentication fails, the browser is redirected to */login?error* so we can display an error message by detecting if the parameter *error* is non-null.
- IMPORTANT: Do not display details about why authentication failed. For example, we do not want to display that the user does not exist as this will tell an attacker that they should try a different username.
- <3> When we are successfully loged out, the browser is redirected to */login?logout* so we can display an logout success message by detecting if the parameter *logout* is non-null.
- <4> The username should be present on the HTTP parameter username
- <5> The password should be present on the HTTP parameter password
- TIP: We use Spring Web MVC's <form:form> tag to automatically add the CSRF token to our form. We could also manually add the CSRF token using `<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>`.
- Start up the server and try visiting http://localhost:8080/sample/ to see the updates to our configuration. We now see our login page, but it does not look very pretty. The issue is that we have not granted access to the css files.
- == Grant access to remaining resources
- We need to update our configuration to allow anyone to access our resources and our logout pages. Update the configuration as shown below:
- .src/main/java/org/springframework/security/samples/config/SecurityConfig.java
- [source,java]
- ----
- // ...
- @Configuration
- @EnableWebSecurity
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .antMatchers("/resources/**").permitAll() <1>
- .anyRequest().authenticated()
- .and()
- .formLogin()
- .loginPage("/login")
- .permitAll()
- .and()
- .logout() <2>
- .permitAll();
- }
- // ...
- }
- ----
- <1> This allows anyone to access a URL that begins with */resources/*. Since this is where our css, javascript, and images are stored all our static resources are viewable by anyone.
- <2> As you might expect, `logout().permitAll()` allows any user to request logout and view logout success URL.
- Start up the server and try visiting http://localhost:8080/sample/ to see the updates to our configuration. We now see a custom login page that looks like the rest of our application.
- * Try entering an invalid username and password. You will see our error message is displayed.
- * Try entering a valid username and password. You will be authenticated successfully.
- * Try clicking the Log Out button. You will see our logout success message
|