SpringCloud2.0整合OAuth2.0

本文档详细介绍了如何在SpringCloud2.0中整合OAuth2.0授权服务,包括OAuth授权服务器配置、Spring-Security安全设置、资源服务器配置、使用Redis存储token并解决最新版RedisTokenStore的弃用问题,以及自定义客户端认证和配置文件的加密认证等步骤。
摘要由CSDN通过智能技术生成

以下是把配置文件放在Git仓库,SpringCloudConfig配置中心拉取,动态刷新

一.for pom.xml

<dependencies>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
       </dependency>
       <!--config-->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-config-client</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-config</artifactId>
       </dependency>
       <!--spring-cloud-bus-->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-bus-amqp</artifactId>
       </dependency>
       <!-- actuator监控 -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-actuator</artifactId>
       </dependency>
       <!-- hystrix容错 -->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
       </dependency>
       <!-- 加密标配 -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-security</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-oauth2</artifactId>
       </dependency>
       <!--添加  重试机制 的依赖
因网络的抖动等原因导致config-client在启动时候访问config-server没有访问成功从而报错,
希望config-client能重试几次,故重试机制
-->
       <dependency>
           <groupId>org.springframework.retry</groupId>
           <artifactId>spring-retry</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-aop</artifactId>
       </dependency>
       <!--nosql-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-redis</artifactId>
       </dependency>
       <dependency>
           <groupId>redis.clients</groupId>
           <artifactId>jedis</artifactId>
           <version>2.9.0</version>
       </dependency>
       <!--cache-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-cache</artifactId>
       </dependency>
   </dependencies>
   <build>
       <finalName>${project.artifactId}</finalName>
       <plugins>
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
               <version>1.5.13.RELEASE</version>
               <configuration>
                   <!-- 指定程序入口 -->
                   <mainClass>com.huajie.provider.auth.AuthApplication</mainClass>
               </configuration>
               <executions>
                   <execution>
                       <goals>
                           <goal>repackage</goal>
                       </goals>
                   </execution>
                   <!--<execution>-->
                   <!--<goals>-->
                   <!--<goal>build-info</goal>-->
                   <!--</goals>-->
                   <!--</execution>-->
               </executions>
           </plugin>
           <!-- 添加docker-maven插件 -->
           <plugin>
               <groupId>com.spotify</groupId>
               <artifactId>docker-maven-plugin</artifactId>
               <version>0.4.13</version>
               <configuration>
                   <imageName>${project.artifactId}:${project.version}</imageName>
                   <baseImage>java</baseImage>
                   <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
                   <!--覆盖已存在的标签 镜像-->
                   <forceTags>true</forceTags>
                   <resources>
                       <resource>
                           <targetPath>/</targetPath>
                           <directory>${project.build.directory}</directory>
                           <include>${project.build.finalName}.jar</include>
                       </resource>
                   </resources>
               </configuration>
           </plugin>
       </plugins>
   </build>

二 for java file (class)

1. OAuth 授权服务器配置

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private static final Logger log = LoggerFactory.getLogger(AuthorizationServerConfiguration.class);

    // 注入认证管理
    @Autowired
    AuthenticationManager authenticationManager;

    // 方案 一:采用redis缓存服务存储token
    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    // 方案二 使用内存存储token
    @Autowired
    private TokenStore tokenStore;


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        log.info("======================^_^ start client validation  ^_^========================");
        //自定义验证:实现 ClientDetailsService接口
        clients.withClientDetails(new BaseClientDetailService());

        //内存中 配置客户端,一个用于password认证一个用于client认证
//        clients.inMemory()
//            .withClient("client_1")
//            .resourceIds("order")
//            .authorizedGrantTypes("client_credentials", "refresh_token")
//            .scopes("select")
//            .authorities("oauth2")
//            .secret(finalSecret)
//            .and()
//            .withClient("client_2")
//            .resourceIds("order") // 资源id
//            .authorizedGrantTypes("password", "refresh_token")
//            .scopes("select")
//            .authorities("oauth2")
//            .secret(finalSecret)
//            .and()
//            .withClient("client_code")
//            .resourceIds(DEMO_RESOURCE_ID)  // 资源id
//            .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token",
//                    "password", "implicit")
//            .scopes("all")
//            //.authorities("oauth2")
//            .redirectUris("http://www.baidu.com")
//            .accessTokenValiditySeconds(1200)
//            .refreshTokenValiditySeconds(50000);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        log.info("======================^_^ start generate token ^_^========================");
        // 基于方案一,*******redis服务存储token*********
        // 样例keys如下:
//        1) "auth_to_access:227ccfa0102c5cbefcc06a8b99bc12fa"
//        2) "uname_to_access:client:admin"
//        3) "access_to_refresh:e711ab59-f49b-4400-a3eb-4af90df67395"
//        4) "client_id_to_access:client"
//        5) "refresh_to_access:c45d5a9e-f3e6-4170-9ae7-b8f57e67277f"
//        6) "refresh:c45d5a9e-f3e6-4170-9ae7-b8f57e67277f"
//        7) "refresh_auth:c45d5a9e-f3e6-4170-9ae7-b8f57e67277f"
//        8) "access:e711ab59-f49b-4400-a3eb-4af90df67395"
//        9) "auth:e711ab59-f49b-4400-a3eb-4af90df67395"
        endpoints
                .tokenStore(new MyRedisTokenStore(redisConnectionFactory))
                .authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, 
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud Security 为我们提供了 OAuth2 Client 和 OAuth2 Resource Server 的自动配置。我们可以通过在 Spring Boot 应用程序中添加以下依赖关系来使用它们: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-resource-server</artifactId> </dependency> ``` 这将添加 Spring Security 和 OAuth2 Client 和 OAuth2 Resource Server 的所有必需组件。 在配置文件中配置 OAuth2 客户端应用程序的详细信息,如下所示: ```yaml spring: security: oauth2: client: registration: github: client-id: *** client-secret: *** provider: github: authorization-uri: https://github.com/login/oauth/authorize token-uri: https://github.com/login/oauth/access_token user-info-uri: https://api.github.com/user user-name-attribute: login ``` 在这里,我们配置了一个名为“github”的 OAuth2 客户端应用程序,并提供了必要的详细信息,例如客户端 ID、客户端密钥和提供者详细信息。 我们可以使用 `@EnableOAuth2Sso` 注解启用单点登录(SSO)支持。如果我们要使用 OAuth2 作为资源服务器,则可以使用 `@EnableResourceServer` 注解来启用资源服务器支持。 我们可以在需要保护的端点上使用 `@EnableOAuth2Sso` 或 `@EnableResourceServer` 注解来保护它们。例如,以下是一个使用 `@EnableResourceServer` 注解保护端点的示例: ```java @RestController @EnableResourceServer public class UserController { @GetMapping("/user") public Principal user(Principal principal) { return principal; } } ``` 这里,我们使用 `@EnableResourceServer` 注解启用资源服务器支持,并在 `/user` 端点上保护它。在这里,我们使用 `Principal` 对象返回当前经过身份验证的用户信息。 以上是 Spring Cloud Security 集成 OAuth2 的基本介绍,你可以根据需要进一步了解和配置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值