Officially listed || SAS 0.2.0 Getting Started Tutorial

background

  • Spring Authorization Server (hereinafter referred to as SAS ) is the latest authorization server project developed by the Spring team that adapts to the OAuth protocol, aiming to replace the original Spring Security OAuth Server.
  • After half a year of development and incubation, version 0.2.0 has been released, which supports OAuth protocols such as authorization code, client, refresh, and logout.
  • At present, the SAS project has been migrated to the official warehouse for maintenance and has become an official sub-project of the government.
  • At the beginning of the year, the author "New Year Out of the Box | Spring Authorization Server, a new authorization server to get started
    》The article is no longer suitable for the current version, so the feature integrates the hand-on article.
  • environment of this article is based on Spring Boot 2.5.3 && SAS 0.2.0

Get started

1. Core dependencies

  • SAS and Security are needed here, pay attention to the notes

<!-- 注意groupId 正式仓库没有 experimental ,特别注意不然下载不到jar-->
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-oauth2-authorization-server</artifactId>
  <version>0.2.0</version>
</dependency>

<!--提供 form 认证-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. Configure security authentication

  • Define the user source and form authentication information
@EnableWebSecurity
public class DefaultSecurityConfig {
    @Bean
    UserDetailsService users() {
        UserDetails user = User.builder()
                .username("lengleng")
                .password("{noop}123456")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }
    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(authorizeRequests ->
                        authorizeRequests.anyRequest().authenticated()
                )
                .formLogin(withDefaults());
        return http.build();
    }
}

3. Configure SAS server

@Configuration
@EnableWebSecurity
public class AuthServerConfiguration {

  // security 挂载 SAS 【最重要的一步】
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.formLogin(Customizer.withDefaults()).build();
    }

  // 客户端来源
  @Bean
  public RegisteredClientRepository registeredClientRepository() {
      RegisteredClient client = RegisteredClient.withId("pig")
              .clientId("pig")
              .clientSecret("{noop}pig")
              .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
              .authorizationGrantTypes(authorizationGrantTypes -> {
                  authorizationGrantTypes.add(AuthorizationGrantType.AUTHORIZATION_CODE);
                  authorizationGrantTypes.add(AuthorizationGrantType.REFRESH_TOKEN);
              })
              .redirectUri("https://pig4cloud.com")
              .build();
      return new InMemoryRegisteredClientRepository(client);
  }

  // 以下两个bean 定义 生成jwt 的配置,可以直接参考文末源码介绍,这里就不在截图
    @Bean
    @SneakyThrows
    public JWKSource<SecurityContext> jwkSource() {
    ....
  }

  @Bean
  public static JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
   ...
  }
}

Test run

Through the above configuration, the SAS server can be built and completed, and we will test in the authorization code mode

    1. When the browser visits the following link, it will be redirected to the login page
http://localhost:3000/oauth2/authorize?client_id=pig&client_secret=pig&response_type=code&redirect_uri=https://pig4cloud.com

    1. After entering the account password, it will automatically call back to the target page with the code

1629369635

    1. Use code to exchange token
 curl --location --request POST 'http://localhost:3000/oauth2/token' \
