getting-started.adoc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. [[oauth2AuthorizationServer-getting-started]]
  2. = Getting Started
  3. If you are just getting started with Spring Security Authorization Server, the following sections walk you through creating your first application.
  4. [[oauth2AuthorizationServer-system-requirements]]
  5. == System Requirements
  6. Spring Security Authorization Server requires a Java 17 or higher Runtime Environment.
  7. [[oauth2AuthorizationServer-installing-spring-security-authorization-server]]
  8. == Installing Spring Security Authorization Server
  9. The easiest way to begin using Spring Security Authorization Server is by creating a https://spring.io/projects/spring-boot[Spring Boot]-based application.
  10. You can use https://start.spring.io[start.spring.io] to generate a basic project or use the https://github.com/spring-projects/spring-authorization-server/tree/main/samples/default-authorizationserver[default authorization server sample] as a guide.
  11. Then add Spring Boot's starter for Spring Security Authorization Server as a dependency:
  12. [tabs]
  13. ======
  14. Maven::
  15. +
  16. [[oauth2AuthorizationServer-spring-boot-maven-dependency]]
  17. [source,xml,role="primary",subs="attributes,verbatim"]
  18. ----
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
  22. </dependency>
  23. ----
  24. Gradle::
  25. +
  26. [[oauth2AuthorizationServer-spring-boot-gradle-dependency]]
  27. [source,gradle,role="secondary",subs="attributes,verbatim"]
  28. ----
  29. implementation "org.springframework.boot:spring-boot-starter-oauth2-authorization-server"
  30. ----
  31. ======
  32. TIP: See https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started.html#getting-started.installing[Installing Spring Boot] for more information on using Spring Boot with Maven or Gradle.
  33. Alternatively, you can add Spring Security Authorization Server without Spring Boot using the following example:
  34. [tabs]
  35. ======
  36. Maven::
  37. +
  38. [[oauth2AuthorizationServer-maven-dependency]]
  39. [source,xml,role="primary",subs="attributes,verbatim"]
  40. ----
  41. <dependency>
  42. <groupId>org.springframework.security</groupId>
  43. <artifactId>spring-security-oauth2-authorization-server</artifactId>
  44. <version>{spring-security-version}</version>
  45. </dependency>
  46. ----
  47. Gradle::
  48. +
  49. [[oauth2AuthorizationServer-gradle-dependency]]
  50. [source,gradle,role="secondary",subs="attributes,verbatim"]
  51. ----
  52. implementation "org.springframework.security:spring-security-oauth2-authorization-server:{spring-security-version}"
  53. ----
  54. ======
  55. [[oauth2AuthorizationServer-developing-your-first-application]]
  56. == Developing Your First Application
  57. To get started, you need the minimum required components defined as a `@Bean`. When using the `spring-boot-starter-oauth2-authorization-server` dependency, define the following properties and Spring Boot will provide the necessary `@Bean` definitions for you:
  58. [[oauth2AuthorizationServer-application-yml]]
  59. .application.yml
  60. [source,yaml]
  61. ----
  62. server:
  63. port: 9000
  64. logging:
  65. level:
  66. org.springframework.security: trace
  67. spring:
  68. security:
  69. user:
  70. name: user
  71. password: password
  72. oauth2:
  73. authorizationserver:
  74. client:
  75. oidc-client:
  76. registration:
  77. client-id: "oidc-client"
  78. client-secret: "{noop}secret"
  79. client-authentication-methods:
  80. - "client_secret_basic"
  81. authorization-grant-types:
  82. - "authorization_code"
  83. - "refresh_token"
  84. redirect-uris:
  85. - "http://127.0.0.1:8080/login/oauth2/code/oidc-client"
  86. post-logout-redirect-uris:
  87. - "http://127.0.0.1:8080/"
  88. scopes:
  89. - "openid"
  90. - "profile"
  91. require-authorization-consent: true
  92. ----
  93. TIP: Beyond the Getting Started experience, most users will want to customize the default configuration. The xref:servlet/oauth2/authorization-server/getting-started.adoc#oauth2AuthorizationServer-defining-required-components[next section] demonstrates providing all of the necessary beans yourself.
  94. [[oauth2AuthorizationServer-defining-required-components]]
  95. == Defining Required Components
  96. If you want to customize the default configuration (regardless of whether you're using Spring Boot), you can define the minimum required components as a `@Bean` in a Spring `@Configuration`.
  97. These components can be defined as follows:
  98. [[oauth2AuthorizationServer-sample-gettingstarted]]
  99. .SecurityConfig.java
  100. [source,java]
  101. ----
  102. @Configuration
  103. @EnableWebSecurity
  104. public class SecurityConfig {
  105. @Bean // <1>
  106. @Order(1)
  107. public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
  108. throws Exception {
  109. OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
  110. OAuth2AuthorizationServerConfigurer.authorizationServer();
  111. // @formatter:off
  112. http
  113. .securityMatcher(authorizationServerConfigurer.getEndpointsMatcher())
  114. .with(authorizationServerConfigurer, (authorizationServer) ->
  115. authorizationServer
  116. .oidc(Customizer.withDefaults()) // Enable OpenID Connect 1.0
  117. )
  118. .authorizeHttpRequests((authorize) ->
  119. authorize
  120. .anyRequest().authenticated()
  121. )
  122. // Redirect to the login page when not authenticated from the
  123. // authorization endpoint
  124. .exceptionHandling((exceptions) -> exceptions
  125. .defaultAuthenticationEntryPointFor(
  126. new LoginUrlAuthenticationEntryPoint("/login"),
  127. new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
  128. )
  129. );
  130. // @formatter:on
  131. return http.build();
  132. }
  133. @Bean // <2>
  134. @Order(2)
  135. public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
  136. throws Exception {
  137. // @formatter:off
  138. http
  139. .authorizeHttpRequests((authorize) -> authorize
  140. .anyRequest().authenticated()
  141. )
  142. // Form login handles the redirect to the login page from the
  143. // authorization server filter chain
  144. .formLogin(Customizer.withDefaults());
  145. // @formatter:on
  146. return http.build();
  147. }
  148. @Bean // <3>
  149. public UserDetailsService userDetailsService() {
  150. // @formatter:off
  151. UserDetails userDetails = User.withDefaultPasswordEncoder()
  152. .username("user")
  153. .password("password")
  154. .roles("USER")
  155. .build();
  156. // @formatter:on
  157. return new InMemoryUserDetailsManager(userDetails);
  158. }
  159. @Bean // <4>
  160. public RegisteredClientRepository registeredClientRepository() {
  161. // @formatter:off
  162. RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString())
  163. .clientId("oidc-client")
  164. .clientSecret("{noop}secret")
  165. .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
  166. .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
  167. .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
  168. .redirectUri("http://127.0.0.1:8080/login/oauth2/code/oidc-client")
  169. .postLogoutRedirectUri("http://127.0.0.1:8080/")
  170. .scope(OidcScopes.OPENID)
  171. .scope(OidcScopes.PROFILE)
  172. .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
  173. .build();
  174. // @formatter:on
  175. return new InMemoryRegisteredClientRepository(oidcClient);
  176. }
  177. @Bean // <5>
  178. public JWKSource<SecurityContext> jwkSource() {
  179. KeyPair keyPair = generateRsaKey();
  180. RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  181. RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
  182. // @formatter:off
  183. RSAKey rsaKey = new RSAKey.Builder(publicKey)
  184. .privateKey(privateKey)
  185. .keyID(UUID.randomUUID().toString())
  186. .build();
  187. // @formatter:on
  188. JWKSet jwkSet = new JWKSet(rsaKey);
  189. return new ImmutableJWKSet<>(jwkSet);
  190. }
  191. private static KeyPair generateRsaKey() { // <6>
  192. KeyPair keyPair;
  193. try {
  194. KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
  195. keyPairGenerator.initialize(2048);
  196. keyPair = keyPairGenerator.generateKeyPair();
  197. }
  198. catch (Exception ex) {
  199. throw new IllegalStateException(ex);
  200. }
  201. return keyPair;
  202. }
  203. @Bean // <7>
  204. public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
  205. return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
  206. }
  207. @Bean // <8>
  208. public AuthorizationServerSettings authorizationServerSettings() {
  209. return AuthorizationServerSettings.builder().build();
  210. }
  211. }
  212. ----
  213. This is a minimal configuration for getting started quickly. To understand what each component is used for, see the following descriptions:
  214. <1> A Spring Security filter chain for the xref:servlet/oauth2/authorization-server/protocol-endpoints.adoc[Protocol Endpoints].
  215. <2> A Spring Security filter chain for xref:servlet/authentication/index.adoc#servlet-authentication[authentication].
  216. <3> An instance of {security-api-url}/org/springframework/security/core/userdetails/UserDetailsService.html[`UserDetailsService`] for retrieving users to authenticate.
  217. <4> An instance of xref:servlet/oauth2/authorization-server/core-model-components.adoc#oauth2AuthorizationServer-registered-client-repository[`RegisteredClientRepository`] for managing clients.
  218. <5> An instance of `com.nimbusds.jose.jwk.source.JWKSource` for signing access tokens.
  219. <6> An instance of `java.security.KeyPair` with keys generated on startup used to create the `JWKSource` above.
  220. <7> An instance of {security-api-url}/org/springframework/security/oauth2/jwt/JwtDecoder.html[`JwtDecoder`] for decoding signed access tokens.
  221. <8> An instance of xref:servlet/oauth2/authorization-server/configuration-model.adoc#oauth2AuthorizationServer-configuring-authorization-server-settings[`AuthorizationServerSettings`] to configure Spring Security Authorization Server.