GitLab 配置 OAuth2 实现第三方登录,简直太方便了!
点击关注公众号,实用技术文章及时了解需求提出:公司内部已有一套oneid用户中心,需要支持登录gitlab。实现GitLab支持配置第三方登录, 修改配置文件gitlab.rb:vi/e...
点击关注公众号,实用技术文章及时了解
需求提出:
公司内部已有一套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 "";
}
}
经过上面的操作就已完成常规的登录了,界面如下
后续
因公司已有一套用户中心,需要实现直接在用户中心点击就完成登录的过程跳转到首页。结合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
,就可以完成登录的动作了。
推荐
PS:因为公众号平台更改了推送规则,如果不想错过内容,记得读完点一下“在看”,加个“星标”,这样每次新文章推送才会第一时间出现在你的订阅列表里。点“在看”支持我们吧!
更多推荐
所有评论(0)