onetimetoken.adoc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. [[one-time-token-login]]
  2. = One-Time Token Login
  3. Spring Security offers support for One-Time Token (OTT) authentication via the `oneTimeTokenLogin()` DSL.
  4. Before diving into implementation details, it's important to clarify the scope of the OTT feature within the framework, highlighting what is supported and what isn't.
  5. == Understanding One-Time Tokens vs. One-Time Passwords
  6. It's common to confuse One-Time Tokens (OTT) with https://en.wikipedia.org/wiki/One-time_password[One-Time Passwords] (OTP), but in Spring Security, these concepts differ in several key ways.
  7. For clarity, we'll assume OTP refers to https://en.wikipedia.org/wiki/Time-based_one-time_password[TOTP] (Time-Based One-Time Password) or https://en.wikipedia.org/wiki/HMAC-based_one-time_password[HOTP] (HMAC-Based One-Time Password).
  8. === Setup Requirements
  9. - OTT: No initial setup is required. The user doesn't need to configure anything in advance.
  10. - OTP: Typically requires setup, such as generating and sharing a secret key with an external tool to produce the one-time passwords.
  11. === Token Delivery
  12. - OTT: Usually a custom javadoc:org.springframework.security.web.authentication.ott.GeneratedOneTimeTokenHandler[] must be implemented, responsible for delivering the token to the end user.
  13. - OTP: The token is often generated by an external tool, so there's no need to send it to the user via the application.
  14. === Token Generation
  15. - OTT: The javadoc:org.springframework.security.authentication.ott.OneTimeTokenService#generate(org.springframework.security.authentication.ott.GenerateOneTimeTokenRequest)[] method requires a javadoc:org.springframework.security.authentication.ott.OneTimeToken[] to be returned, emphasizing server-side generation.
  16. - OTP: The token is not necessarily generated on the server side, it's often created by the client using the shared secret.
  17. In summary, One-Time Tokens (OTT) provide a way to authenticate users without additional account setup, differentiating them from One-Time Passwords (OTP), which typically involve a more complex setup process and rely on external tools for token generation.
  18. The One-Time Token Login works in two major steps.
  19. 1. User requests a token by submitting their user identifier, usually the username, and the token is delivered to them, often as a Magic Link, via e-mail, SMS, etc.
  20. 2. User submits the token to the one-time token login endpoint and, if valid, the user gets logged in.
  21. [[default-pages]]
  22. == Default Login Page and Default One-Time Token Submit Page
  23. The `oneTimeTokenLogin()` DSL can be used in conjunction with `formLogin()`, which will produce an additional One-Time Token Request Form in the xref:servlet/authentication/passwords/form.adoc[default generated login page].
  24. It will also set up the javadoc:org.springframework.security.web.authentication.ui.DefaultOneTimeTokenSubmitPageGeneratingFilter[] to generate a default One-Time Token submit page.
  25. In the following sections we will explore how to configure OTT Login for your needs.
  26. - <<sending-token-to-user,Sending the token to the user>>
  27. - <<changing-submit-page-url,Configuring the One-Time Token submit page>>
  28. - <<changing-generate-url,Changing the One-Time Token generate URL>>
  29. [[sending-token-to-user]]
  30. == Sending the Token to the User
  31. It is not possible for Spring Security to reasonably determine the way the token should be delivered to your users.
  32. Therefore, a custom javadoc:org.springframework.security.web.authentication.ott.GeneratedOneTimeTokenHandler[] must be provided to deliver the token to the user based on your needs.
  33. One of the most common delivery strategies is a Magic Link, via e-mail, SMS, etc.
  34. In the following example, we are going to create a magic link and sent it to the user's email.
  35. .One-Time Token Login Configuration
  36. [tabs]
  37. ======
  38. Java::
  39. +
  40. [source,java,role="primary"]
  41. ----
  42. @Configuration
  43. @EnableWebSecurity
  44. public class SecurityConfig {
  45. @Bean
  46. public SecurityFilterChain filterChain(HttpSecurity http, MagicLinkGeneratedOneTimeTokenSuccessHandler magicLinkSender) {
  47. http
  48. // ...
  49. .formLogin(Customizer.withDefaults())
  50. .oneTimeTokenLogin(Customizer.withDefaults());
  51. return http.build();
  52. }
  53. }
  54. import org.springframework.mail.SimpleMailMessage;
  55. import org.springframework.mail.javamail.JavaMailSender;
  56. @Component <1>
  57. public class MagicLinkGeneratedOneTimeTokenSuccessHandler implements GeneratedOneTimeTokenSuccessHandler {
  58. private final MailSender mailSender;
  59. private final GeneratedOneTimeTokenSuccessHandler redirectHandler = new RedirectGeneratedOneTimeTokenSuccessHandler("/ott/sent");
  60. // constructor omitted
  61. @Override
  62. public void handle(HttpServletRequest request, HttpServletResponse response, OneTimeToken oneTimeToken) throws IOException, ServletException {
  63. UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
  64. .replacePath(request.getContextPath())
  65. .replaceQuery(null)
  66. .fragment(null)
  67. .path("/login/ott")
  68. .queryParam("token", oneTimeToken.getTokenValue()); <2>
  69. String magicLink = builder.toUriString();
  70. String email = getUserEmail(oneTimeToken.getUsername()); <3>
  71. this.mailSender.send(email, "Your Spring Security One Time Token", "Use the following link to sign in into the application: " + magicLink); <4>
  72. this.redirectHandler.handle(request, response, oneTimeToken); <5>
  73. }
  74. private String getUserEmail() {
  75. // ...
  76. }
  77. }
  78. @Controller
  79. class PageController {
  80. @GetMapping("/ott/sent")
  81. String ottSent() {
  82. return "my-template";
  83. }
  84. }
  85. ----
  86. ======
  87. <1> Make the `MagicLinkGeneratedOneTimeTokenSuccessHandler` a Spring bean
  88. <2> Create a login processing URL with the `token` as a query param
  89. <3> Retrieve the user's email based on the username
  90. <4> Use the `JavaMailSender` API to send the email to the user with the magic link
  91. <5> Use the `RedirectGeneratedOneTimeTokenSuccessHandler` to perform a redirect to your desired URL
  92. The email content will look similar to:
  93. > Use the following link to sign in into the application: \http://localhost:8080/login/ott?token=a830c444-29d8-4d98-9b46-6aba7b22fe5b
  94. The default submit page will detect that the URL has the `token` query param and will automatically fill the form field with the token value.
  95. [[changing-generate-url]]
  96. == Changing the One-Time Token Generate URL
  97. By default, the javadoc:org.springframework.security.web.authentication.ott.GenerateOneTimeTokenFilter[] listens to `POST /ott/generate` requests.
  98. That URL can be changed by using the `generateTokenUrl(String)` DSL method:
  99. .Changing the Generate URL
  100. [tabs]
  101. ======
  102. Java::
  103. +
  104. [source,java,role="primary"]
  105. ----
  106. @Configuration
  107. @EnableWebSecurity
  108. public class SecurityConfig {
  109. @Bean
  110. public SecurityFilterChain filterChain(HttpSecurity http) {
  111. http
  112. // ...
  113. .formLogin(Customizer.withDefaults())
  114. .oneTimeTokenLogin((ott) -> ott
  115. .generateTokenUrl("/ott/my-generate-url")
  116. );
  117. return http.build();
  118. }
  119. }
  120. @Component
  121. public class MagicLinkGeneratedOneTimeTokenSuccessHandler implements GeneratedOneTimeTokenSuccessHandler {
  122. // ...
  123. }
  124. ----
  125. ======
  126. [[changing-submit-page-url]]
  127. == Changing the Default Submit Page URL
  128. The default One-Time Token submit page is generated by the javadoc:org.springframework.security.web.authentication.ui.DefaultOneTimeTokenSubmitPageGeneratingFilter[] and listens to `GET /login/ott`.
  129. The URL can also be changed, like so:
  130. .Configuring the Default Submit Page URL
  131. [tabs]
  132. ======
  133. Java::
  134. +
  135. [source,java,role="primary"]
  136. ----
  137. @Configuration
  138. @EnableWebSecurity
  139. public class SecurityConfig {
  140. @Bean
  141. public SecurityFilterChain filterChain(HttpSecurity http) {
  142. http
  143. // ...
  144. .formLogin(Customizer.withDefaults())
  145. .oneTimeTokenLogin((ott) -> ott
  146. .submitPageUrl("/ott/submit")
  147. );
  148. return http.build();
  149. }
  150. }
  151. @Component
  152. public class MagicLinkGeneratedOneTimeTokenSuccessHandler implements GeneratedOneTimeTokenSuccessHandler {
  153. // ...
  154. }
  155. ----
  156. ======
  157. [[disabling-default-submit-page]]
  158. == Disabling the Default Submit Page
  159. If you want to use your own One-Time Token submit page, you can disable the default page and then provide your own endpoint.
  160. .Disabling the Default Submit Page
  161. [tabs]
  162. ======
  163. Java::
  164. +
  165. [source,java,role="primary"]
  166. ----
  167. @Configuration
  168. @EnableWebSecurity
  169. public class SecurityConfig {
  170. @Bean
  171. public SecurityFilterChain filterChain(HttpSecurity http) {
  172. http
  173. .authorizeHttpRequests((authorize) -> authorize
  174. .requestMatchers("/my-ott-submit").permitAll()
  175. .anyRequest().authenticated()
  176. )
  177. .formLogin(Customizer.withDefaults())
  178. .oneTimeTokenLogin((ott) -> ott
  179. .showDefaultSubmitPage(false)
  180. );
  181. return http.build();
  182. }
  183. }
  184. @Controller
  185. public class MyController {
  186. @GetMapping("/my-ott-submit")
  187. public String ottSubmitPage() {
  188. return "my-ott-submit";
  189. }
  190. }
  191. @Component
  192. public class MagicLinkGeneratedOneTimeTokenSuccessHandler implements GeneratedOneTimeTokenSuccessHandler {
  193. // ...
  194. }
  195. ----
  196. ======