配置web.xml

添加spring-cloud-starter-security,spring-security-oauth2-autoconfigure和spring-boot-starter-oauth2-client 3个依赖。

  1. <!-- Spring cloud starter: Security -->
  2. <!-- Include: web, actuator, security, zuul, etc. -->
  3. <dependency>
  4. <groupId>org.springframework.cloud</groupId>
  5. <artifactId>spring-cloud-starter-security</artifactId>
  6. </dependency>
  7. <!-- Spring Security OAuth2 Autoconfigure (optional in spring-cloud-security after 2.1) -->
  8. <dependency>
  9. <groupId>org.springframework.security.oauth.boot</groupId>
  10. <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  11. </dependency>
  12. <!-- Spring Security OAuth2 Client (optional in spring-cloud-security after 2.1) -->
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-oauth2-client</artifactId>
  16. </dependency>

此外,它还是一个Eureka Client和Config Client,如何配置Eureka Client和Config Client请看前面章节。

配置Application

添加@EnableOAuth2Client注解,声明为OAuth2 Client。

  1. @SpringBootApplication
  2. @EnableOAuth2Client
  3. public class AppSqlApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(AppSqlApplication.class, args);
  6. }
  7. }

SSO单点登录的配置

(1)配置Configer

该服务作为一个OAuth2 Client,可以使用上一节的OAuth2 Server来登录。这其实就是SSO单点登录的例子。

  1. package com.mycloud.demo.config;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  8. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  9. import org.springframework.security.core.GrantedAuthority;
  10. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  11. import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
  12. import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
  13. import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
  14. import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
  15. import org.springframework.security.oauth2.core.user.OAuth2User;
  16.  
  17. @Configuration
  18. public class AppSqlConfiger2 extends WebSecurityConfigurerAdapter {
  19.  
  20. /* (non-Javadoc)
  21. * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
  22. */
  23. @Override
  24. protected void configure(HttpSecurity http) throws Exception {
  25.  
  26. //@formatter:off
  27. http.authorizeRequests()
  28. .antMatchers("/", "/index**", "/login**", "/error**").permitAll()
  29. .antMatchers("/sql-sp-search/**").hasRole("SQL_USER")
  30. .antMatchers("/sql-tr-search/**").hasRole("SQL_USER")
  31. .and().logout().logoutSuccessUrl("/")
  32. .and().oauth2Login().userInfoEndpoint().userService(userService())
  33. ;
  34. //@formatter:on
  35. }
  36.  
  37. @SuppressWarnings("unchecked")
  38. private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService() {
  39.  
  40. //@formatter:off
  41. // Why configure this?
  42. // The default user-authority is DefaultOAuth2UserService.java, OAuth2UserAuthority.java and DefaultOAuth2User.java.
  43. // But the authority is set to ROLE_USER instead of authorities come from user-info endpoint on OAuth2UserAuthority.
  44. // So we need to reset the authority again after 'DefaultOAuth2UserService.loadUser()'.
  45. //@formatter:on
  46. final OAuth2UserService<OAuth2UserRequest, OAuth2User> delegate = new DefaultOAuth2UserService();
  47. return (userRequest) -> {
  48. OAuth2User oauthUser = delegate.loadUser(userRequest);
  49.  
  50. List<GrantedAuthority> authorities = new ArrayList<>();
  51. Object obj = oauthUser.getAttributes().get("authorities");
  52. if (obj != null) {
  53. List<String> authoritiesStrList = (List<String>) obj;
  54. for (String elem : authoritiesStrList) {
  55. GrantedAuthority authority = new SimpleGrantedAuthority(elem);
  56. authorities.add(authority);
  57. }
  58. }
  59.  
  60. return new DefaultOAuth2User(authorities, oauthUser.getAttributes(), "user");
  61. };
  62. }
  63. }

[注1] 我们在这里使用了oauth2Login()及自定义了一个OAuth2UserService。OAuth2UserService实际上就是上一节中讲的调用Authorization Server的/user端点拿到的User信息。至于为什么自定义了一个OAuth2UserService,可以看代码中的注释。

