Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >SpringCloud微服务实战系列(十九)Ouath2在真实场景中的应用之客户端接入(第一种写法)

SpringCloud微服务实战系列(十九)Ouath2在真实场景中的应用之客户端接入(第一种写法)

作者头像
品茗IT
发布于 2020-05-28 08:30:07
发布于 2020-05-28 08:30:07
1.2K00
代码可运行
举报
文章被收录于专栏:品茗IT品茗IT
运行总次数:0
代码可运行

SpringCloud微服务实战系列(十九)Ouath2在真实场景中的应用之客户端接入(第一种写法)

一、概述

《SpringCloud微服务实战系列(十七)Ouath2在真实场景中的应用之资源服务器》]中

已经介绍了资源服务器是如何搭建的。

《SpringCloud微服务实战系列(十八)Ouath2在真实场景中的应用之授权服务器》]中

已经介绍了授权服务器是如何搭建的。

本篇就是对Oauth2的实际应用方法的客户端接入方式的其中一种方法进行介绍。这种方法跟另外一种的区别是:

  1. 可以配置用户信息查询地址并自动查询补入。
  2. Nginx转发未携带请求host则会出错

如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以加入我们的java学习圈,点击即可加入,共同学习,节约学习时间,减少很多在学习中遇到的难题。

在Spring Oauth2中,Oauth2的使用过程中将角色分为三种:ResourceServer,AuthorizationServer,OauthClient.

由于篇幅较大,这里将Oauth2的搭建分成三个部分。本篇介绍OauthClient的其中一种写法。

这种方式是基于spring-security-oauth2-client的自动化配置。在Springboot官方文档可以找到这种配置方法。https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-security.html#boot-features-security-oauth2

代码可以在https://www.pomit.cn/java/spring/springcloud.html中的Oauth2相关中的组件下载即可。

二、客户端接入

客户端接入是一个复杂的过程,按照Springboot官方文档的指引,我这里把完整的流程写出来。

下面讲述下这个过程是怎样的。

2.1 引入依赖

需要引入spring-boot-starter-web、spring-cloud-starter-security和spring-security-oauth2-client相关jar包.

依赖如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-security</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.security</groupId>
		<artifactId>spring-security-oauth2-client</artifactId>
	</dependency>
</dependencies>
2.2 配置文件

这里使用yaml文件写配置,配置文件application.yml:

application.yml:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
server:
   port: 8181
spring:
   profiles:
      active: loc
   application:
      name: oauthClient
logging:
   level:
      root: info

这里

  1. 应用名称为oauthClient
  2. 指定配置为loc。

application-loc.yml:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
env: loc

spring:
   security:
      oauth2:
         client:
            registration:
               oauthClient:
                  clientId: MwonYjDKBuPtLLlK
                  clientSecret: 123456
                  clientName: oauthClient
                  provider: oauthAuth
                  authorizationGrantType: authorization_code
                  redirectUriTemplate: http://tw.pomit.cn/custom-callback
            provider:
               oauthAuth:
                  tokenUri: http://sso.pomit.cn/oauth/token
                  authorizationUri: http://sso.pomit.cn/oauth/authorize
                  userInfoUri: http://res.pomit.cn/api/userInfo
                  userNameAttribute: data

这里配置的东西可能会让你产生疑惑,下面一一讲述:

  1. spring.security.oauth2.client.registration.oauthClient是客户端的配置,其中最后的后缀oauthClient是你的应用名,千万别照搬了。clientId和clientSecret是客户端的密钥,需要在授权服务器加上这个客户端,provider指的是授权服务器,authorizationGrantType是授权类型,redirectUriTemplate是回调地址,授权服务器授权成功要有回调地址的。
  2. spring.security.oauth2.client.provider.oauthAuth是关于授权服务器的配置,其中最后的后缀oauthAuth是你的授权服务器应用名,千万别照搬了。tokenUri是token获取地址,后缀基本上都是/oauth/token;authorizationUri是授权地址,后缀基本上都是/oauth/authorize;userInfoUri是获取用户信息接口,这个要配置资源服务器的地址,是自己定义的,userNameAttribute是参数字段名。

基本配置就是这样了,如果中间出现问题,要多试几次查找问题。

2.3 启动

使用main直接启动即可。无需其他配置。

OauthClientApplication:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package cn.pomit.springbootwork.oauthclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

}
2.4 安全控制配置

这个安全控制,只是普通的Spring Security的安全配置,外加一行oauth2的配置。

