spring cloud搭建oauth2资源服务

依赖

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.5.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
    <java.version>11</java.version>
    <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties>
<dependencies>
    <!-- spring cloud oauth2 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <!-- spring cloud -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

配置

application.yml

security:
  oauth2:
    client:
      client-id: application-client-id
      client-secret: application-client-secret
      access-token-uri: http://authsite-host/oauth/token
    resource:
      id: application-resource-id
      tokenInfoUri: http://authsite-host/oauth/check_token
      userInfoUri: http://authsite-host/oauth/check_user
  • application-client-id、application-client-secret、application-resource-id修改为OAUTH2授权服务中注册的客户端、资源对应值
  • 注意: 资源服务也需要配置注册为客户端, 否则无法通过认证服务器获取TOKEN和用户信息

JAVA配置

创建JAVA配置: ResourceServerConfig.java

@Configuration
// 启用资源服务器配置
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    protected ResourceServerProperties resource;

    public ResourceServerConfig(ResourceServerProperties resource) {
        this.resource = resource;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(this.resource.getResourceId());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 自定义访问控制逻辑
        http.authorizeRequests().anyRequest().authenticated();
    }
}

猜你喜欢

转载自blog.csdn.net/zhoudingding/article/details/106372600