form.asc 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. = Creating a Custom Login Form
  2. :author: Rob Winch
  3. :starter-appname: hellomvc-jc
  4. :completed-appname: form-jc
  5. :include-dir: _includes
  6. 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.
  7. include::{include-dir}/setting-up-the-sample.asc[]
  8. Verify the application is working:
  9. * A page displaying a user's inbox can be seen at http://localhost:8080/sample/
  10. * Try clicking on the Compose link and creating a message. The message details should be displayed.
  11. * Now click on the Inbox link and see the message listed. You can click on the summary link to see the details displayed again.
  12. = Overriding the default configure(HttpSecurity) method
  13. 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
  14. up and running quickly. However, our login form does not look like the rest of our application. Let's see how we can update our configuration to use a custom form.
  15. == Default configure(HttpSecurity)
  16. The default configuration for the configure(HttpSecurity) method can be seen below:
  17. [source,java]
  18. ----
  19. protected void configure(HttpSecurity http) throws Exception {
  20. http
  21. .authorizeRequests()
  22. .anyRequest().authenticated() <1>
  23. .and()
  24. .formLogin() <2>
  25. .and()
  26. .httpBasic(); <3>
  27. }
  28. ----
  29. The configuration ensures that:
  30. <1> every request requires the user to be authenticated
  31. <2> form based authentication is supported
  32. <3> HTTP Basic Authentication is supported
  33. == Configuring a custom login page
  34. 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:
  35. .src/main/java/org/springframework/security/samples/config/SecurityConfig.java
  36. [source,java]
  37. ----
  38. // ...
  39. @Configuration
  40. @EnableWebSecurity
  41. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  42. @Override
  43. protected void configure(HttpSecurity http) throws Exception {
  44. http
  45. .authorizeRequests()
  46. .anyRequest().authenticated()
  47. .and()
  48. .formLogin()
  49. .loginPage("/login");
  50. }
  51. // ...
  52. }
  53. ----
  54. The line `loginPage("/login")` instructs Spring Security
  55. * when authentication is required, redirect the browser to */login*
  56. * we are in charge of rendering the login page when */login* is requested
  57. * when authentication attempt fails, redirect the browser to */login?error* (since we have not specified otherwise)
  58. * we are in charge of rendering a failure page when */login?error* is requested
  59. * when we successfully logout, redirect the browser to */login?logout* (since we have not specified otherwise)
  60. * we are in charge of rendering a logout confirmation page when */login?logout* is requested
  61. 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?
  62. == Granting access to unauthenticated users
  63. The issue is that Spring Security is protecting access to our custom login page. In particular the following is happening:
  64. * We make a request to our web application
  65. * Spring Security sees that we are not authenticated
  66. * We are redirected to */login*
  67. * The browser requests */login*
  68. * Spring Security sees that we are not authenticated
  69. * We are redirected to */login* ...
  70. 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:
  71. .src/main/java/org/springframework/security/samples/config/SecurityConfig.java
  72. [source,java]
  73. ----
  74. // ...
  75. @Configuration
  76. @EnableWebSecurity
  77. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  78. @Override
  79. protected void configure(HttpSecurity http) throws Exception {
  80. http
  81. .authorizeRequests()
  82. .anyRequest().authenticated()
  83. .and()
  84. .formLogin()
  85. .loginPage("/login")
  86. .permitAll();
  87. }
  88. // ...
  89. }
  90. ----
  91. The `permitAll()` statement instructs Spring Security to allow any access to any URL (i.e. */login* and */login?error*) associated to `formLogin()`.
  92. 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.
  93. 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.
  94. = Creating a login page
  95. Within Spring Web MVC there are two steps to creating our login page:
  96. * Creating a controller
  97. * Creating a view
  98. == Configuring a login view controller
  99. 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:
  100. [source,java]
  101. ----
  102. // ...
  103. @EnableWebMvc
  104. @ComponentScan("org.springframework.security.samples.mvc")
  105. public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
  106. // ...
  107. @Override
  108. public void addViewControllers(ViewControllerRegistry registry) {
  109. registry.addViewController("/login").setViewName("login");
  110. registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
  111. }
  112. }
  113. ----
  114. == Creating a login view
  115. Our existing configuration means that all we need to do is create a *login.html* file with the following contents:
  116. .src/main/resources/views/login.html
  117. [source,xml]
  118. ----
  119. <html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org">
  120. <head>
  121. <title tiles:fragment="title">Messages : Create</title>
  122. </head>
  123. <body>
  124. <div tiles:fragment="content">
  125. <form name="f" th:action="@{/login}" method="post"> <1>
  126. <fieldset>
  127. <legend>Please Login</legend>
  128. <div th:if="${param.error}" class="alert alert-error"> <2>
  129. Invalid username and password.
  130. </div>
  131. <div th:if="${param.logout}" class="alert alert-success"> <3>
  132. You have been logged out.
  133. </div>
  134. <label for="username">Username</label>
  135. <input type="text" id="username" name="username"/> <4>
  136. <label for="password">Password</label>
  137. <input type="password" id="password" name="password"/> <5>
  138. <div class="form-actions">
  139. <button type="submit" class="btn">Log in</button>
  140. </div>
  141. </fieldset>
  142. </form>
  143. </div>
  144. </body>
  145. </html>
  146. ----
  147. <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*.
  148. <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.
  149. <3> When we are successfully logged 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.
  150. <4> The username should be present on the HTTP parameter username
  151. <5> The password should be present on the HTTP parameter password
  152. 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.
  153. 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}"/>`.
  154. 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.
  155. == Grant access to remaining resources
  156. We need to update our configuration to allow anyone to access our resources and our logout pages. Update the configuration as shown below:
  157. .src/main/java/org/springframework/security/samples/config/SecurityConfig.java
  158. [source,java]
  159. ----
  160. // ...
  161. @Configuration
  162. @EnableWebSecurity
  163. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  164. @Override
  165. protected void configure(HttpSecurity http) throws Exception {
  166. http
  167. .authorizeRequests()
  168. .antMatchers("/resources/**").permitAll() <1>
  169. .anyRequest().authenticated()
  170. .and()
  171. .formLogin()
  172. .loginPage("/login")
  173. .permitAll()
  174. .and()
  175. .logout() <2>
  176. .permitAll();
  177. }
  178. // ...
  179. }
  180. ----
  181. <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.
  182. <2> As you might expect, `logout().permitAll()` allows any user to request logout and view logout success URL.
  183. 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.
  184. * Try entering an invalid username and password. You will see our error message is displayed.
  185. * Try entering a valid username and password. You will be authenticated successfully.
  186. * Try clicking the Log Out button. You will see our logout success message
  187. == Conclusion
  188. You should now know how to add a custom login form using Spring Security's Java Configuration. To learn more refer to the link:index.html[Spring Security Guides index page].