Jira - 对接公司用户中心

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 %>


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

max229max

有帮助就打赏一个呗~

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值