GitLab 配置 OAuth2 实现第三方登录,简直太方便了!

简介: GitLab 配置 OAuth2 实现第三方登录,简直太方便了!

需求提出:


公司内部已有一套oneid用户中心,需要支持登录gitlab。


实现


GitLab支持配置第三方登录, 修改配置文件gitlab.rb


vi /etc/gitlab/gitlab.rb
#OAuth2.0
gitlab_rails['omniauth_enabled'] = true
gitlab_rails['omniauth_allow_single_sign_on'] = ['OneID']
gitlab_rails['omniauth_block_auto_created_users'] = false
gitlab_rails['omniauth_providers'] = [
  {
    'name' => 'OneID',
    'app_id' => '123',
    'app_secret' => '1111',
    'args' => {
      client_options: {
        'site' => 'http://10.30.75.85:31900',
        'authorize_url' => '/auth',
        'user_info_url' => '/userInfo'
      },
      user_response_structure: {
        root_path: [],
        id_path: 'userAccountID',
        attributes: {
          name: 'realName',
          nickname: 'nickname',
          email: 'email',
         username:'username'
        }
      },
      name: 'OneID',
      strategy_class: "OmniAuth::Strategies::OAuth2Generic"
    }
  }
]


http://10.30.75.85:31900 :本人服务的地址


以上数据仅供参考,请根据实际情况修改,不清楚配置请百度,有详细案例


我服务实现方式为java web项目(Spring boot),配置:


<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.11.3</version>
</dependency>
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.5.00</version>
</dependency>
<!-- 需要作为独立jar文件引用时(包含隐式依赖) -->
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.5.00</version>
    <classifier>standalone</classifier>
</dependency>


定义OAuthController.java