(2)配置参数

  1. ## Spring info
  2. spring:
  3. # OAuth2 Client info (see ClientRegistration.java)
  4. security:
  5. oauth2:
  6. client:
  7. registration:
  8. server-auth:
  9. client-id: app-sql-client
  10. client-secret: '{cipher}e93cce4a8056a7359ded238e97a1c6d25142e6b688873a1e6181ac06753dd9ae'
  11. # basic or post (default is basic)
  12. # client-authentication-method: basic
  13. # authorizationGrantType cannot be null, authorizationGrantType must be authorization_code
  14. authorization-grant-type: authorization_code
  15. # redirectUriTemplate cannot be empty, default is '{baseUrl}/login/oauth2/code/{registrationId}'
  16. redirect-uri: http://localhost:10200/app-sql/login/oauth2/code/server-auth
  17. scope: all
  18. # client-name: app-sql
  19. provider:
  20. server-auth:
  21. # It's very important to add 'scope=all' to the url. Auth Server didn't config the scope, so in client side,
  22. # we must config it, otherwise, 'Empty scope (either the client or the user is not allowed the requested scopes)'
  23. # error occurred.
  24. # use zuul to replace 'http://localhost:10030/server-auth/xxx'
  25. token-uri: http://localhost:10020/server-zuul/s3/server-auth/oauth/token?scope=all
  26. authorization-uri: http://localhost:10020/server-zuul/s3/server-auth/oauth/authorize
  27. user-info-uri: http://localhost:10020/server-zuul/s3/server-auth/user
  28. # header, form or query (default is header)
  29. # user-info-authentication-method: header
  30. # the key used to get the user's "name"
  31. user-name-attribute: user

使用OAuth2RestTemplate在Client端调用被OAuth2保护的Resource

上面几步实际上是搭建一个SSO登录系统,但是如果我们想要在OAuth2 Client端调用OAuth2 Resource时,就需要做一些额外配置了。OAuth2 Resource的配置会在下一节详细介绍,这里主要来讲在OAuth2 Client端如何配置。

在OAuth2 Client端配置的核心就是OAuth2RestTemplate。我们通过给OAuth2RestTemplate配置好所有访问OAuth2 Authorization Server的参数创建OAuth2RestTemplate,接下来对OAuth2 Resource的调用交给OAuth2RestTemplate即可。

这里使用password模式为例。

(1)配置Configer

  1. @Configuration
  2. public class AppSqlConfiger {
  3.  
  4. @Bean
  5. @ConfigurationProperties("app-sql.resources.app-db")
  6. protected OAuth2ProtectedResourceDetails resource() {
  7. return new ResourceOwnerPasswordResourceDetails();
  8. }
  9.  
  10. @Bean
  11. public OAuth2RestTemplate restTemplate() {
  12. AccessTokenRequest atr = new DefaultAccessTokenRequest();
  13. return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
  14. }
  15. }

(2)配置参数

  1. ## Regard 'app-sql' as oauth2-client and 'app-db' as oauth2-resource.
  2. ## Create OAuth2RestTemplate in 'app-sql' and set parameters(see AppSqlConfiger.java) and call 'app-db'.
  3. app-sql:
  4. resources:
  5. app-db:
  6. clientId: app-sql-client
  7. clientSecret: '{cipher}e93cce4a8056a7359ded238e97a1c6d25142e6b688873a1e6181ac06753dd9ae'
  8. grantType: password
  9. # use zuul to replace 'http://localhost:10030/server-auth/xxx'
  10. accessTokenUri: http://localhost:10020/server-zuul/s3/server-auth/oauth/token
  11. scope: all
  12. username: '{cipher}18a05787c976397d4d7d090ad326cc7417122109f590d8a8ba80cfa35f7a15c3'
  13. password: '{cipher}ab3894c202393761b8f789dd9f047e116b2008ae98b5f8119030796f905471d8'

再看Discovery Client

在Eureka Client一节中,我们讲了使用discoveryClient和loadBalancer来发现服务。现在,我们可以通过zuul来调用其他服务,和loadBalancer类似:

  1. ServiceInstance instance = loadBalancer.choose("server-zuul");
  2. String path = String.format("http://%s:%s/server-zuul/a2/app-db/structure-search/app/MORT/env/%s/db/%s/name/%s", instance.getHost(), instance.getPort(), env, db, name);
  3. ResponseEntity<String> response = restTemplate.exchange(path, HttpMethod.GET, null, String.class);