> --header 'Authorization: Basic cGlnOnBpZw==' \
> --header 'Content-Type: application/x-www-form-urlencoded' \
> --data-urlencode 'grant_type=authorization_code' \
> --data-urlencode 'code=dn0GmDB-4hAfg-Kc9luUkuqZn4keJF9ZkUTlmcSRnYn8uzfEV9Ih429MH-9O77TPEVqPxXAJLPgxq-znOpiI-28Sek305db8Rezd46ods95FrjCSMq_HAswCtAJV4Vrt' \
> --data-urlencode 'redirect_uri=https://pig4cloud.com'
{"access_token":"eyJraWQiOiI2YmU4YzhlYi0wNDA2LTQxZGMtOGE2ZS0xOWZmNThlYzY4MTIiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJsZW5nbGVuZyIsImF1ZCI6InBpZyIsIm5iZiI6MTYyOTM2OTcwMSwiZXhwIjoxNjI5MzcwMDAxLCJpYXQiOjE2MjkzNjk3MDF9.Vb_1kGTqRTejBN8aPRFZPs_3cAa7jFC7XPuG4pPptpTtVbso0iHE5ghuNfFAk3DO4vDBjokYSWwNBfj9RuiwI5ElWbbK71leE8BAGpQa35pKYoKgXybf92KWbNIxHI3BXuQww8iWtQI5_xgNUWVJ6sx0uI4f5hA_vGZEM0vHza0FZZWPAFt9X6j_R0tmu0JPnnnQ2sTQyFJUzQomqbF1OpZaJi3_HjnjX7g_Z-NdJi-1s9jItNtzaaYzkyXnhmKLQoEq-OVxOOL0C2hP_bAZ1dy39HDUHuosxtGPsw49wWuqZQTcMbr9YojbyUMkR7k30zAAByjUmkXzjaS4T-EIaA","refresh_token":"YlxCAnSyvtq1HcKqE3D3o-P_lT90wxdRQ6jfWbwQoKQaeFUZr51gQQQawSfpUUH4yf9kW51v7ENH2o4pDot7yIeN2tljVpKU6zuolj6gFKq0uDA6KkDDz54cDzfx1aw4","token_type":"Bearer","expires_in":"299"}
    1. Refresh token
curl --location --request POST 'http://localhost:3000/oauth2/token' \
> --header 'Authorization: Basic cGlnOnBpZw==' \
> --header 'Content-Type: application/x-www-form-urlencoded' \
> --data-urlencode 'grant_type=authorization_code' \
> --data-urlencode 'code=dn0GmDB-4hAfg-Kc9luUkuqZn4keJF9ZkUTlmcSRnYn8uzfEV9Ih429MH-9O77TPEVqPxXAJLPgxq-znOpiI-28Sek305db8Rezd46ods95FrjCSMq_HAswCtAJV4Vrt' \
> --data-urlencode 'redirect_uri=https://pig4cloud.com'
{"access_token":"eyJraWQiOiI2YmU4YzhlYi0wNDA2LTQxZGMtOGE2ZS0xOWZmNThlYzY4MTIiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJsZW5nbGVuZyIsImF1ZCI6InBpZyIsIm5iZiI6MTYyOTM2OTcwMSwiZXhwIjoxNjI5MzcwMDAxLCJpYXQiOjE2MjkzNjk3MDF9.Vb_1kGTqRTejBN8aPRFZPs_3cAa7jFC7XPuG4pPptpTtVbso0iHE5ghuNfFAk3DO4vDBjokYSWwNBfj9RuiwI5ElWbbK71leE8BAGpQa35pKYoKgXybf92KWbNIxHI3BXuQww8iWtQI5_xgNUWVJ6sx0uI4f5hA_vGZEM0vHza0FZZWPAFt9X6j_R0tmu0JPnnnQ2sTQyFJUzQomqbF1OpZaJi3_HjnjX7g_Z-NdJi-1s9jItNtzaaYzkyXnhmKLQoEq-OVxOOL0C2hP_bAZ1dy39HDUHuosxtGPsw49wWuqZQTcMbr9YojbyUMkR7k30zAAByjUmkXzjaS4T-EIaA","refresh_token":"YlxCAnSyvtq1HcKqE3D3o-P_lT90wxdRQ6jfWbwQoKQaeFUZr51gQQQawSfpUUH4yf9kW51v7ENH2o4pDot7yIeN2tljVpKU6zuolj6gFKq0uDA6KkDDz54cDzfx1aw4","token_type":"Bearer","expires_in":"299"}%     lengleng@MacBook-Pro  ~/Downloads/auth-server-demo   password ± 
 lengleng@MacBook-Pro  ~/Downloads/auth-server-demo   password ±  curl --location --request POST 'http://localhost:3000/oauth2/token' \
