公司账号服务单点登录到gitlab

目标:使用oauth协议,点击挂在系统的gitlab链接,直接登录到gitlab的服务,如果没有账号则新建

操作:
一.服务端:
1.在自己的系统内添加oauth协议的包

<dependency><groupId>org.apache.oltu.oauth2</groupId><artifactId>org.apache.oltu.oauth2.authzserver</artifactId><version>0.31</version>
</dependency>
<dependency><groupId>org.apache.oltu.oauth2</groupId><artifactId>org.apache.oltu.oauth2.resourceserver</artifactId><version>0.31</version>
</dependency>

2.实现和client端交互的三个接口,接口之间的参数验证已经省略
(1).获取客户端 code,没遇到什么问题

import java.net.URI;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ResponseType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
public class AuthorizeController {private static Logger logger = LoggerFactory.getLogger(AuthorizeController.class);@RequestMapping("/responseCode")public Object toShowUser(Model model, HttpServletRequest request) {logger.info("访问responseCode接口,获取状态码");try {OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);//1.验证clientIdif ("********************".equals(oauthRequest.getClientId())) {String authCode = null;String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);logger.info("responseType:" + responseType);// ResponseType仅支持CODE和TOKENif (responseType.equals(ResponseType.CODE.toString())) {OAuthIssuerImpl oAuthIssuer = new OAuthIssuerImpl(new MD5Generator());authCode = oAuthIssuer.authorizationCode();}// 进行OAuth响应构建OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);// 设置授权码,存储用来下一个请求认证builder.setCode(authCode);// 得到到客户端重定向地址String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);logger.info("redirectURI:" + redirectURI);// 构建响应final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();String responceUri = response.getLocationUri();// 根据OAuthResponse返回ResponseEntity响应HttpHeaders headers = new HttpHeaders();try {headers.setLocation(new URI(response.getLocationUri()));} catch (Exception e) {e.printStackTrace();}return "redirect:" + responceUri;}} catch (Exception e) {}return null;}
}

(2)生成access_token,在这块卡了很长时间,原因是返回值是Map的形式,gitlab官方也没有找到对返回值的规范,就写出来记录一下吧。

import java.util.HashMap;
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.issuer.UUIDValueGenerator;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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 com.alibaba.fastjson.JSON;@Controller
public class AccessTokenController {private static Logger logger = LoggerFactory.getLogger(AccessTokenController.class);// 获取客户端的code码,向客户端返回access token@RequestMapping(value = "/responseAccessToken",method = RequestMethod.POST)@ResponseBodypublic Object token(HttpServletRequest request) {logger.info("访问responseAccessToken接口        获取access_token");OAuthIssuer oauthIssuerImpl = null;OAuthResponse response = null;// 构建OAuth请求try {OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);// 1.验证authcodeString authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);// 2.验证clientSecretString clientSecret = oauthRequest.getClientSecret();logger.info("clientSecret:" + clientSecret);// 3.生成Access TokenoauthIssuerImpl = new OAuthIssuerImpl(new UUIDValueGenerator());final String accessToken = oauthIssuerImpl.accessToken();            Map<String,String> resultMap = new HashMap<String,String>();resultMap.put("access_token", accessToken);resultMap.put("expires_in", "0");return resultMap;} catch (OAuthSystemException e) {e.printStackTrace();} catch (OAuthProblemException e) {e.printStackTrace();}return null;}
}

(3).通过access_token获取账号信息,这块的遇到的问题主要有两个,第一个是在request中没有取到access_token,试着打印了http完整的请求,发现在request之前会打印完整信息,但是request是取不到的,具体获取方法先如下。第二个问题是,用户同步的问题,id(感觉是为了保证唯一性,否则每次都是新建的账号),name,nickname,email,这四个参数是可以满足,新建gitlab账号,正常单点登录的问题。

import java.util.HashMap;
import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.apache.commons.lang3.StringUtils;
import org.apache.oltu.oauth2.as.request.OAuthUnauthenticatedTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import com.alibaba.fastjson.JSON;@Controller
public class UserInfoController {private static Logger logger = LoggerFactory.getLogger(UserInfoController.class);@RequestMapping("/userInfo")@ResponseBodypublic Object userInfo(HttpServletRequest request) {logger.info("访问userInfo接口  获取账号信息");String header = request.getHeader("authorization");String[] split = header.split(" ");String accesstoken = split[1].trim();// 1.验证token//1.1验证token的过期时间String username = commonUtils.getUsernameByToken(accesstoken);if (StringUtils.isBlank(username)) {return "";}// 2.取到账号信息返回Map<String, Object> resultMap = new HashMap<String, Object>();if ("zhangsan".equals(username)) {resultMap.put("id", "111");resultMap.put("name", "zhangsan");resultMap.put("nickname", "zhangsan");resultMap.put("email", "******@163.com");} else if ("lisi".equals(username)) {resultMap.put("id", "112");resultMap.put("name", "lisi");resultMap.put("nickname", "lisi");resultMap.put("email", "lisi@163.com");} logger.info(JSON.toJSONString(resultMap));ResponseEntity<Object> responseEntity = new ResponseEntity<Object>(resultMap, HttpStatus.valueOf(200));return responseEntity;}
}

二,是客户端gitlab的配置,主要修改 /etc/gitlab/gitlab.rb文件
配置的含义可以看gitlab官方解释,具体配置app_id和app_secret 自己和服务端关联起来就好,三个接口可以自己定义,gitlab有默认接口:

