Web网站的授权oAuth2.0 单点登录

news2024/9/20 16:49:23

1.Web网站的授权(oAuth2.0)

在这里插入图片描述
在这里插入图片描述

  1. Client 第三方应用(需要做鉴权的业务网站、业务系统)
  2. UserAgent 用户代理(浏览器)
  3. Resource Owner 用户授权(用户手动点击【同意】按钮,授权使用第三方登录渠道),第三方渠道授权登录:微信同意登录、或qq授权登录或微博 、GitHub、Gitee,这里使用Gitee做当前网站的第三方授权渠道
  4. 用户认证,用户输入账号和密码(gitee账号&密码),账号会通过第三方授权服务器检验(gitee服务器、门户服务),如果校验通过会返一个授权码Authorization Code到业务系统(业务网站)
  5. 网站再次发请求并携带上一步获取的授权码Authorization Code去访问第三方授权服务(gitee、门户服务),第三方授权服务会返回一个访问令牌Access token
  6. 以后浏览器就可以通过token访问令牌跳过第三方授权直接访问服务器任意请求,token访问令牌可能需要做jwt解密(token校验)或token失效返新token操作
    在这里插入图片描述

点击gitee按钮,跳转到gitee码云登录页,如果gitee账号登录成功,会redirect重定向到咱们自动的业务网站系统首页
在这里插入图片描述
在做这套第三方渠道跳转前需要,需要在Gitee上创建第三方应用,这个应用需要配置如下:

  • Client ID :创建应用时自动生成的唯一标识
  • Client Secret :创建应用时自动生成的密钥
  • 重定向回调地址url:(需要手动配置)第三方登录授权成功后需要重定向到系统的首页
  1. 授权码Authorization Code
