Spring Authorization Server 全新授权服务器整合使用

Wesley13
• 阅读 1174

前言

  • Spring Authorization Server 是 Spring 团队最新开发适配 OAuth 协议的授权服务器项目,旨在替代原有的 Spring Security OAuth

  • 经过半年的开发和孵化,目前已经发布了 0.1.0 版本,初步支持授权码、客户端、刷新、注销等 OAuth 协议

  • 本文环境基于 Spring Boot 2.4.2 && authorization-server 0.1.0

Server 搭建

1. maven 依赖

<!--oauth2 server-->
<dependency>
  <groupId>org.springframework.security.experimental</groupId>
  <artifactId>spring-security-oauth2-authorization-server</artifactId>
  <version>0.1.0</version>
</dependency>
<!--security dependency-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. 初始化配置

  • 由于官方还未提供对应的 Spring Boot Starter 自动化配置,需要自己配置相关的 @Bean

  • 本配置基于 Spring Boot 2.4.2 请知悉

    @Configuration @EnableWebSecurity @Import(OAuth2AuthorizationServerConfiguration.class) public class AuthServerConfiguration {

    //  定义 spring security 拦击链规则
    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(authorizeRequests ->
                        authorizeRequests.anyRequest().authenticated()
                )
                .formLogin(withDefaults());
        return http.build();
    }
    

    // 创建默认登录用户 lengleng / 123456 @Bean public UserDetailsService userDetailsService() { UserDetails userDetails = User.builder() .username("lengleng") .password("{noop}123456") .authorities("ROLE_USER") .build(); return new InMemoryUserDetailsManager(userDetails); } // 创建默认的bean 登录客户端,基于 授权码、 刷新令牌的能力 @Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient client = RegisteredClient.withId("pig") .clientId("pig") .clientSecret("pig") .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) .authorizationGrantTypes(authorizationGrantTypes -> { authorizationGrantTypes.add(AuthorizationGrantType.AUTHORIZATION_CODE); authorizationGrantTypes.add(AuthorizationGrantType.REFRESH_TOKEN); }) .redirectUri("https://pig4cloud.com") .build(); return new InMemoryRegisteredClientRepository(client); } // 指定token 生成的加解密密钥 @Bean @SneakyThrows public JWKSource jwkSource() { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // @formatter:off RSAKey rsaKey= new RSAKey.Builder(publicKey) .privateKey(privateKey) .keyID(UUID.randomUUID().toString()) .build(); JWKSet jwkSet = new JWKSet(rsaKey); return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet); } }

测试

授权码认证

curl --location --request GET 'http://localhost:3000/oauth2/authorize?client_id=pig&client_secret=pig&response_type=code&redirect_uri=https://pig4cloud.com'

获取令牌

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={code}' \
--data-urlencode 'redirect_uri=https://pig4cloud.com'

刷新令牌

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={refresh_token}' \

撤销令牌

  • 通过 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={access_token}'
    --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={refresh_token}'
    --data-urlencode 'token_type_hint=refresh_token'

内容扩展 | Token 个性化

  • RegisteredClient 支持个性化 token 设置的入参

    RegisteredClient..tokenSettings()

  • 默认配置如下, 包括令牌有效期,刷新令牌控制等

    protected static Map<String, Object> defaultSettings() {
        Map<String, Object> settings = new HashMap<>();
        settings.put(ACCESS_TOKEN_TIME_TO_LIVE, Duration.ofMinutes(5));
        settings.put(REUSE_REFRESH_TOKENS, true);
        settings.put(REFRESH_TOKEN_TIME_TO_LIVE, Duration.ofMinutes(60));
        return settings;
    }
    

总结

>>> 源码 https://gitee.com/log4j/pig,欢迎署名转载 <<<

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Spring Security 实战干货:OAuth2第三方授权初体验
1\.前言现在很多项目都有第三方登录或者第三方授权的需求,而最成熟的方案就是OAuth2.0授权协议。SpringSecurity也整合了OAuth2.0,在目前最新的SpringSecurity5中整合了OAuth2.0的客户端,我们可以很方便的使用SpringSecurityOAuth2来实现相关的需求。接下来跟着胖哥
Stella981 Stella981
2年前
Kerberos无约束委派的攻击和防御
 0x00前言简介当ActiveDirectory首次与Windows2000Server一起发布时,Microsoft就提供了一种简单的机制来支持用户通过Kerberos对Web服务器进行身份验证并需要授权用户更新后端数据库服务器上的记录的方案。这通常被称为Kerberosdoublehopissue(双跃点问题),
Stella981 Stella981
2年前
CAS 实现站内单点登录及实现第三方 OAuth、OpenId 登录(四)
一、OAuth配置1.配置OAuth提供商<bean id"weibo" class"com.buession.oauth.provider.impl.WeiboProvider"    <property name"key" value"the_key_for_
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Android蓝牙连接汽车OBD设备
//设备连接public class BluetoothConnect implements Runnable {    private static final UUID CONNECT_UUID  UUID.fromString("0000110100001000800000805F9B34FB");
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这