关于spring:Spring-SAS-02-上手教程

81次阅读

共计 7277 个字符,预计需要花费 19 分钟才能阅读完成。

正式上市 || SAS 0.2.0 上手教程

背景

  • Spring Authorization Server(以下简称 SAS)是 Spring 团队最新开发适配 OAuth 协定的受权服务器我的项目,旨在代替原有的 Spring Security OAuth Server。
  • 通过半年的开发和孵化,目前曾经公布了 0.2.0 版本,已反对受权码、客户端、刷新、登记等 OAuth 协定。
  • 目前 SAS 我的项目曾经迁徙至官网正式仓库保护,成为官网的正式子项目。
  • 笔者年初《新年开箱 | Spring Authorization Server 全新的受权服务器上手
    》文章曾经不适配以后版本,所以特写整合上手文章。
  • 本文环境基于 Spring Boot 2.5.3 && SAS 0.2.0

开始上手

1. 外围依赖

  • 这里须要 SAS、Security, 留神看正文

<!-- 留神 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. 配置 security 平安认证

  • 定义用户起源及其 form 认证的信息
@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. 配置 SAS 服务器

@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) {...}
}

测试运行

通过以上配置即可搭建实现 SAS 服务端,咱们以受权码模式测试

    1. 浏览器拜访如下链接,会重定向至登录页
http://localhost:3000/oauth2/authorize?client_id=pig&client_secret=pig&response_type=code&redirect_uri=https://pig4cloud.com

    1. 输出账号密码后,会携带 code 主动回调至指标页面

    1. 应用 code 换 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. 刷新 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"}%

撤销令牌

  • 通过 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'
  • 通过 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'

下期预报

SAS 是 OAuth 2.1 协定的实现,不反对明码模式。那么怎么扩大实现呢?下一篇文章我会分享扩大实现明码模式,欢送关注。

本文源码: https://github.com/lltx/auth-…

正文完
 0