@GetMapping("/oauth2.0/gitee/success")
    public String oauth2(@RequestParam("code") String code, HttpSession httpSession) throws Exception {

        HttpResponse post = null;
        try {
            //https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
            Map<String,String> map = new HashMap<>();
            map.put("grant_type",Oauth2Constant.OAUTH2_GRANT_TYPE);
            map.put("code",code);
            map.put("client_id", Oauth2Constant.OAUTH2_CLIENT_ID);
            map.put("redirect_uri",Oauth2Constant.OAUTH2_RIDIRECT_URI);
            map.put("client_secret",Oauth2Constant.OAUTH2_CLIENT_SECRET);
            //String host, String path, String method,
            //Map<String, String> headers,
            //Map<String, String> querys,
            //Map<String, String> bodys
            post = HttpUtils.doPost("https://gitee.com", "/oauth/token", "POST", new HashMap<>(), map, new HashMap<>());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //取出token
        //获取状态行的响应码,如果是200就代表响应成功
        if (post.getStatusLine().getStatusCode() == 200){
            HttpEntity entity = post.getEntity();
            //将HttpEntity转换成String类型
            String entityJsonString = EntityUtils.toString(entity);
            //Json字符串 -> java对象  参数必须是String类型Json串
            SocialUser socialUser = JSON.parseObject(entityJsonString,SocialUser.class);

            //判断账号是否是第一次登陆,如果是第一次登陆就直接注册到会员服务
            R<MemberOAuthVo> r = memberFeignService.oauth2Login(socialUser);
            if (r.getCode() == 0){
                MemberOAuthVo memberOAuthVo = r.getData(new TypeReference<MemberOAuthVo>() {});
                log.info("用户信息:{}",memberOAuthVo);
                httpSession.setAttribute("loginUser",memberOAuthVo);
                return "redirect:http://gulimall.com";
            }
        }else {
            //获取失败 -> 重定向到登录页
            return "redirect:http://auth.gulimall.com/login.html";
        }

        //第三方授权成功 -> 跳转至登陆页
        return "redirect:http://gulimall.com";

    }

实体

/**
 * @Description: 社交用户信息
 **/

@Data
public class SocialUser {

    /**
     *     "access_token": "56310a891ae93588988a3c0e4e685a49",
     *     "token_type": "bearer",
     *     "expires_in": 86400,
     *     "refresh_token": "08782b4126a13a5fab5c22c78f772a88996c03c32aab13069bd7210165ebd91c",
     *     "scope": "user_info",
     *     "created_at": 1687418634
     */

    /**
     * 登陆状态识别:只要登陆就存在,会变化(有效期 1天)
     */
    private String access_token;

    private String token_type;

    /**
     * access_token的过期时间
     */
    private long expires_in;

    /**
     * 可以通过以下 refresh_token 方式重新获取 access_token( POST请求 )
     * https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token={refresh_token}
     */
    private String refresh_token;

    /**
     * 权限
     */
    private String scope;

    /**
     * 社交账号与用户账号的关联字段,固定不变
     */
    private long created_at;

}

HttpUtil

package com.atguigu.common.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {
    /**
     * get
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    /**
     * post form
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      Map<String, String> bodys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    /**
     * Post String
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Post stream
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Put String
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Put stream
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Delete
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String host, String path, String method,
                                        Map<String, String> headers,
                                        Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
}

2.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2042759.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

CPU飙升 怎么定位问题

传统的方法 【top】 查看所有进程占系统CPU的排序&#xff0c;定位是哪个进程搞的鬼。PID那一列就是进程号。 【top -Hp pid】 定位进程中使用 CPU 最高的线程tid 【printf ‘0x%x’ tid】 线程 tid 转化 16 进制,例如printf ‘0x%x’ 11882 得到16进制的 0x2e6a 【jstack…

Spring——IOC/DI思想

1、IOC&#xff08;Inversion of Control&#xff09;控制反转 何为控制反转&#xff1f; 在业务层中我们如果要调用数据层的方法那么必然牵扯到对象的创建&#xff0c;如果我想要改变上述数据层的方法中的内容&#xff0c;那么我就要改变业务层的代码&#xff0c;重新创建对…

R语言的矩阵运算

下面内容摘录自《R 语言与数据科学的终极指南》专栏文章的部分内容&#xff0c;每篇文章都在 5000 字以上&#xff0c;质量平均分高达 94 分&#xff0c;看全文请点击下面链接&#xff1a; 3章4节&#xff1a;R的逻辑运算和矩阵运算-CSDN博客文章浏览阅读165次。在 R 语言的丰…

PHP概述、环境搭建与基本语法讲解

目录 【学习目标、重难点知识】 什么是网站&#xff1f; 1. PHP 介绍 1.1. PHP 概述 1.1.1. PHP 是什么&#xff1f; 1.1.2. PHP 都能做什么&#xff1f; 1.2. PHP 环境搭建 1.2.1. PhpStudy 2. PHP 基本语法 2.1. PHP 语法入门 2.1.1. 第一个 PHP 程序 2.1.2. PHP …

Postman入门指南

前言 当前最为主流的开发模式&#xff1a;前后端分离 在这种模式下&#xff0c;前端技术人员基于"接口文档"&#xff0c;开发前端程序&#xff1b;后端技术人员也基于"接口文档"&#xff0c;开发后端程序。 由于前后端分离&#xff0c;对我们后端技术人…

PHP 无参数RCE总结

在这篇文章中&#xff0c;我总结了在参与CTF比赛过程中积累的关于PHP无参数远程代码执行&#xff08;RCE&#xff09;的经验。由于一直以来时间有限&#xff0c;今天终于有机会整理这些知识点。 可能用到的函数&#xff08;PHP的内置函数&#xff09; localeconv() 函数返回一…

String 事务

目录 一、什么是事务 二、Spring事务的实现方式 1、编程式事务 2、声明式事务 三、自动操作事务的注解的三个属性 1、rollbackFor 2、isolation 3、propagation 前言&#xff1a;本文所见围绕的主题是事务&#xff0c;所以笔者先讲解什么是事务&#xff0c;先让大家了解…

Selenium + Python 自动化测试15(模块化测试)

我们的目标是&#xff1a;按照这一套资料学习下来&#xff0c;大家可以独立完成自动化测试的任务。 上一篇我们讨论了使用SMTP 对象的sendmail 发送HTML报告的方法。 本篇文章我们接着讲测试代码的一些优化&#xff0c;提高我们测试代码的易读性&#xff0c;维护方便性。大家也…

ZooKeeper 集群的详细部署

ZooKeeper 集群部署 一、ZooKeeper 简介1.1 什么是 ZooKeeper1.2 ZooKeeper 特点 二 ZooKeeper 的架构和设计4.1 ZooKeeper 数据模型4.1.1 Znode 节点特性 三、ZooKeeper 的集群安装前准备工作3.1 需要的准备工作3.2 Linux 系统 3 个节点准备3.2.1 克隆3.2.2 配置另外两台服务器…

评论系统如何不崩溃?揭开海量评论背后的技术秘密

我是小米,一个喜欢分享技术的29岁程序员。如果你喜欢我的文章,欢迎关注我的微信公众号“软件求生”,获取更多技术干货! 大家好,我是小米!今天我们来聊聊一个非常实际的场景:海量新闻评论的入库问题。假设你在某个新闻平台工作,某条热门新闻突然火爆,用户的评论量如潮水…

SpringBoot Web开发(请求,响应,分层解耦)

Author_T17&#x1f965; 目录 一.请求响应概述 1.Servlet 2.DispatcherServlet 3.请求响应工作概图 4.BS/CS架构 二.API测试工具 三.请求 1.简单参数 &#xff08;1&#xff09;原始方式&#xff08;不推荐&#xff09; ​编辑 &#xff08;2&#xff09;Spring Boo…

【剑指 offer】删除链表中重复的结点

目 录 描述: 在一个排序的链表中&#xff0c;存在重复的结点&#xff0c;请删除该链表中重复的结点&#xff0c;重复的结点不保留&#xff0c;返回链表头指针。 例如&#xff0c;链表 1->2->3->3->4->4->5 处理后为 1->2->5 思路&#xff1a; 通过快慢…

2024年阳光电源社招校招入职测评:前程无忧智鼎题库全解析

在职场竞争日益激烈的今天&#xff0c;企业对人才的选拔标准越来越高。阳光电源&#xff0c;作为行业的领军企业&#xff0c;采用了前程无忧智鼎题库进行社招校招入职测评&#xff0c;旨在通过科学的方法选拔出与企业文化和价值观高度契合的人才。 测评概览 测评名称&#xff1…

大模型RAG企业级项目实战:Chatdoc智能助手文档(从零开始,适合新手)

大模型RAG企业级项目实战&#xff1a;Chatdoc智能助手文档&#xff08;从零开始&#xff0c;适合新手&#xff09; 大模型RAG企业级项目实战完整链接 LLM模型缺陷&#xff1a; ​ 知识是有局限性的(缺少垂直领域/非公开知识/数据安全) ​ 知识实时性(训练周期长、成本高) …

5计算机网络全面解析

网络功能和分类 计算机网络是计算机技术与通信技术相结合的产物&#xff0c;它实现了远程通信、远程信息处理和资源共享。 计算机网络的功能&#xff1a;数据通信、资源共享、管理集中化、实现分布式处理、负载均衡。 网络性能指标&#xff1a;速率、带宽&#xff08;频带宽…

1.微服务发展阶段

单体应用阶段 简介 系统业务量很小的时候我们把所有的代码都放在一个项目中&#xff0c;然后将这个项目部署在一台服务器上&#xff0c;整个项目所有的服务都由这台服务器去提供 优点 1.展现层、控制层、持久层全都在一个应用里面&#xff0c;调用方便、快速&#xff0c;单个请…

Unity URP 曲面细分学习笔记

Unity URP 曲面细分学习笔记 1.曲面细分与镶嵌1.1 外壳着色器 Hull Shader1.2 镶嵌器阶段 Tessellator1.3 域着色器阶段 Domain Shader 2.具体实现2.1 不同的细分策略2.1.1 平面镶嵌 Flat Tessellation2.1.2 PN Tessellation&#xff08;Per-Node Tessellation&#xff09;2.1.…

NPM使用教程:从入门到精通

NPM使用教程&#xff1a;从入门到精通&#xff0c;掌握Node.js包管理神器 引言 随着Node.js的流行&#xff0c;JavaScript已经成为服务器端开发的主力军。NPM&#xff08;Node Package Manager&#xff09;作为Node.js的官方包管理工具&#xff0c;为开发者提供了一个庞大的代…

用R的界面来安装扩展包

下面内容摘录自《R 语言与数据科学的终极指南》专栏文章的部分内容&#xff0c;每篇文章都在 5000 字以上&#xff0c;质量平均分高达 94 分&#xff0c;看全文请点击下面链接&#xff1a; 2章4节&#xff1a;认识和安装R的扩展包&#xff0c;什么是模糊搜索安装&#xff0c;工…

Linux高级编程 8.12 标准IO

目录 一、标准io 二、文件 三、man手册 四、操作文件 1.fopen 2.fputc 3.fgetc 4.fgets 5.fputs 6.fread 7.fwrite 五、命令解读 1.显示目录下的文件信息命令 2.vimdiff小工具 3.stat命令 一、标准io IO&#xff1a; input output I&#xff1a; 键盘是标准输…