onetimetoken.adoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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.OneTimeTokenGenerationSuccessHandler[] 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. In the following sections we will explore how to configure OTT Login for your needs.
  22. - <<default-pages,Understanding the integration with the default generated login page>>
  23. - <<sending-token-to-user,Sending the token to the user>>
  24. - <<changing-submit-page-url,Configuring the One-Time Token submit page>>
  25. - <<changing-generate-url,Changing the One-Time Token generate URL>>
  26. - <<customize-generate-consume-token,Customize how to generate and consume tokens>>
  27. [[default-pages]]
  28. == Default Login Page and Default One-Time Token Submit Page
  29. 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].
  30. It will also set up the javadoc:org.springframework.security.web.authentication.ui.DefaultOneTimeTokenSubmitPageGeneratingFilter[] to generate a default One-Time Token submit page.
  31. [[sending-token-to-user]]
  32. == Sending the Token to the User
  33. It is not possible for Spring Security to reasonably determine the way the token should be delivered to your users.
  34. Therefore, a custom javadoc:org.springframework.security.web.authentication.ott.OneTimeTokenGenerationSuccessHandler[] must be provided to deliver the token to the user based on your needs.
  35. One of the most common delivery strategies is a Magic Link, via e-mail, SMS, etc.
  36. In the following example, we are going to create a magic link and sent it to the user's email.
  37. .One-Time Token Login Configuration
  38. [tabs]
  39. ======
  40. Java::
  41. +
  42. [source,java,role="primary"]
  43. ----
  44. @Configuration
  45. @EnableWebSecurity
  46. public class SecurityConfig {
  47. @Bean
  48. public SecurityFilterChain filterChain(HttpSecurity http, MagicLinkGeneratedOneTimeTokenHandler magicLinkSender) {
  49. http
  50. // ...
  51. .formLogin(Customizer.withDefaults())
  52. .oneTimeTokenLogin(Customizer.withDefaults());
  53. return http.build();
  54. }
  55. }
  56. import org.springframework.mail.SimpleMailMessage;
  57. import org.springframework.mail.javamail.JavaMailSender;
  58. @Component <1>
  59. public class MagicLinkGeneratedOneTimeTokenHandler implements GeneratedOneTimeTokenSuccessHandler {
  60. private final MailSender mailSender;
  61. private final GeneratedOneTimeTokenHandler redirectHandler = new RedirectGeneratedOneTimeTokenHandler("/ott/sent");
  62. // constructor omitted
  63. @Override
  64. public void handle(HttpServletRequest request, HttpServletResponse response, OneTimeToken oneTimeToken) throws IOException, ServletException {
  65. UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
  66. .replacePath(request.getContextPath())
  67. .replaceQuery(null)
  68. .fragment(null)
  69. .path("/login/ott")
  70. .queryParam("token", oneTimeToken.getTokenValue()); <2>
  71. String magicLink = builder.toUriString();
  72. String email = getUserEmail(oneTimeToken.getUsername()); <3>
  73. this.mailSender.send(email, "Your Spring Security One Time Token", "Use the following link to sign in into the application: " + magicLink); <4>
  74. this.redirectHandler.handle(request, response, oneTimeToken); <5>
  75. }
  76. private String getUserEmail() {
  77. // ...
  78. }
  79. }
  80. @Controller
  81. class PageController {
  82. @GetMapping("/ott/sent")
  83. String ottSent() {
  84. return "my-template";
  85. }
  86. }
  87. ----
  88. Kotlin::
  89. +
  90. [source,kotlin,role="secondary"]
  91. ----
  92. @Configuration
  93. @EnableWebSecurity
  94. class SecurityConfig {
  95. @Bean
  96. open fun filterChain(
  97. http: HttpSecurity,
  98. magicLinkSender: MagicLinkGeneratedOneTimeTokenSuccessHandler?
  99. ): SecurityFilterChain {
  100. http{
  101. formLogin {}
  102. oneTimeTokenLogin { }
  103. }
  104. return http.build()
  105. }
  106. }
  107. import org.springframework.mail.SimpleMailMessage;
  108. import org.springframework.mail.javamail.JavaMailSender;
  109. @Component (1)
  110. class MagicLinkGeneratedOneTimeTokenSuccessHandler(
  111. private val mailSender: MailSender,
  112. private val redirectHandler: GeneratedOneTimeTokenHandler = RedirectGeneratedOneTimeTokenHandler("/ott/sent")
  113. ) : GeneratedOneTimeTokenHandler {
  114. override fun handle(request: HttpServletRequest, response: HttpServletResponse, oneTimeToken: OneTimeToken) {
  115. val builder = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
  116. .replacePath(request.contextPath)
  117. .replaceQuery(null)
  118. .fragment(null)
  119. .path("/login/ott")
  120. .queryParam("token", oneTimeToken.getTokenValue()) (2)
  121. val magicLink = builder.toUriString()
  122. val email = getUserEmail(oneTimeToken.getUsername()) (3)
  123. this.mailSender.send(email, "Your Spring Security One Time Token", "Use the following link to sign in into the application: $magicLink")(4)
  124. this.redirectHandler.handle(request, response, oneTimeToken) (5)
  125. }
  126. private fun getUserEmail(): String {
  127. // ...
  128. }
  129. }
  130. @Controller
  131. class PageController {
  132. @GetMapping("/ott/sent")
  133. fun ottSent(): String {
  134. return "my-template"
  135. }
  136. }
  137. ----
  138. ======
  139. <1> Make the `MagicLinkGeneratedOneTimeTokenHandler` a Spring bean
  140. <2> Create a login processing URL with the `token` as a query param
  141. <3> Retrieve the user's email based on the username
  142. <4> Use the `JavaMailSender` API to send the email to the user with the magic link
  143. <5> Use the `RedirectOneTimeTokenGenerationSuccessHandler` to perform a redirect to your desired URL
  144. The email content will look similar to:
  145. > Use the following link to sign in into the application: \http://localhost:8080/login/ott?token=a830c444-29d8-4d98-9b46-6aba7b22fe5b
  146. 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.
  147. [[changing-generate-url]]
  148. == Changing the One-Time Token Generate URL
  149. By default, the javadoc:org.springframework.security.web.authentication.ott.GenerateOneTimeTokenFilter[] listens to `POST /ott/generate` requests.
  150. That URL can be changed by using the `generateTokenUrl(String)` DSL method:
  151. .Changing the Generate URL
  152. [tabs]
  153. ======
  154. Java::
  155. +
  156. [source,java,role="primary"]
  157. ----
  158. @Configuration
  159. @EnableWebSecurity
  160. public class SecurityConfig {
  161. @Bean
  162. public SecurityFilterChain filterChain(HttpSecurity http) {
  163. http
  164. // ...
  165. .formLogin(Customizer.withDefaults())
  166. .oneTimeTokenLogin((ott) -> ott
  167. .generateTokenUrl("/ott/my-generate-url")
  168. );
  169. return http.build();
  170. }
  171. }
  172. @Component
  173. public class MagicLinkGeneratedOneTimeTokenHandler implements GeneratedOneTimeTokenSuccessHandler {
  174. // ...
  175. }
  176. ----
  177. Kotlin::
  178. +
  179. [source,kotlin,role="secondary"]
  180. ----
  181. @Configuration
  182. @EnableWebSecurity
  183. class SecurityConfig {
  184. @Bean
  185. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  186. http {
  187. //...
  188. formLogin { }
  189. oneTimeTokenLogin {
  190. generateTokenUrl = "/ott/my-generate-url"
  191. }
  192. }
  193. return http.build()
  194. }
  195. }
  196. @Component
  197. class MagicLinkGeneratedOneTimeTokenSuccessHandler : GeneratedOneTimeTokenHandler {
  198. // ...
  199. }
  200. ----
  201. ======
  202. [[changing-submit-page-url]]
  203. == Changing the Default Submit Page URL
  204. 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`.
  205. The URL can also be changed, like so:
  206. .Configuring the Default Submit Page URL
  207. [tabs]
  208. ======
  209. Java::
  210. +
  211. [source,java,role="primary"]
  212. ----
  213. @Configuration
  214. @EnableWebSecurity
  215. public class SecurityConfig {
  216. @Bean
  217. public SecurityFilterChain filterChain(HttpSecurity http) {
  218. http
  219. // ...
  220. .formLogin(Customizer.withDefaults())
  221. .oneTimeTokenLogin((ott) -> ott
  222. .submitPageUrl("/ott/submit")
  223. );
  224. return http.build();
  225. }
  226. }
  227. @Component
  228. public class MagicLinkGeneratedOneTimeTokenHandler implements GeneratedOneTimeTokenSuccessHandler {
  229. // ...
  230. }
  231. ----
  232. Kotlin::
  233. +
  234. [source,kotlin,role="secondary"]
  235. ----
  236. @Configuration
  237. @EnableWebSecurity
  238. class SecurityConfig {
  239. @Bean
  240. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  241. http {
  242. //...
  243. formLogin { }
  244. oneTimeTokenLogin {
  245. submitPageUrl = "/ott/submit"
  246. }
  247. }
  248. return http.build()
  249. }
  250. }
  251. @Component
  252. class MagicLinkGeneratedOneTimeTokenSuccessHandler : GeneratedOneTimeTokenHandler {
  253. // ...
  254. }
  255. ----
  256. ======
  257. [[disabling-default-submit-page]]
  258. == Disabling the Default Submit Page
  259. If you want to use your own One-Time Token submit page, you can disable the default page and then provide your own endpoint.
  260. .Disabling the Default Submit Page
  261. [tabs]
  262. ======
  263. Java::
  264. +
  265. [source,java,role="primary"]
  266. ----
  267. @Configuration
  268. @EnableWebSecurity
  269. public class SecurityConfig {
  270. @Bean
  271. public SecurityFilterChain filterChain(HttpSecurity http) {
  272. http
  273. .authorizeHttpRequests((authorize) -> authorize
  274. .requestMatchers("/my-ott-submit").permitAll()
  275. .anyRequest().authenticated()
  276. )
  277. .formLogin(Customizer.withDefaults())
  278. .oneTimeTokenLogin((ott) -> ott
  279. .showDefaultSubmitPage(false)
  280. );
  281. return http.build();
  282. }
  283. }
  284. @Controller
  285. public class MyController {
  286. @GetMapping("/my-ott-submit")
  287. public String ottSubmitPage() {
  288. return "my-ott-submit";
  289. }
  290. }
  291. @Component
  292. public class MagicLinkGeneratedOneTimeTokenHandler implements GeneratedOneTimeTokenSuccessHandler {
  293. // ...
  294. }
  295. ----
  296. Kotlin::
  297. +
  298. [source,kotlin,role="secondary"]
  299. ----
  300. @Configuration
  301. @EnableWebSecurity
  302. class SecurityConfig {
  303. @Bean
  304. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  305. http {
  306. authorizeHttpRequests {
  307. authorize("/my-ott-submit", authenticated)
  308. authorize(anyRequest, authenticated)
  309. }
  310. formLogin { }
  311. oneTimeTokenLogin {
  312. showDefaultSubmitPage = false
  313. }
  314. }
  315. return http.build()
  316. }
  317. }
  318. @Controller
  319. class MyController {
  320. @GetMapping("/my-ott-submit")
  321. fun ottSubmitPage(): String {
  322. return "my-ott-submit"
  323. }
  324. }
  325. @Component
  326. class MagicLinkGeneratedOneTimeTokenSuccessHandler : GeneratedOneTimeTokenHandler {
  327. // ...
  328. }
  329. ----
  330. ======
  331. [[customize-generate-consume-token]]
  332. == Customize How to Generate and Consume One-Time Tokens
  333. The interface that define the common operations for generating and consuming one-time tokens is the javadoc:org.springframework.security.authentication.ott.OneTimeTokenService[].
  334. Spring Security uses the javadoc:org.springframework.security.authentication.ott.InMemoryOneTimeTokenService[] as the default implementation of that interface, if none is provided.
  335. For production environments consider using javadoc:org.springframework.security.authentication.ott.JdbcOneTimeTokenService[].
  336. Some of the most common reasons to customize the `OneTimeTokenService` are, but not limited to:
  337. - Changing the one-time token expire time
  338. - Storing more information from the generate token request
  339. - Changing how the token value is created
  340. - Additional validation when consuming a one-time token
  341. There are two options to customize the `OneTimeTokenService`.
  342. One option is to provide it as a bean, so it can be automatically be picked-up by the `oneTimeTokenLogin()` DSL:
  343. .Passing the OneTimeTokenService as a Bean
  344. [tabs]
  345. ======
  346. Java::
  347. +
  348. [source,java,role="primary"]
  349. ----
  350. @Configuration
  351. @EnableWebSecurity
  352. public class SecurityConfig {
  353. @Bean
  354. public SecurityFilterChain filterChain(HttpSecurity http) {
  355. http
  356. // ...
  357. .formLogin(Customizer.withDefaults())
  358. .oneTimeTokenLogin(Customizer.withDefaults());
  359. return http.build();
  360. }
  361. @Bean
  362. public OneTimeTokenService oneTimeTokenService() {
  363. return new MyCustomOneTimeTokenService();
  364. }
  365. }
  366. @Component
  367. public class MagicLinkGeneratedOneTimeTokenHandler implements GeneratedOneTimeTokenSuccessHandler {
  368. // ...
  369. }
  370. ----
  371. Kotlin::
  372. +
  373. [source,kotlin,role="secondary"]
  374. ----
  375. @Configuration
  376. @EnableWebSecurity
  377. class SecurityConfig {
  378. @Bean
  379. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  380. http {
  381. //...
  382. formLogin { }
  383. oneTimeTokenLogin { }
  384. }
  385. return http.build()
  386. }
  387. @Bean
  388. open fun oneTimeTokenService(): OneTimeTokenService {
  389. return MyCustomOneTimeTokenService()
  390. }
  391. }
  392. @Component
  393. class MagicLinkGeneratedOneTimeTokenSuccessHandler : GeneratedOneTimeTokenHandler {
  394. // ...
  395. }
  396. ----
  397. ======
  398. The second option is to pass the `OneTimeTokenService` instance to the DSL, which is useful if there are multiple `SecurityFilterChain` and a different `OneTimeTokenService` is needed for each of them.
  399. .Passing the OneTimeTokenService using the DSL
  400. [tabs]
  401. ======
  402. Java::
  403. +
  404. [source,java,role="primary"]
  405. ----
  406. @Configuration
  407. @EnableWebSecurity
  408. public class SecurityConfig {
  409. @Bean
  410. public SecurityFilterChain filterChain(HttpSecurity http) {
  411. http
  412. // ...
  413. .formLogin(Customizer.withDefaults())
  414. .oneTimeTokenLogin((ott) -> ott
  415. .oneTimeTokenService(new MyCustomOneTimeTokenService())
  416. );
  417. return http.build();
  418. }
  419. }
  420. @Component
  421. public class MagicLinkGeneratedOneTimeTokenHandler implements GeneratedOneTimeTokenSuccessHandler {
  422. // ...
  423. }
  424. ----
  425. Kotlin::
  426. +
  427. [source,kotlin,role="secondary"]
  428. ----
  429. @Configuration
  430. @EnableWebSecurity
  431. class SecurityConfig {
  432. @Bean
  433. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  434. http {
  435. //...
  436. formLogin { }
  437. oneTimeTokenLogin {
  438. oneTimeTokenService = MyCustomOneTimeTokenService()
  439. }
  440. }
  441. return http.build()
  442. }
  443. }
  444. @Component
  445. class MagicLinkGeneratedOneTimeTokenSuccessHandler : GeneratedOneTimeTokenHandler {
  446. // ...
  447. }
  448. ----
  449. ======