Jira - 對接公司用戶中心
2019-12
Jira接公司內部用戶中心
流程是登錄用戶中心,
拿到用戶信息,成功就登錄jira
如果是新用戶就創建用戶後再登錄。
需要些一個單獨的登錄頁面
保存爲auth-jira.jsp 放到jira的安裝目錄
假設jira的安裝目錄爲 /opt/atlassian/jira/
登錄文件保存到 /opt/atlassian_bak/jira/atlassian-jira/auth/auth-jira.jsp
登錄頁面就是 http://jira.xxx.com/auth/auth-jira.jsp
auth-jira.jsp內容
<%@page import="java.io.StringWriter"%>
<%@page import="com.atlassian.crowd.embedded.api.PasswordCredential"%>
<%@page
import="com.atlassian.crowd.manager.application.ApplicationService"%>
<%@page import="com.atlassian.crowd.model.application.Application"%>
<%@page import="java.lang.reflect.Method"%>
<%@page import="java.lang.reflect.Field"%>
<%@page import="com.atlassian.crowd.embedded.api.Group"%>
<%@page import="com.atlassian.crowd.embedded.impl.ImmutableUser"%>
<%@page import="com.atlassian.crowd.embedded.api.User"%>
<%@page import="java.io.IOException"%>
<%@page import="org.apache.commons.collections.map.HashedMap"%>
<%@page import="java.nio.charset.Charset"%>
<%@page import="java.util.Base64"%>
<%@page import="com.atlassian.jira.util.json.JSONObject"%>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.net.URLConnection"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.net.URL"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="com.atlassian.jira.component.ComponentAccessor"%>
<%@page import="com.atlassian.crowd.embedded.api.UnfilteredCrowdService"%>
<%@page import="org.slf4j.LoggerFactory"%>
<%@page import="org.slf4j.Logger"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%!//常量
final String USER_CENTER_LOGIN_URL = "http://xxx.com/login/index";
final String USER_CENTER_CHECK_URL = "http://xxx.com/login/index/checksso";
final String CONFLUENCE_AUTH_LOGIN_URL = "http://jira.xxx.com/auth/auth-jira.jsp"; //登錄jira的路徑
final Logger log = LoggerFactory.getLogger("aut-login.jsp");%>
<%!//部門用戶分組映射
final static Map DEPARTMENT_GROUP_MAPPING = new HashMap();
static {
/*TODO自己配置 */
DEPARTMENT_GROUP_MAPPING.put("235", "jira-software-users");
DEPARTMENT_GROUP_MAPPING.put("245", "jira-software-users");
DEPARTMENT_GROUP_MAPPING.put("1234", "jira-software-users");
DEPARTMENT_GROUP_MAPPING.put("1239", "jira-software-users");// groupName 使用 部門對應的groupName
}%>
<%!UnfilteredCrowdService server = ComponentAccessor.getComponent(UnfilteredCrowdService.class);%>
<%!static class HttpKit {
/**
* http 獲取內容
* @param url
* @return
*/
public static String get(String url) {
System.err.print(url);
String result = "";
BufferedReader in = null;
PrintWriter _out = null;
HttpURLConnection conn = null;
try {
String urlName = url;
URL realUrl = new URL(urlName);
//打開和URL之間的連接
conn = (HttpURLConnection) realUrl.openConnection();
//設置通用的請求屬性
conn.setRequestProperty("accept", "**");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
//獲取URLConnection對象對應的輸出流
_out = new PrintWriter(conn.getOutputStream());
//發送請求參數
_out.print("");
//flush輸出流的緩衝
_out.flush();
//定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (Exception e) {
System.out.println("發送POST請求出現異常!" + e);
e.printStackTrace();
} finally {
try {
if (_out != null) {
_out.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
if (conn != null) {
conn.disconnect();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.err.print(result);
return result;
}
}
/***
* 通過 用戶中心 獲取用戶
* @param token
* @return
*/
private Map getUserInfo4UserCenter(String token) {
String resp = HttpKit.get(this.USER_CENTER_CHECK_URL + "?sid=" + token);
if (resp != null && !"".equals(resp) && !"fbd".equals(resp)) {
try {
JSONObject json = new JSONObject(
new String(Base64.getDecoder().decode(resp.trim()), Charset.forName("utf-8")));
System.err.println("\n" + json);
Map obj = new HashedMap();
// 1. sid 網站單點登錄標識
// 2. url 網站驗證單點登錄是否成功的網址
// 3. username 登錄用戶名
// 4. isadmin 是否爲管理員
/*
{
"department_id": "235",
"password": "fffffffffffffffffffffffffff",
"name": "張三",
"username": "zhangsan"
}
*/
obj.put("department_id", json.get("department_id"));
obj.put("name", json.get("name"));
obj.put("username", json.get("username"));
obj.put("password", json.get("password"));
return obj;
} catch (Exception e) {
e.printStackTrace();
log.error("獲取用戶解碼出現異常", e);
}
}
return null;
}
public User createNewUser(String userName, String password, String fullName, String email, String groupName)
throws Exception {
ImmutableUser user = new ImmutableUser(1, userName, fullName, email, true);
server.addUser(user, password);
Group group = server.getGroup(groupName);
User savedUser = server.getUser(userName);
server.addUserToGroup(savedUser, group);
return savedUser;
}
public void affirmPassword(User user, String password) throws Exception {
try {
Field field = server.getClass().getDeclaredField("applicationService");
field.setAccessible(true);
Method getApplicationMethod = server.getClass().getDeclaredMethod("getApplication", new Class[] {});
getApplicationMethod.setAccessible(true);
Application apps = (Application) getApplicationMethod.invoke(server, new Object[] {});
ApplicationService applicationService = (ApplicationService) field.get(server);
User users = applicationService.authenticateUser(apps, user.getName(),
PasswordCredential.unencrypted(password));
return;
} catch (Exception exception) {
exception.printStackTrace();
}
server.updateUserCredential(user, password);
}
public void main(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws Exception {
//主流程邏輯
String sid = request.getParameter("sid");
if (sid == null) {
//跳轉到用戶中心
response.sendRedirect(this.USER_CENTER_LOGIN_URL + "?from=pos&struli=" + Base64.getEncoder()
.encodeToString(this.CONFLUENCE_AUTH_LOGIN_URL.getBytes(Charset.forName("utf-8"))));
return;
}
Map userInfo = getUserInfo4UserCenter(sid);
if (userInfo == null) {
out.println("<h1>從用戶中心獲取用戶信息失敗,請重新從用戶中心打開</h1>");
return;
}
String userName = (String) userInfo.get("username");//獲取用戶名
String password = String.valueOf(userInfo.get("password"));
String fullName = (String) userInfo.get("name");
String email = (String) userInfo.get("email");
String department_id = (String) userInfo.get("department_id");
String is_lock = String.valueOf(userInfo.get("is_lock"));
String pass = String.valueOf(userInfo.get("password"));
User user = server.getUser(userName);
boolean isNewUser = false;
if (user == null) {
String groupName = "jira-software-users"/*(String) DEPARTMENT_GROUP_MAPPING.get(department_id)*/;
if (groupName != null && !"".equals(groupName)) { //該部門在 cwd_auth_department_group 表中有配置.
user = createNewUser(userName, password, fullName, email, groupName);
isNewUser = true;
} else {
out.print("<h1>你所在的部門: " + department_id + ",不能訪問此係統,請聯繫部門負責人!</h1>");
return;
}
} else {
//確認密碼 如果密碼不一樣則會更改密碼
affirmPassword(user, password);
}
if (user != null) {//進行登入系統
out.println(
"<form action=\"/login.jsp\" method=\"post\" id=\"loginFrom\"><input name=\"os_username\" value=\""
+ userName + "\" type=\"hidden\"><input name=\"os_password\" value=\"" + password
+ "\" type=\"hidden\"><input name=\"login\" value=\"Log In\" type=\"hidden\"><input name=\"os_destination\" value=\"\" type=\"hidden\"></form>");
if (isNewUser) {
out.print("<h1>歡迎您訪問本系統! 用戶名:" + userName + ",密碼:" + password
+ ",<a href='javascript:document.getElementById(\"loginFrom\").submit();'>點擊此處回 進入系統</a></h1>");
return;
} else {
out.print("<script type=\"text/javascript\">\n" + "<!--\n" + " (function(){\n"
+ " document.getElementById('loginFrom').submit();\n" + " })();\n" + "//-->\n"
+ "</script>");
}
} else {
out.println("<h1>用戶自動登入失敗,請聯繫相關人員</h1>");
}
}%>
<%
StringWriter errout = new StringWriter();
try{
main(request, response, out);
}catch(Exception exception){
PrintWriter pr = new PrintWriter(errout);
exception.printStackTrace(new PrintWriter(errout));
pr.flush();
}
%>
<%=errout %>