> --header 'Authorization: Basic cGlnOnBpZw==' \
> --header 'Content-Type: application/x-www-form-urlencoded' \
> --data-urlencode 'grant_type=refresh_token' \
> --data-urlencode 'refresh_token=YlxCAnSyvtq1HcKqE3D3o-P_lT90wxdRQ6jfWbwQoKQaeFUZr51gQQQawSfpUUH4yf9kW51v7ENH2o4pDot7yIeN2tljVpKU6zuolj6gFKq0uDA6KkDDz54cDzfx1aw4' \
>
{"access_token":"eyJraWQiOiI2YmU4YzhlYi0wNDA2LTQxZGMtOGE2ZS0xOWZmNThlYzY4MTIiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJsZW5nbGVuZyIsImF1ZCI6InBpZyIsIm5iZiI6MTYyOTM2OTc2OSwiZXhwIjoxNjI5MzcwMDY5LCJpYXQiOjE2MjkzNjk3Njl9.dj_ktchQnTKRXGSQK7EZ3FAdz8StPOo27rURdCI8FN6jM3RFRD0s67v4LB1SRexl5KKHPuH6yYHhlr_u0um8ZpeQIrkumA2COukJAzy5O3SLsBYvLqipz-Ea9h9RZvC7EQZG-AbVJ378X214WxdsOYj1UPTv4Iegy4QsgERJSijINrCQZc0msHqSWIc_p61o2KIc8qaekrkZgY_JqCOz8K7x6drKvJ5gyWc9CyzeOrob5WrJfQGqqhjwjTl76g-9YyZ5Q97LX5lKRh8HOU6AUgKCyd4Jdol6PR6CkYd3gd4kyd5Ra7c3GbhzGUaxDrez79NDPx0aRAB9GA9mSohtsw","refresh_token":"YlxCAnSyvtq1HcKqE3D3o-P_lT90wxdRQ6jfWbwQoKQaeFUZr51gQQQawSfpUUH4yf9kW51v7ENH2o4pDot7yIeN2tljVpKU6zuolj6gFKq0uDA6KkDDz54cDzfx1aw4","token_type":"Bearer","expires_in":"299"}%

Revoke token

  • Through access_token
curl --location --request POST 'http://localhost:3000/oauth2/revoke' \
--header 'Authorization: Basic cGlnOnBpZw==' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'token=eyJraWQiOiI0NmM3Zjk0OS01NmZmLTRlMjgtYmI4Zi0wNjZjYWU4ODllNDkiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJsZW5nbGVuZyIsImF1ZCI6InBpZyIsIm5iZiI6MTYyOTM0MzM4NiwiZXhwIjoxNjI5MzQzNjg2LCJpYXQiOjE2MjkzNDMzODZ9.avRZ9NuybP8bqenEstvDq3SAKuSI6Y3ihh2PqeiQvwkUAWBPY6N9JCaxJllKhrcS6OgL76I38Yvt0B1ICMFistqemWl1rxQUB2aXpZuTwnPjxtxV6deDxyr--Y1w7I9jVpT5jnaqOXDIZ6dhIlUCfqBPT9a4DmwuEsz5H60KUO-NbMM66DPDxvTgauuylhrjiPQgaDyaxFHbtdw6qq_pgFI023fkIASodauCFiUcl64HKV3or9B3OkXW0EgnA553ofTbgz0hlROMfee15wuzOAXTUkhlUOjjosuEslimT9vFM9wtRza4o864Gi_j_zIhIoSSmRfUScXTgt9aZT1xlQ' \
--data-urlencode 'token_type_hint=access_token'
  • Pass refresh_token
curl --location --request POST 'http://localhost:3000/oauth2/revoke' \
--header 'Authorization: Basic cGlnOnBpZw==' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'token=ku4R4n7YD1f584KXj4k_3GP9o-HbdY-PDIIh-twPVJTmvHa5mLIoifaNhbBvFNBbse6_wAMcRoOWuVs9qeBWpxQ5zIFrF1A4g1Q7LhVAfH1vo9Uc7WL3SP3u82j0XU5x' \
--data-urlencode 'token_type_hint=refresh_token'

Next preview

SAS is an implementation of OAuth 2.1 protocol and does not support password mode. So how to extend the implementation? In the next article, I will share the extended implementation of the password mode, welcome to pay attention.

The source code of this article: https://github.com/lltx/auth-server-demo


冷冷
300 声望87 粉丝