配置web.xml

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

<!-- Spring cloud starter: Security -->
<!-- Include: web, actuator, security, zuul, etc. -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<!-- Spring Security OAuth2 Autoconfigure (optional in spring-cloud-security after 2.1) -->
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency>
<!-- Spring Security OAuth2 Client (optional in spring-cloud-security after 2.1) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

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

配置Application

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

@SpringBootApplication
@EnableOAuth2Client
public class AppSqlApplication {
public static void main(String[] args) {
SpringApplication.run(AppSqlApplication.class, args);
}
}

SSO单点登录的配置

(1)配置Configer

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

package com.mycloud.demo.config;

import java.util.ArrayList;
import java.util.List; import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User; @Configuration
public class AppSqlConfiger2 extends WebSecurityConfigurerAdapter { /* (non-Javadoc)
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
*/
@Override
protected void configure(HttpSecurity http) throws Exception { //@formatter:off
http.authorizeRequests()
.antMatchers("/", "/index**", "/login**", "/error**").permitAll()
.antMatchers("/sql-sp-search/**").hasRole("SQL_USER")
.antMatchers("/sql-tr-search/**").hasRole("SQL_USER")
.and().logout().logoutSuccessUrl("/")
.and().oauth2Login().userInfoEndpoint().userService(userService())
;
//@formatter:on
} @SuppressWarnings("unchecked")
private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService() { //@formatter:off
// Why configure this?
// The default user-authority is DefaultOAuth2UserService.java, OAuth2UserAuthority.java and DefaultOAuth2User.java.
// But the authority is set to ROLE_USER instead of authorities come from user-info endpoint on OAuth2UserAuthority.
// So we need to reset the authority again after 'DefaultOAuth2UserService.loadUser()'.
//@formatter:on
final OAuth2UserService<OAuth2UserRequest, OAuth2User> delegate = new DefaultOAuth2UserService();
return (userRequest) -> {
OAuth2User oauthUser = delegate.loadUser(userRequest); List<GrantedAuthority> authorities = new ArrayList<>();
Object obj = oauthUser.getAttributes().get("authorities");
if (obj != null) {
List<String> authoritiesStrList = (List<String>) obj;
for (String elem : authoritiesStrList) {
GrantedAuthority authority = new SimpleGrantedAuthority(elem);
authorities.add(authority);
}
} return new DefaultOAuth2User(authorities, oauthUser.getAttributes(), "user");
};
}
}

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

(2)配置参数

## Spring info
spring:
# OAuth2 Client info (see ClientRegistration.java)
security:
oauth2:
client:
registration:
server-auth:
client-id: app-sql-client
client-secret: '{cipher}e93cce4a8056a7359ded238e97a1c6d25142e6b688873a1e6181ac06753dd9ae'
# basic or post (default is basic)
# client-authentication-method: basic
# authorizationGrantType cannot be null, authorizationGrantType must be authorization_code
authorization-grant-type: authorization_code
# redirectUriTemplate cannot be empty, default is '{baseUrl}/login/oauth2/code/{registrationId}'
redirect-uri: http://localhost:10200/app-sql/login/oauth2/code/server-auth
scope: all
# client-name: app-sql
provider:
server-auth:
# It's very important to add 'scope=all' to the url. Auth Server didn't config the scope, so in client side,
# we must config it, otherwise, 'Empty scope (either the client or the user is not allowed the requested scopes)'
# error occurred.
# use zuul to replace 'http://localhost:10030/server-auth/xxx'
token-uri: http://localhost:10020/server-zuul/s3/server-auth/oauth/token?scope=all
authorization-uri: http://localhost:10020/server-zuul/s3/server-auth/oauth/authorize
user-info-uri: http://localhost:10020/server-zuul/s3/server-auth/user
# header, form or query (default is header)
# user-info-authentication-method: header
# the key used to get the user's "name"
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

@Configuration
public class AppSqlConfiger { @Bean
@ConfigurationProperties("app-sql.resources.app-db")
protected OAuth2ProtectedResourceDetails resource() {
return new ResourceOwnerPasswordResourceDetails();
} @Bean
public OAuth2RestTemplate restTemplate() {
AccessTokenRequest atr = new DefaultAccessTokenRequest();
return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
}
}

(2)配置参数

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

再看Discovery Client

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

ServiceInstance instance = loadBalancer.choose("server-zuul");
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);
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. Java eclipse等常见问题汇总

    1.Eclipse 注释模板设置 2.eclipse注释字体大小显示不一样大

  2. 【Mac】打开配置文件,添加/修改环境变量

    打开文件编辑器: 进入终端,输入open -e .bash_profile或者open -t ~/.bash_profile  打开profile文件 填写配置的环境变量: #示例代码 export ...

  3. Spring MVC 学习笔记(二)

    6. 视图和视图解析器  ❤  Spring MVC如何解析视图                                  • 请求处理方法执行完成后,最终返回一个ModelAndView对象 ...

  4. Selenium常用API的使用java语言之7-控制浏览器操作

    (六)控制浏览器操作 1.控制浏览器窗口大小 有时候我们希望能以某种浏览器尺寸找开,访问的页面在这种尺寸下运行.例如可以将浏览器设置成移动端大小(480* 800),然后访问移动站点,对其样式进行评估 ...

  5. 48、[源码]-Spring容器创建-初始化事件派发器、监听器等

    48.[源码]-Spring容器创建-初始化事件派发器.监听器等 8.initApplicationEventMulticaster();初始化事件派发器: 获取BeanFactory 从BeanFa ...

  6. 没有向ZK写offset数据

    两天公司要学习kafka,结合之前的storm,做了一个简单的集成,之前也参考了网上的例子一些例子,发现或多或少都有一些问题.所以自己做了一个. 这个是网上其他人遇到的问题,给摘录一下,防止以后自己和 ...

  7. 使用JSP/Servlet技术开发新闻发布系统---JSP数据交互(二)

    JSP内置对象application application对象 JSP常用的内置对象 对象的作用域 作用的分类 对象的作用域 page作用域 实例 //页面1 <% String name = ...

  8. 原生JS实现简易随机点名功能

    定时器的工作原理,这里将用引用How JavaScript Timers Work中的例子来解释定时器的工作原理,该图为一个简单版的原理图.· 上图中,左侧数字代表时间,单位毫秒:左侧文字代表某一个操 ...

  9. ueditor从word粘贴公式

    官网地址http://ueditor.baidu.com Git 地址 https://github.com/fex-team/ueditor 参考博客地址 http://blog.ncmem.com ...

  10. Linux操作系统常用命令合集——第三篇-系统管理操作(25个命令)

    1.whoami [命令作用] 显示当前登录有效用户名称 [命令语法]  whoami    [选项] [常用选项] 无 [参数说明] 用户名称 [命令示例] 显示当前登录有效用户名称 # whoam ...