2
0

getting-started.adoc 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. [[servlet-hello]]
  2. = Hello Spring Security
  3. This section covers the minimum setup for how to use Spring Security with {spring-boot-reference-url}[Spring Boot] and then points you to next steps after that.
  4. [NOTE]
  5. ====
  6. The completed starter application can be found {gh-samples-url}/servlet/spring-boot/java/hello-security[in our samples repository].
  7. For your convenience, you can download a minimal Spring Boot + Spring Security application https://start.spring.io/starter.zip?type=maven-project&language=java&packaging=jar&jvmVersion=1.8&groupId=example&artifactId=hello-security&name=hello-security&description=Hello%20Security&packageName=example.hello-security&dependencies=web,security[prepared by Spring Initializr].
  8. ====
  9. [[servlet-hello-dependencies]]
  10. == Updating Dependencies
  11. You first need to add Spring Security to your application's classpath; two ways to do this are to xref:getting-spring-security.adoc#getting-maven-boot[use Maven] or xref:getting-spring-security.adoc#getting-gradle-boot[Gradle].
  12. [[servlet-hello-starting]]
  13. == Starting Hello Spring Security Boot
  14. With Spring Security <<servlet-hello-dependencies,on the classpath>>, you can now {spring-boot-reference-url}#using.running-your-application[run the Spring Boot application].
  15. The following snippet shows some of the output that indicates that Spring Security is enabled in your application:
  16. .Running Spring Boot Application
  17. ====
  18. .Maven
  19. [source,bash,role="primary"]
  20. ----
  21. $ ./mvnw spring-boot:run
  22. ...
  23. INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration :
  24. Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336
  25. ...
  26. ----
  27. .Gradle
  28. [source,bash,role="secondary"]
  29. ----
  30. $ ./gradlew :bootRun
  31. ...
  32. INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration :
  33. Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336
  34. ...
  35. ----
  36. .Jar
  37. [source,bash,role="secondary"]
  38. ----
  39. $ java -jar target/myapplication-0.0.1.jar
  40. ...
  41. INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration :
  42. Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336
  43. ...
  44. ----
  45. ====
  46. Now that you have it running, you might try hitting an endpoint to see what happens.
  47. If you hit an endpoint without credentials like so:
  48. .Querying a Secured Boot Application
  49. ====
  50. [source,bash]
  51. ----
  52. $ curl -i http://localhost:8080/some/path
  53. HTTP/1.1 401
  54. ...
  55. ----
  56. ====
  57. then Spring Security denies access with a `401 Unauthorized`.
  58. [TIP]
  59. If you provide the same URL in a browser, it will redirect to a default login page.
  60. And if you hit an endpoint with credentials (found in the console output) as follows:
  61. .Querying with Credentials
  62. ====
  63. [source,bash]
  64. ----
  65. $ curl -i -u user:8e557245-73e2-4286-969a-ff57fe326336 http://localhost:8080/some/path
  66. HTTP/1.1 404
  67. ...
  68. ----
  69. ====
  70. then Spring Boot will service the request, returning a `404 Not Found` in this case since `/some/path` doesn't exist.
  71. From here, you can:
  72. * Better understand <<hello-expectations,what Spring Boot enables in Spring Security by default>>
  73. * Read about <<security-use-cases,common use cases>> that Spring Security helps with
  74. * Start configuring xref:servlet/authentication/index.adoc[authentication]
  75. [[hello-expectations]]
  76. [[servlet-hello-auto-configuration]]
  77. == Runtime Expectations
  78. The default arrangement of Spring Boot and Spring Security affords the following behaviors at runtime:
  79. * Requires an authenticated user xref:servlet/authorization/authorize-http-requests.adoc[for any endpoint] (including Boot's `/error` endpoint)
  80. * xref:servlet/authentication/passwords/user-details-service.adoc[Registers a default user] with a generated password at startup (the password is logged to the console; in the preceding example, the password is `8e557245-73e2-4286-969a-ff57fe326336`)
  81. * Protects xref:servlet/authentication/passwords/password-encoder.adoc[password storage with BCrypt] as well as others
  82. * Provides form-based xref:servlet/authentication/passwords/form.adoc[login] and xref:servlet/authentication/logout.adoc[logout] flows
  83. * Authenticates xref:servlet/authentication/passwords/form.adoc[form-based login] as well as xref:servlet/authentication/passwords/basic.adoc[HTTP Basic]
  84. * Provides content negotiation; for web requests, redirects to the login page; for service requests, returns a `401 Unauthorized`
  85. * xref:servlet/exploits/csrf.adoc[Mitigates CSRF] attacks
  86. * xref:servlet/authentication/session-management.adoc#ns-session-fixation[Mitigates Session Fixation] attacks
  87. * Writes xref:servlet/exploits/headers.adoc#servlet-headers-hsts[Strict-Transport-Security] to https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security[ensure HTTPS]
  88. * Writes xref:servlet/exploits/headers.adoc#servlet-headers-content-type-options[X-Content-Type-Options] to mitigate https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#x-content-type-options[sniffing attacks]
  89. * Writes xref:servlet/exploits/headers.adoc#servlet-headers-cache-control[Cache Control headers] that protect authenticated resources
  90. * Writes xref:servlet/exploits/headers.adoc#servlet-headers-frame-options[X-Frame-Options] to mitigate https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#x-frame-options[Clickjacking]
  91. * Integrates with xref:servlet/integrations/servlet-api.adoc[``HttpServletRequest``'s authentication methods]
  92. * Publishes xref:servlet/authentication/events.adoc[authentication success and failure events]
  93. It can be helpful to understand how Spring Boot is coordinating with Spring Security to achieve this.
  94. Taking a look at {spring-boot-api-url}org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfiguration.html[Boot's security auto configuration], it does the following (simplified for illustration):
  95. .Spring Boot Security Auto Configuration
  96. ====
  97. [source,java]
  98. ----
  99. @EnableWebSecurity <1>
  100. @Configuration
  101. public class DefaultSecurityConfig {
  102. @Bean
  103. @ConditionalOnMissingBean(UserDetailsService.class)
  104. InMemoryUserDetailsManager inMemoryUserDetailsManager() { <2>
  105. String generatedPassword = // ...;
  106. return new InMemoryUserDetailsManager(User.withUsername("user")
  107. .password(generatedPassword).roles("ROLE_USER").build());
  108. }
  109. @Bean
  110. @ConditionalOnMissingBean(AuthenticationEventPublisher.class)
  111. DefaultAuthenticationEventPublisher defaultAuthenticationEventPublisher(ApplicationEventPublisher delegate) { <3>
  112. return new DefaultAuthenticationEventPublisher(delegate);
  113. }
  114. }
  115. ----
  116. ====
  117. 1. Adds the `@EnableWebSecurity` annotation. (Among other things, this publishes xref:servlet/architecture.adoc#servlet-securityfilterchain[Spring Security's default `Filter` chain] as a `@Bean`)
  118. 2. Publishes a xref:servlet/authentication/passwords/user-details-service.adoc[`UserDetailsService`] `@Bean` with a username of `user` and a randomly generated password that is logged to the console
  119. 3. Publishes an xref:servlet/authentication/events.adoc[`AuthenticationEventPublisher`] `@Bean` for publishing authentication events
  120. [NOTE]
  121. Spring Boot adds any `Filter` published as a `@Bean` to the application's filter chain.
  122. This means that using `@EnableWebSecurity` in conjunction with Spring Boot automatically registers Spring Security's filter chain for every request.
  123. [[security-use-cases]]
  124. == Security Use Cases
  125. There are a number of places that you may want to go from here.
  126. To figure out what's next for you and your application, consider these common use cases that Spring Security is built to address:
  127. * I am building a REST API, and I need to xref:servlet/oauth2/resource-server/jwt.adoc[authenticate a JWT] or xref:servlet/oauth2/resource-server/opaque-token.adoc[other bearer token]
  128. * I am building a Web Application, API Gateway, or BFF and
  129. ** I need to xref:servlet/oauth2/login/core.adoc[login using OAuth 2.0 or OIDC]
  130. ** I need to xref:servlet/saml2/login/index.adoc[login using SAML 2.0]
  131. ** I need to xref:servlet/authentication/cas.adoc[login using CAS]
  132. * I need to manage
  133. ** Users in xref:servlet/authentication/passwords/ldap.adoc[LDAP] or xref:servlet/authentication/passwords/ldap.adoc#_active_directory[Active Directory], with xref:servlet/integrations/data.adoc[Spring Data], or with xref:servlet/authentication/passwords/jdbc.adoc[JDBC]
  134. ** xref:servlet/authentication/passwords/storage.adoc[Passwords]
  135. In case none of those match what you are looking for, consider thinking about your application in the following order:
  136. 1. *Protocol*: First, consider the protocol your application will use to communicate.
  137. For servlet-based applications, Spring Security supports HTTP as well as xref:servlet/integrations/websocket.adoc[Websockets].
  138. 2. *Authentication*: Next, consider how users will xref:servlet/authentication/index.adoc[authenticate] and if that authentication will be stateful or stateless
  139. 3. *Authorization*: Then, consider how you will determine xref:servlet/authorization/index.adoc[what a user is authorized to do]
  140. 4. *Defense*: Finally, xref:servlet/exploits/csrf.adoc#csrf-considerations[integrate with Spring Security's default protections] and consider xref:servlet/exploits/headers.adoc[which additional protections you need]