需要继承WebSecurityConfigurerAdapter,并加上@EnableWebSecurity。

AccessSecurityConfiguration如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package cn.pomit.springbootwork.oauthclient.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class AccessSecurityConfiguration extends WebSecurityConfigurerAdapter {
	@Override
	public void configure(HttpSecurity http) throws Exception {
		http
        .authorizeRequests()
            .mvcMatchers("/test/**").permitAll()
            .antMatchers("/").permitAll()
			.antMatchers("/index.html").permitAll()
			.antMatchers("/css/**").permitAll()
			.antMatchers("/js/**").permitAll()
			.antMatchers("/img/**").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated().and()
            .oauth2Login().redirectionEndpoint()
			.baseUri("/custom-callback");
	}
}

其中, .oauth2Login().redirectionEndpoint().baseUri("/custom-callback");是表明了oauth2的授权回调地址。

2.5 测试web

这里写了三个web接口,来测试不用的访问控制级别的返回信息。

OauthTestRest:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package cn.pomit.springbootwork.oauthclient.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pomit.springbootwork.oauthclient.model.ResultModel;

@Controller
@RequestMapping("/")
public class OauthTestRest {

	@ResponseBody
	@RequestMapping(value = "/test/test", method = { RequestMethod.GET })
	public ResultModel test() {
		
		return ResultModel.ok("我就是test,客户端");
	}
	
	@RequestMapping(value = "/", method = { RequestMethod.GET })
	public String index() {
		
		return "/index.html";
	}
	
	@RequestMapping(value = "/logTo", method = { RequestMethod.GET })
	public String logTo() {
		
		return "/index.html";
	}

}

OauthClientRest:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package cn.pomit.springbootwork.oauthclient.web;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.pomit.springbootwork.oauthclient.model.IpModel;
import cn.pomit.springbootwork.oauthclient.model.ResultModel;
import cn.pomit.springbootwork.oauthclient.util.IPUtil;

@RestController
@RequestMapping("/api")
public class OauthClientRest {

	@RequestMapping(value = "/ip", method = { RequestMethod.GET })
	public ResultModel ip(HttpServletRequest request) {
		IpModel ipModel = new IpModel();
		ipModel.setClientIpAddress(IPUtil.getIpAddr(request));
		ipModel.setServerIpAddress(IPUtil.localIp());
		return ResultModel.ok(ipModel);
	}
	
	@RequestMapping(value = "/test")
	public ResultModel test(Principal principal) {

		return ResultModel.ok(principal.getName());
	}
	
	@RequestMapping(value = "/userInfo")
	public ResultModel userinfo(Principal principal) {

		return ResultModel.ok(principal.getName());
	}
}

OauthAdminRest:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package cn.pomit.springbootwork.oauthclient.web;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.pomit.springbootwork.oauthclient.model.IpModel;
import cn.pomit.springbootwork.oauthclient.model.ResultModel;
import cn.pomit.springbootwork.oauthclient.util.IPUtil;

@RestController
@RequestMapping("/admin")
public class OauthAdminRest {

	@RequestMapping(value = "/ip", method = { RequestMethod.GET })
	public ResultModel ip(HttpServletRequest request) {
		IpModel ipModel = new IpModel();
		ipModel.setClientIpAddress(IPUtil.getIpAddr(request));
		ipModel.setServerIpAddress(IPUtil.localIp());
		return ResultModel.ok(ipModel);
	}
	
	@RequestMapping(value = "/test")
	public ResultModel test(Principal principal) {

		return ResultModel.ok(principal.getName());
	}
	
	@RequestMapping(value = "/userInfo")
	public ResultModel userinfo(Principal principal) {

		return ResultModel.ok(principal.getName());
	}
}
2.6 过程中用到的其他实体和工具

IpModel :

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package cn.pomit.springbootwork.oauthclient.model;

public class IpModel {
	private String clientIpAddress;
	private String serverIpAddress;

	public String getClientIpAddress() {
		return clientIpAddress;
	}

	public void setClientIpAddress(String clientIpAddress) {
		this.clientIpAddress = clientIpAddress;
	}

	public String getServerIpAddress() {
		return serverIpAddress;
	}

	public void setServerIpAddress(String serverIpAddress) {
		this.serverIpAddress = serverIpAddress;
	}

}

IPUtil:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package cn.pomit.springbootwork.oauthclient.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

