添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
<




    
dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
spring:
  security:
    oauth2:
      client:
        registration:
          my-client:
            provider: my-auth
            client-id: client-id
            client-secret: client-secret
            authorization-grant-type: client_credentials
            scope: all
        provider:
          my-auth:
            token-uri: http://localhost/oauth/token            
@Configuration
public class ClientConfig {
	@Bean
	public OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clientRegistration,
                       OAuth2AuthorizedClientService authorizedClientService) {
		OAuth2AuthorizedClientProvider authorizedClientProvider =
                OAuth2AuthorizedClientProviderBuilder.builder()
                        .clientCredentials()
                        .build();
        AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager =
                new AuthorizedClientServiceOAuth2AuthorizedClientManager(
                        clientRegistration, authorizedClientService);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
        return authorizedClientManager;
```java

获取TOKEN

@Autowired
OAuth2AuthorizedClientManager authorizedClientManager;
public String getAccessToken() {
    OAuth2AuthorizeRequest request = OAuth2AuthorizeRequest
            .withClientRegistrationId("my-client")
            .principal("my client")
            .build();
    return Optional.ofNullable(oAuth2AuthorizedClientManager)
            .map(clientManager -> clientManager.authorize(request))
            .map(OAuth2AuthorizedClient::getAccessToken)
            .map(AbstractOAuth2Token::getTokenValue)
            .orElseThrow(() -> new RuntimeException("令牌获取失败"));
  • 授权管理器
    org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager
public OAuth2AuthorizedClient authorize(OAuth2AuthorizeRequest authorizeRequest) {
	...
	contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
	...
	OAuth2AuthorizationContext authorizationContext = buildAuthorizationContext(authorizeRequest, principal,
		contextBuilder);
	try {
		authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
  • 客户端凭据授权供应者
    org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider
// 客户端凭据授权模式的访问令牌客户端
private OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient = new DefaultClientCredentialsTokenResponseClient();
// 客户端授权
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
	Assert.notNull(context, "context cannot be null");
	ClientRegistration clientRegistration = context.getClientRegistration();
	if (!AuthorizationGrantType.CLIENT_CREDENTIALS.equals(clientRegistration.getAuthorizationGrantType())) {
		return null;
	OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
	if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
		// 客户端已经授权并且没有过期,则无需重复授权
		return null;
	// 请求访问令牌
	OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
			clientRegistration);
	OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, clientCredentialsGrantRequest);
	return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
			tokenResponse.getAccessToken());
// 请求访问令牌
private OAuth2AccessTokenResponse getTokenResponse(ClientRegistration clientRegistration,
		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest) {
	try {
		return this.accessTokenResponseClient.getTokenResponse(clientCredentialsGrantRequest);
	catch (OAuth2AuthorizationException ex) {
		throw new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex);
  • 客户端凭据模式的令牌客户端
    org.springframework.security.oauth2.client.endpoint.DefaultClientCredentialsTokenResponseClient
// 请求转换器
private Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>> requestEntityConverter = new OAuth2ClientCredentialsGrantRequestEntityConverter();
// 获取令牌
public OAuth2AccessTokenResponse getTokenResponse(
		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest) {
	Assert.notNull(clientCredentialsGrantRequest, "clientCredentialsGrantRequest cannot be null");
	RequestEntity<?> request = this.requestEntityConverter.convert(clientCredentialsGrantRequest);
	ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
	OAuth2AccessTokenResponse tokenResponse = response.getBody();
	if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) {
		// 如果访问令牌不包含scopes,则取客户端注册信息中的scope
		tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse)
				.scopes(clientCredentialsGrantRequest.getClientRegistration().getScopes())
				.build();
	return tokenResponse;
  • 客户端证书授权请求实体转换器
    org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequestEntityConverter
public RequestEntity<?> convert(T authorizationGrantRequest) {
	// 将客户端ID和密码以BASIC认证模式装入HEADER
	HttpHeaders headers = getHeadersConverter().convert(authorizationGrantRequest);
	// scope和grant_type参数
	MultiValueMap<String, String> parameters = getParametersConverter().convert(authorizationGrantRequest);
	URI uri = UriComponentsBuilder
			.fromUriString(authorizationGrantRequest.getClientRegistration().getProviderDetails().getTokenUri())
			.build().toUri();
	return new RequestEntity<>(parameters, headers, HttpMethod.POST, uri);
                                    oauth2-简化模式案例1.项目结构图2.搭建授权服务器(auth-server)3.搭建资源服务器(user-server)4.搭建第三方应用服务器(client-app)5.测试
1.项目结构图
2.搭建授权服务器(auth-server)
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.
                                    开头的配置项可以参考这个类OAuth2协议响应的标准参数字段可以参考这个类重定向到,并且会携带client_idscopestatenonce参数和会对回调地址(携带了code和state)进行处理,调用进行认证背后会进行连续token-uri请求,最后返回完全填充的缓存跳转登录前的请求由于类是final,不能继承,所以我们创建一个,然后把源码copy过来,主要修改accessTokenType为空的情况@Override。
                                    记一次异常解决:OAuth2获取token报错invalid stream header
在整合springcloud gateway、eureka、securityOAuth2的时候,采用授权码模式,用授权码去访问/oauth/token获取token时,遇到invalid stream header异常。
解决方法:
检查需要创建的OAuth2的几张表:oauth_access_tokenoauth_approvals、oauth_client_details、oauth_client_tokenoauth_code、oauth_refresh_token
这几张表的字段类型一定要设
使用 Spring security oauth2 client 实现授权码模式,可以不用手动拼接url请求code和token等信息,用户登录成功之后可以在SuccessHandler中获取当前用户的信息。如果还想获取用户信息以外的授权资源,必须要有AccessToken,要怎么获取呢?先看下如何获取用户信息
<dependency>
    <groupId&gt...
  1.授权码模式(authorization code) 
  2.简化模式(implicit) 
  3.密码模式(resource owner password credentials) 
  4.客户端模式client credentialsClientCredentials客户端模式: 
Client使用自己的 client证书(如 clien
                                    在之前我们已经对接过了GitHub、Gitee客户端,使用OAuth2 Client能够快速便捷的集成第三方登录,集成第三方登录一方面降低了企业的获客成本,同时为用户提供更为便捷的登录体验。但是随着企业的发展壮大,越来越有必要搭建自己的OAuth2服务器。OAuth2不仅包括前面的OAuth客户端,还包括了授权服务器,在这里我们要通过最小化配置搭建自己的授权服务器。授权服务器主要提供OAuth Client注册、用户认证、token分发、token验证、token刷新等功能。......
                                    oauth2获取access_token的几种方式:
简化模式(implicit):在redirect_url中传递access_token,oauth客户端运行在浏览器中。
密码模式(password):将用户名和密码传过去,直接获取access_token客户端模式client credentials):用户向客户端注册,然后客户端以自己的名义向“服务端”获取资源。
授权码模式(aut...
获取access_token请求(/oauth/token)
	请求所需参数:client_id、client_secret、grant_type、username、password
<span style="color:#000000"><code><spa
  在《授权服务器是如何实现授权的呢?》中,我们可以了解到服务端实现授权的流程,同时知道,当授权端点AuthorizationEndpoint生成授权码时,就会重定向到客户端的请求地址,这个时候,客户端就会拿着授权码再来授权服务器换取对应的Token,这篇内容,我们就详细分析如何使用授权码code换取Token的。在前面文章中,我们可以了解到客户端是通过“/oauth/token”来换取token的,该接口对应TokenEndpoint类的postAccessToken()方法,我们这篇文章就围绕
                                    使用背景 :公司有个开发平台,若要访问开发平台,必须先要获取授权访问令牌(也就是下面说的:access_token)。公司的授权系统是用spring oauth2.0实现的,今天就不讲这个项目,网上比较多。今天主要是讲下网络的比较少会用到的,spring 有个OAuth2.0 Client 组件会去实现获取access_token,然后spring 官网上关于这个组件的文档一点都不完善,只能自己研