Spring SAS 0.2.0 上手教程

Spring SAS 0.2.0 上手教程正式上市 || SAS 0.2.0 上手教程 背景 Spring Authorization Server (以下简称 SAS)是 Spring 团队最新开发适配 OAuth 协议的授权服务器项目,旨

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

Spring 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

Spring SAS 0.2.0 上手教程

    1. 输入账号密码后,会携带 code 自动回调至目标页面

1629369635

    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 协议的实现,不支持密码模式。 那么怎么扩展实现呢 ?下一篇文章我会分享扩展实现密码模式,欢迎关注。

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

今天的文章Spring SAS 0.2.0 上手教程分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/21038.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注