 user_info_url: '/api/v3/user', # The endpoint on your OAuth 2 server that provides user info for the current userauthorize_url: '/oauth/authorize', # The authorization endpoint for your OAuth servertoken_url: '/oauth/token' # The token request endpoint for your OAuth server

具体查看 oauth2_generic.rb 文件,忘了在哪个目录了

gitlab_rails['omniauth_enabled'] = true
gitlab_rails['omniauth_allow_single_sign_on'] = ['****']
gitlab_rails['omniauth_block_auto_created_users'] = false
#gitlab_rails['omniauth_auto_sign_in_with_provider'] = '****'
gitlab_rails['omniauth_providers'] = [{'name' => '****',#'app_id' => '67bc4a4b7515a2cc5a31ab91d8bf953f68b21b08b701dc20c6102eec65d80e9c',#'app_secret' => 'b9ca8154f8efc888ed95a44161ed1237fb0b8a84ea7fe2532eb879f812cf73d8','app_id' => '67bc4a4b7515a2cc5a31ab91d8bf953f68b21b08b701dc20c','app_secret' => 'b9ca8154f8efc888ed95a44161ed1237fb0b8a84ea7fe253','args' => {client_options: {'site' => 'http://127.0.0.1:8080', 'authorize_url' => '/v1/sso/responseCode','token_url' => '/v1/sso/responseAccessToken','user_info_url' => '/v1/sso/userInfo'},user_response_structure: {root_path: [],id_path: 'id',attributes: { name: 'name',nickname: 'nickname',email: 'email'}},name: '****', strategy_class: "OmniAuth::Strategies::OAuth2Generic"   }}
]

至此,是可以满足正常的单点登录啦。
出现过的问题:

  1. 导航栏: 邮箱已经别注册,gitlab是一个邮箱对应一个账号
  2. 客户端会做token是否过期的判断,注意过期时间
  3. 对于gitlab已有的账号,需要关联一下账号 操作步骤:正常登录–>setting–>account–>Connected Accounts

还有剩余问题:
测试中出现

还有遇到的问题欢迎大家评论探讨。、
有帮助的话记得收藏点赞,谢谢。

公司账号服务单点登录到gitlab相关推荐

  1. 微服务——用户微服务单点登录

    用户微服务单点登录 为什么要使用单点登录原理 链接:https://blog.csdn.net/weixin_45528987/article/details/105365115 架构图 看图可能还有 ...

  2. 根据AD账号直接单点登录到第三方系统

    上周在做一个单点登录的任务,今天有时间就整理一下,当时遇到的问题很多,我会慢慢的回忆记录下来. 首先这个单点登录我们要构思一下: 之前的版本是,跳转的链接url是个固定值,它保存到了数据库,我们点击后 ...

  3. 十六.SpringCloud+SpringSession实现微服务单点登录

    Session不共享问题 对于登录而言,通常情况下我们喜欢把登录信息存储到服务器的Session中,这种存储方式在单体应用中没有问题,但是在分布式/集群环境中会存在Session丢失问题,如下图: 解 ...

  4. SSO单点登录教程案例 客户端和服务端

    这里写自定义目录标题 前言 条件 环境要求 准备工作 下载基础项目 项目结构说明 执行流程图 代码实现 单点登录步骤梳理: 代码下载 前言 文章摘抄:https://www.jianshu.com/p ...

  5. SSO单点登录教程(四)自己动手写SSO单点登录服务端和客户端

    作者:蓝雄威,叩丁狼教育高级讲师.原创文章,转载请注明出处. 一.前言 我们自己动手写单点登录的服务端目的是为了加深对单点登录的理解.如果你们公司想实现单点登录/单点注销功能,推荐使用开源的单点登录框 ...

  6. Gitlab集成odoo单点登录

    Gitlab集成odoo单点登录 1.Gitlab使用oauth2单点登录的背景 OAuth代表资源所有者向客户端应用程序提供对服务器资源的"安全委派访问".实际上,OAuth允许 ...

  7. 统一协同工作平台用户管理、单点登录以及任务集成接口说明

    1 概述 西北油田分公司信息化经过长期建设,在各个业务点上,逐步搭建了适应业务管理的信息化系统,为分公司经营管理提供了强大的信息化辅助管理支撑. 但是,分公司前期建设的信息化系统都是基于传统办公自动化 ...

  8. CAS4.1单点登录实现(包含原理配置实现及简易demo)

    CAS单点登录-简介 CAS 简介 CAS ( Central Authentication Service ) 是 Yale 大学发起的一个企业级的.开源的项目,旨在为 Web 应用系统提供一种可靠 ...

  9. 10_单点登录SSO

    是什么 在企业发展初期,企业使用的系统很少,通常一个或者两个,每个系统都有自己的登录模块,运营人员每天用自己 的账号登录,很方便.但随着企业的发展,用到的系统随之增多,运营人员在操作不同的系统时,需要 ...

最新文章

  1. UIAutomation 自动化
  2. 电商常用同义词库_【福利】不可错过的电商设计神器,提高工作效率
  3. java rhino 运行 js_Mozilla Rhino :如何从Java调用JS函数
  4. BZOJ5073 小A的咒语(动态规划)
  5. Android 系统性能优化(24)--布局优化
  6. 添加Silverlight应用到HTML
  7. 了解一下JAVA中的NIO模块
  8. Leetcode每日一题:面试题17.10.find-majority-element-lcci(主要元素)
  9. 今日头条 mysql_今日头条的核心技术细节是什么?
  10. 分布式事务处理--消息发送一致性的异常流程处理
  11. python清洗数据去除停用词_python去除停用词(结巴分词下)
  12. 产品读书《赋能:打造应对不确定性的敏捷团队》
  13. opencv打开图片显示全灰色
  14. ZigBee模块无线传输星形拓扑组网结构简介
  15. 十分钟自动执行一次_十分钟上手BDP,简单好用的数据分析神器
  16. cassandra cqlsh 使用实际IP或者locahost都可以进入命令行
  17. Mellotron:Multispeaker expressive voice synthesis by conditioning on rhythm, pitch and global style
  18. mysql sending data 耗时_mysql sending data状态时间花费太大
  19. Shopify卖家:EDM营销就要搭配SaleSmartly,轻松搞定转化率
  20. 深度学习笔记---多尺度网络结构归类总结

热门文章

  1. 最好用的超大视频压缩软件
  2. 程序员经常看的开源月刊《HelloGitHub》第 56 期
  3. 阿里前端工程师面试题+解题思路
  4. 20135203齐岳 信息安全系统设计基础期中总结
  5. STM32F103 实例应用(2)——DAP仿真下载以及STVP下载
  6. 数字经济时代,企业上云将成为数字化转型突破口
  7. vue实现 文件重命名
  8. 计算机毕业设计springboot+vue基本微信小程序的校园二手商城的设计与实现
  9. 扫雷游戏软件测试,软件测试-扫雷游戏
  10. 立体匹配——A Large Dataset to Train Convolutional Networks for Disparity, Optical Flow, and Scene Flow Es