public class IPUtil {
	/**
	 * @Description: 获取客户端IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (ip.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (Exception e) {
					e.printStackTrace();
				}
				ip = inet.getHostAddress();
			}
		}
		// 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}

	/**
	 * 获取的是本地的IP地址
	 * 
	 * @return
	 */
	public static String localIp() {
		String result = "";
		try {
			InetAddress address = InetAddress.getLocalHost();
			result = address.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return result;
	}
}

ResultModel:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package cn.pomit.springbootwork.oauthclient.model;

/**
 * @author cff
 */
public class ResultModel {
	private String errorCode;
    private String message;
    private Object data;

    public ResultModel() {

    }

    public ResultModel(String errorCode, String message) {
        this.errorCode = errorCode;
        this.message = message;
    }

    public ResultModel(String errorCode, String message, Object data) {
        this.errorCode = errorCode;
        this.message = message;
        this.data = data;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void set	ErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static ResultModel ok(String testValue) {
        ResultModel rm = new ResultModel();
        rm.setData(testValue);
        return rm;
    }
}

三、测试过程

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
资源服务器:http://res.pomit.cn
授权服务器:http://sso.pomit.cn

客户端:
服务器1:http://tw.pomit.cn
  1. 未授权时:

在这里插入图片描述

  1. 点击授权登录:

在这里插入图片描述

  1. 如果已经授权过,则不会出现授权页面。否则出现授权登录页面:

在这里插入图片描述