@Controller
@RefreshScope
public class OAuthController extends BaseController {
    @Value("${dossen.gitlab.url}")
    private String gitLabUrl;
    /**
     * 获得通过oneid登录得重定向地址
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String getGitLabStateVal(HttpServletRequest request, HttpServletResponse response){
        //所有cookie-我就看看,没什么用
        Cookie[] cookies = request.getCookies();
        //获得通过oneid登录得重定向地址
        String location = ImitativeLoginGitLabUtil.getLocation(gitLabUrl);
        String[] urlAndCookie = location.split("&&");
        //设置cookie
        Cookie cookie = new Cookie("_gitlab_session",urlAndCookie[1].replaceAll("_gitlab_session=",""));
        cookie.setPath("/");
        response.addCookie(cookie);
        return "redirect:"+urlAndCookie[0];
    }
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public String auth(OAuthRequest request) {
        //需要自己写实现逻辑鉴权返回给gitlab
        return "redirect:"";
    }
    /**
     * 获取用户信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userInfo")
    public Object userInfo(HttpServletRequest request) {
        //gitlab请求参数查询用户信息,返回给gitlab
        UserGetResponse userGetResponse = null;
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userAccountID", userGetResponse.getUserAccountID());
        resultMap.put("realName", userGetResponse.getRealName());
        resultMap.put("nickname", userGetResponse.getRealName());
        resultMap.put("username", userGetResponse.getEmail().split("@")[0]);
        resultMap.put("email", userGetResponse.getEmail());
        ResponseEntity<Object> responseEntity = new ResponseEntity<Object>(resultMap, 
        HttpStatus.valueOf(200));
        return responseEntity;
    }
}


定义ImitativeLoginGitLabUtil.java


package com.dossen.gitlab.adapter.util;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Value;
/**
 * 模拟登录gitlab请求获取重定向值
 * @Author wenfl
 * @Date 2021-10-14
 */
public class ImitativeLoginGitLabUtil {
    public static String getLocation(String gitLabUrl){
        HttpResponse<String> response = null;
        try {
            //打开登录页面
            response =Unirest.get(gitLabUrl).asString();
            //得到document对象
            Document doc = Jsoup.parse(response.getBody());
            String authenticity_token = doc.select("meta[name=csrf-token]").get(0).attr("content");
            String cookeiValue = response.getHeaders().getFirst("Set-Cookie");
            response = Unirest.post(gitLabUrl+"/users/auth/OneID")
                    .header("Cookie", cookeiValue)
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .field("authenticity_token", authenticity_token)
                    .asString();
            //获得重定向地址
            String location = response.getHeaders().getFirst("Location")+"&&"+cookeiValue.split(";")[0];
            return location;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}


经过上面的操作就已完成常规的登录了,界面如下


image.png


后续


因公司已有一套用户中心,需要实现直接在用户中心点击就完成登录的过程跳转到首页。结合OAuthController中getGitLabStateVal方法完成模拟gitlab页面点击第三方登录按钮操作,主要还是设置cookie的动作,需要在gitlab的域中设置才能生效 :


修改gitlab的nginx配置/var/opt/gitlab/nginx/conf/gitlab-http.conf


# 以下操作是为了能让用户中心点击图标实现登录的过程
location /oneid/login{
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://10.30.75.85:31900/login;
}


修改proxy_pass为java web项目地址


image.png



执行:gitlab-ctl restart nginx


注:不要执行gitlab-ctl reconfigure,否则配置会被覆盖


这样就可以在用户中心配置地址为:http://gitlaburl.com/oneid/login,就可以完成登录的动作了。



相关文章
|
6月前
|
开发工具 git
Gitlab配置mirrorRepository 镜像仓库
Gitlab配置mirrorRepository 镜像仓库 🔊业务场景📆1.在a项目中点击settings-》repository-》mirroring repositories📌tips🧣最后的话
192 0
|
7月前
|
Shell 网络安全 开发工具
手把手教你配置Git客户端上传代码至Gitlab仓库
手把手教你配置Git客户端上传代码至Gitlab仓库
147 1
手把手教你配置Git客户端上传代码至Gitlab仓库
|
9月前
|
JSON 网络安全 数据安全/隐私保护
gitlab--安装和配置
gitlab--安装和配置
|
7月前
|
安全
Gitlab配置webhook报错:Urlis blocked: Requests to the local netwo..解决
Gitlab配置webhook报错:Urlis blocked: Requests to the local netwo..解决
392 0
|
8月前
|
Linux 开发工具 数据安全/隐私保护
【GitLab私有仓库】在Linux上用Gitlab搭建自己的私有库并配置cpolar内网穿透
GitLab 是一个用于仓库管理系统的开源项目,使用Git作为代码管理工具,并在此基础上搭建起来的Web服务。 Gitlab是被广泛使用的基于git的开源代码管理平台, 基于Ruby on Rails构建, 主要针对软件开发过程中产生的代码和文档进行管理, Gitlab主要针对group和project两个维度进行代码和文档管理, 其中group是群组, project是工程项目, 一个group可以管理多个project, 可以理解为一个群组中有多项软件开发任务, 而一个project中可能包含多个branch, 意为每个项目中有多个分支, 分支间相互独立, 不同分支可以进行归并。 下面我们
|
5月前
|
存储 网络安全 数据安全/隐私保护
docker 安装gitlab,配置邮件,备份全流程
docker 安装gitlab,配置邮件,备份全流程
148 0
|
3天前
|
jenkins 持续交付 API
上传gitlab代码后jenkins自动进行发布的配置
上传gitlab代码后jenkins自动进行发布的配置
|
6天前
|
存储 JSON Java
gitlab配置hook,commit message的时候校验提交的信息
gitlab配置hook,commit message的时候校验提交的信息
21 0
|
24天前
|
Linux 网络安全 开发工具
【GitLab私有仓库】在Linux上用Gitlab搭建自己的私有库并配置cpolar内网穿透
【GitLab私有仓库】在Linux上用Gitlab搭建自己的私有库并配置cpolar内网穿透
|
2月前
|
Devops 开发工具 数据安全/隐私保护
Docker Swarm总结+CI/CD Devops、gitlab、sonarqube以及harbor的安装集成配置(3/5)
Docker Swarm总结+CI/CD Devops、gitlab、sonarqube以及harbor的安装集成配置(3/5)
79 0

相关实验场景

更多