Oauth2.0基于Spring Authorization Server模块client_secret_basic或者post

介绍

处理oauth2.0请求授权client授权模式, 使用授权服务器对客户端进行身份验证时使用的身份验证方法 **

  • client_secret_basic
  • client_secret_post
  • client_secret_jwt
  • private_key_jwt
  • none
序号 授权服务器对客户端进行身份验证时使用的身份验证方法 说明
1 client_secret_basic ClientSecretBasicAuthenticationConverter
2 client_secret_post ClientSecretPostAuthenticationConverter

基于项目:Spring Authorization Server

1. maven项目依赖

spring-authorization-server v0.2.2

2.application.yml配置

spring:
  application:
    name: oauth2-authorization-server
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/oauth2?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
    password: li123456
    username: root

server:
  port: 9000
  servlet:
    context-path: /uc

logging:
  level:
    root: INFO
    org.springframework.web: INFO
    org.springframework.security: INFO
    org.springframework.security.oauth2: INFO
    com.lance.oauth2.server: debug

3.测试Sql脚本

CREATE TABLE `oauth2_registered_client`
(
    `id`                            varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci  NOT NULL,
    `client_id`                     varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci  NOT NULL,
    `client_id_issued_at`           timestamp                                                NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `client_secret`                 varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    `client_secret_expires_at`      timestamp NULL DEFAULT NULL,
    `client_name`                   varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci  NOT NULL,
    `client_authentication_methods` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    `authorization_grant_types`     varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    `redirect_uris`                 varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    `scopes`                        varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    `client_settings`               varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    `token_settings`                varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

4. AuthorizationServer配置

@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfig {

	@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(JdbcTemplate jdbcTemplate) {
		return new JdbcRegisteredClientRepository(jdbcTemplate);
	}

	@Bean
	public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
		return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
	}

	@Bean
	public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
		return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository);
	}

	@Bean
	public JWKSource jwkSource() {
		RSAKey rsaKey = Jwks.generateRsa();
		JWKSet jwkSet = new JWKSet(rsaKey);
		return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
	}

	@Bean
	public ProviderSettings providerSettings() {
		return ProviderSettings.builder().issuer("http://auth-server:9000").build();
	}
}

5.单元测试Test

@SpringBootTest
class RegisteredClientRepositoryTests {
	@Autowired
	private RegisteredClientRepository registeredClientRepository;

	@Test
	@Disabled
	void findByClientId() {
		String clientId = "8000000010";
		RegisteredClient client = registeredClientRepository.findByClientId(clientId);

		log.info("===>{}", JsonUtils.toJsonString(client));
	}

	@Test
	@Disabled
	void findById() {
		String id = "833cec50-fc11-4488-b29c-d3bb7fe7da98";
		RegisteredClient client = registeredClientRepository.findById(id);

		log.info("===>{}", JsonUtils.toJsonString(client));
	}

	@Test
	@Disabled
	void save() {
		String id = UUID.randomUUID().toString().replaceAll("-", "");

		TokenSettings tokenSettings = TokenSettings.builder()
				.reuseRefreshTokens(true)
				.refreshTokenTimeToLive(Duration.ofDays(7))
				.accessTokenTimeToLive(Duration.ofHours(8))
				.idTokenSignatureAlgorithm(SignatureAlgorithm.RS256)
				.reuseRefreshTokens(false)
				.build();

		RegisteredClient client = RegisteredClient.withId(id)
				.clientId("8000000013")
				.clientIdIssuedAt(Instant.now())
				.clientSecret("{noop}secret")
				.clientSecretExpiresAt(Instant.now().plus(Period.ofDays(20)))
				.clientName("Client credentials client_secret_basic有限公司")
				.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
				.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
				.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
				.scope("server")
				.tokenSettings(tokenSettings)
				.build();
		registeredClientRepository.save(client);

		log.info("===>{}", JsonUtils.toJsonString(client));
	}
}

6. 基于grant_type client_credentials授权模式测试数据

## 基于Post请求
curl --location --request POST 'http://127.0.0.1:9000/uc/oauth2/token?scope=server&grant_type=client_credentials&client_id=8000000012&client_secret=secret' \
--header 'Cookie: JSESSIONID=2E0679E3D163F37375BD7E6B80E73AFF'

## 基于Authorization Basic请求
curl --location --request POST 'http://127.0.0.1:9000/uc/oauth2/token?scope=server&grant_type=client_credentials' \
--header 'Authorization: Basic ODAwMDAwMDAxMzpzZWNyZXQ=' \
--header 'Cookie: JSESSIONID=2E0679E3D163F37375BD7E6B80E73AFF'

7.项目完整地址

Oauth2.0基于Spring Authorization Server模块client_secret_basic或者post Github 地址

Oauth2.0基于Spring Authorization Server模块client_secret_basic或者post Gitee 地址

你可能感兴趣的:(Oauth2.0,spring,boot,oauth2.0,grant,type,basic,post,authorization)