  1. 授权成功后,再点获取信息:

在这里插入图片描述

四、微信OAUTH2授权过程

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

品茗IT-博客专题:https://www.pomit.cn/lecture.html汇总了Spring专题Springboot专题SpringCloud专题web基础配置专题。

快速构建项目

Spring项目快速开发工具:

一键快速构建Spring项目工具

一键快速构建SpringBoot项目工具

一键快速构建SpringCloud项目工具

一站式Springboot项目生成

Mysql一键生成Mybatis注解Mapper

Spring组件化构建

SpringBoot组件化构建

SpringCloud服务化构建

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/05/12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
js工具函数大全 || 实用篇
“ 关注 前端开发社区 ,回复 '领取资源',免费领取Vue,小程序,Node Js,前端开发用的插件以及面试视频等学习资料,让我们一起学习,一起进步
前端老道
2020/05/29
4.7K0
js工具函数大全 || 实用篇
100个常用的 JS 代码片段分享,值得你收藏
function cutstr(str, len) { var temp; var icount = 0; var patrn = /[^\x00-\xff]/; var strre = ""; for (var i = 0; i < str.length; i++) { if (icount < len - 1) { temp = str.substr(i, 1); if (patrn.exec(temp) == null) { icount = icount + 1 } else { icount = icount + 2 } strre += temp } else { break } } return strre + "..." }
前端达人
2021/10/08
2.4K0
JavaScript 103 条技能
1、原生JavaScript实现字符串长度截取 function cutstr(str, len) { var temp; var icount = 0; var patrn = /[^\x00-\xff]/; var strre = ""; for (var i = 0; i < str.length; i++) { if (icount < len - 1) { temp = str.substr
guanguans
2018/04/27
8800
原生态纯JavaScript 100大技巧大收集---你值得拥有(51--100)
56、原生JavaScript全角半角转换,iCase: 0全到半,1半到全,其他不转化
用户1272076
2019/03/26
1.4K0
原生态纯JavaScript 100大技巧大收集---你值得拥有(1--50)
1、原生JavaScript实现字符串长度截取 function cutstr(str, len) { var temp; var icount = 0; var patrn = /[^\x00-\xff]/; var strre = ""; for (var i = 0; i < str.length; i++) { if (icount < len - 1) { temp = str
用户1272076
2019/03/26
6330
JS实用技巧手记之八
除特别注明外,本站所有文章均为慕白博客原创,转载请注明出处来自https://geekmubai.com/programming/157.html
慕白
2018/08/03
4820
【总结】56个JavaScript 实用工具函数助你提升开发效率!
https://juejin.cn/post/7019090370814279693
pingan8787
2021/11/08
9490
【总结】56个JavaScript 实用工具函数助你提升开发效率!
javascript常用工具类的封装
一、js数组工具类 工具类方法 MyArrayFn包含的方法如下 判断一个元素是否在数组中 遍历元素:相当于原生forEach方法 遍历元素,对里面的每个值做处理再返回一个新的值:相当于原生map方法 数组排序:从小到大、从大到小、随机 去重 求两个集合的并集 求两个集合的交集 删除其中一个元素 最大值 最小值 求和 平均值 工具类代码 // js数组工具类 class MyArrayFn { /*判断一个元素是否在数组中*/ contains(arr, val) { re
不愿意做鱼的小鲸鱼
2022/09/26
1.6K0
javascript常用工具类的封装
js实用方法记录-指不定哪天就会用到的js方法
js实用方法记录-指不定哪天就会用到的js方法 常用或者不常用都有 判断是否在微信浏览器中 测试代码:isWeiXin()==false /** * 是否在微信中 */ function isWeixin() { return ( navigator.userAgent .toLowerCase() .indexOf('micromessenger') > -1 ) } 全角转半角 测试代码:wholetoHalf('hello'')=='hell
易墨
2018/09/14
1.3K0
模拟mui框架编码
//调用方法 /* 1、tm.os.ios/tm.os.android/tm.os.versions().webKit //表示安卓设备/ios设备/webKit内核 */ var tm = (function(document) { "use strict"; var readyRE = /complete|loaded|interactive/, //complete 可返回浏览器是否已完成对图像的加载。 idSelectorRE = /^#([\w-]+)$/,
White feathe
2021/12/08
1.3K0
JS常用功能代码片段
使用Math.random()生成一个随机数并将其映射到所需的范围,使用Math.floor()使其成为一个整数。
青梅煮码
2023/03/02
7590
js常用事件整理—兼容所有浏览器
1.鼠标滚动事件。 说明:返回值 大于0向上滚动,小于0向下滚动。 兼容型:所有浏览器。 代码: /*********************** * 函数:鼠标滚动方向 * 参数:event * 返回:滚轮方向[向上(大于0)、向下(小于0)] *************************/ var scrollFunc = function(e) { var direct = 0; e = e || window.event; if (e.wheelDelta) {//
磊哥
2018/05/08
2.3K0
干货丨JS 经典实例收集整理
一、跨浏览器事件 跨浏览器添加事件 //跨浏览器添加事件    function addEvent(obj,type,fn){        if(obj.addEventListener){            obj.addEventListener(type,fn,false);        }else if(obj.attachEvent){//IE            obj.attchEvent('on'+type,fn);        }    } 跨浏览器移除事件 //跨浏览器移除
腾讯NEXT学位
2020/05/12
1.5K0
前端切图仔,常用的21个字符串方法(上)
请注意,JavaScript 并没有一种有别于字符串类型的字符数据类型,所以返回的字符是长度为 1 的字符串。
王小婷
2021/07/21
8870
关于JavaScript常用的工具函数汇总
前言 随着开发经验的积累,很多人会有自己的常用站点,一些网址收藏,自己造的轮子或者别人的轮子,工具函数库等等。 这里提供一些常用的工具函数,如果你也有一些觉得挺不错的库,欢迎在下方评论💓。 格式化时间戳 export function formatDateTimeStamp(date, fmt) { // 格式化时间戳 : formatDateTimeStamp(new Date(time),'yyyy-MM-dd hh:mm:ss') if (/(y+)/.test(fmt)) {
唐志远
2022/10/27
5550
js混淆与反混淆
由于设计原因,前端的js代码是可以在浏览器访问到的,那么因为需要让代码不被分析和复制从而导致更多安全问题,所以我们要对js代码进行混淆。
ek1ng
2023/03/08
12K0
js混淆与反混淆
JavaScript常用的工具函数,不全面大家补充哦
JavaScript ( JS ) 是一种具有函数优先的轻量级,解释型或即时编译型的编程语言。虽然它是作为开发Web 页面的脚本语言而出名的,但是它也被用到了很多非浏览器环境中等等。
苏州程序大白
2021/12/15
3480
JavaScript常用的工具函数,不全面大家补充哦
常用的前端JavaScript方法封装
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/157261.html原文链接:https://javaforall.cn
全栈程序员站长
2022/09/15
8790
分享 49 个常用的 JS 方法,赶紧收藏吧
英文 | https://medium.com/@cookbug/49-commonly-used-front-end-javascript-method-packaging-f9be18947086
前端达人
2021/12/29
4820
前端60余种工具方法,值得收藏
“ 关注 前端开发社区 ,回复 '领取资源',免费领取Vue,小程序,Node Js,前端开发用的插件以及面试视频等学习资料,让我们一起学习,一起进步
前端老道
2020/05/27
9510
前端60余种工具方法,值得收藏
相关推荐
js工具函数大全 || 实用篇
更多 >
领券
💥开发者 MCP广场重磅上线!
精选全网热门MCP server,让你的AI更好用 🚀
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档