Spring Cloud(6.2):搭建OAuth2 Client的更多相关文章

  1. 【译文】用Spring Cloud和Docker搭建微服务平台

    by Kenny Bastani Sunday, July 12, 2015 转自:http://www.kennybastani.com/2015/07/spring-cloud-docker-mi ...

  2. spring cloud+dotnet core搭建微服务架构:Api授权认证(六)

    前言 这篇文章拖太久了,因为最近实在太忙了,加上这篇文章也非常长,所以花了不少时间,给大家说句抱歉.好,进入正题.目前的项目基本都是前后端分离了,前端分Web,Ios,Android...,后端也基本 ...

  3. Spring Cloud 入门教程 - 搭建配置中心服务

    简介 Spring Cloud 提供了一个部署微服务的平台,包括了微服务中常见的组件:配置中心服务, API网关,断路器,服务注册与发现,分布式追溯,OAuth2,消费者驱动合约等.我们不必先知道每个 ...

  4. spring cloud+.net core搭建微服务架构:Api授权认证(六)

    前言 这篇文章拖太久了,因为最近实在太忙了,加上这篇文章也非常长,所以花了不少时间,给大家说句抱歉.好,进入正题.目前的项目基本都是前后端分离了,前端分Web,Ios,Android...,后端也基本 ...

  5. Spring Cloud和Docker搭建微服务平台

    用Spring Cloud和Docker搭建微服务平台 This blog series will introduce you to some of the foundational concepts ...

  6. 手把手教你使用spring cloud+dotnet core搭建微服务架构:服务治理(-)

    背景 公司去年开始使用dotnet core开发项目.公司的总体架构采用的是微服务,那时候由于对微服务的理解并不是太深,加上各种组件的不成熟,只是把项目的各个功能通过业务层面拆分,然后通过nginx代 ...

  7. spring cloud+dotnet core搭建微服务架构:服务发现(二)

    前言 上篇文章实际上只讲了服务治理中的服务注册,服务与服务之间如何调用呢?传统的方式,服务A调用服务B,那么服务A访问的是服务B的负载均衡地址,通过负载均衡来指向到服务B的真实地址,上篇文章已经说了这 ...

  8. spring cloud+dotnet core搭建微服务架构:Api网关(三)

    前言 国庆假期,一直没有时间更新. 根据群里面的同学的提问,强烈推荐大家先熟悉下spring cloud.文章下面有纯洁大神的spring cloud系列. 上一章最后说了,因为服务是不对外暴露的,所 ...

  9. spring cloud+dotnet core搭建微服务架构:配置中心续(五)

    前言 上一章最后讲了,更新配置以后需要重启客户端才能生效,这在实际的场景中是不可取的.由于目前Steeltoe配置的重载只能由客户端发起,没有实现处理程序侦听服务器更改事件,所以还没办法实现彻底实现这 ...

  10. spring cloud+.net core搭建微服务架构:服务注册(一)

    背景 公司去年开始使用dotnet core开发项目.公司的总体架构采用的是微服务,那时候由于对微服务的理解并不是太深,加上各种组件的不成熟,只是把项目的各个功能通过业务层面拆分,然后通过nginx代 ...

随机推荐

  1. flask中使用ajax 处理前端请求,每隔一段时间请求一次

    需求: flask中使用ajax 处理前端请求,每隔一段时间请求一次,并展示在页面 使用 setInterval(function(){},1000)方法 结果展示: html:(test.html) ...

  2. 遇见zTree和chrome的俩坑

    今天后台系统发现一bug,就是前几天用zTree做的树形结构,今下午突然不好使了,然后就查问题.我自己电脑装的是chrome浏览器,后台debug一看传的json数据,没毛病,想当然的断定不是数据的问 ...

  3. CSP模拟赛 Repulsed(树形DP)

    题面 ⼩ w ⼼⾥的⽕焰就要被熄灭了. 简便起⻅,假设⼩ w 的内⼼是⼀棵 n − 1 条边,n 个节点的树. 现在你要在每个节点⾥放⼀些个灭⽕器,每个节点可以放任意多个. 接下来每个节点都要被分配给 ...

  4. sping boot 笔记 哎呦不错哦

    http://blog.csdn.net/u011998835/article/details/78352829 学习

  5. JavaScript是如何工作的02:深入V8引擎&编写优化代码的5个技巧

    概述 JavaScript引擎是执行 JavaScript 代码的程序或解释器.JavaScript引擎可以实现为标准解释器,或者以某种形式将JavaScript编译为字节码的即时编译器. 以为实现J ...

  6. Yarn 配置阿里源

    1.查看一下当前源 yarn config get registry 2.切换为淘宝源 yarn config set registry https://registry.npm.taobao.org ...

  7. Elasticsearch 调优之 shrink

    对于索引分片数量,我们一般在模板中统一定义,在数据规模比较大的集群中,索引分片数一般也大一些,在我的集群中设置为 24.但是,并不是所有的索引数据量都很大,这些小数据量的索引也同样有较大的分片数.在 ...

  8. The database principal owns a schema in the database, and cannot be dropped. (.Net SqlClient Data Pr

    解决microsoft sql server error:15138的方法 http://blog.csdn.net/gray13/article/details/4458523 用sp_change ...

  9. java file 常用操作

    File file = new File("D:\\javaClass\\image"); // 测试此抽象路径名表示的文件或目录是否存在. // 当且仅当此抽象路径名表示的文件或 ...

  10. Python3 输入和输出(一)

    1.输出格式美化 Python两种输出值的方式: 表达式语句和 print() 函数. 第三种方式是使用文件对象的 write() 方法,标准输出文件可以用 sys.stdout 引用. 如果希望输出 ...