栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

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

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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),配置:


    org.jsoup
    jsoup
    1.11.3



    com.konghq
    unirest-java
    3.5.00




    com.konghq
    unirest-java
    3.5.00
    standalone

定义OAuthController.java

@Controller
@RefreshScope
public class OAuthController extends baseController {
    
    @Value("${dossen.gitlab.url}")
    private String gitLabUrl;
   
    
    @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:"";
    }

    
    @ResponseBody
    @RequestMapping(value = "/userInfo")
    public Object userInfo(HttpServletRequest request) {
        //gitlab请求参数查询用户信息,返回给gitlab

        UserGetResponse userGetResponse = null;

        Map resultMap = new HashMap();
        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 responseEntity = new ResponseEntity(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;


public class ImitativeLoginGitLabUtil {
    public static String getLocation(String gitLabUrl){
        HttpResponse 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 "";
    }
}

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

后续

因公司已有一套用户中心,需要实现直接在用户中心点击就完成登录的过程跳转到首页。结合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项目地址

执行:gitlab-ctl restart nginx

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

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

推荐

主流Java进阶技术(学习资料分享)

Java面试题宝典

加入Spring技术开发社区

PS:因为公众号平台更改了推送规则,如果不想错过内容,记得读完点一下“在看”,加个“星标”,这样每次新文章推送才会第一时间出现在你的订阅列表里。点“在看”支持我们吧!

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号