spring cloud搭建oauth2资源服务

依赖

pom.xml

<parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.2.5.RELEASEversion>
    <relativePath/> 
parent>
<properties>
    <java.version>11java.version>
    <spring-cloud.version>Hoxton.SR4spring-cloud.version>
properties>
<dependencies>
    
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-oauth2artifactId>
    dependency>
dependencies>
<dependencyManagement>
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-dependenciesartifactId>
            <version>${spring-cloud.version}version>
            <type>pomtype>
            <scope>importscope>
        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();
    }
}

你可能感兴趣的:(spring,cloud,开发总结)