一.yml配置
#cas单点登录
cas:prefixUrl: https://域名:8443/cas
二.业务层解析ticket
1.根据前端传来的ticket向cas服务端发起请求验证(由于url是https,发起请求要过滤ssl验证)
public static String getStValidate(String url, String st, String service){try {url = url+"?service="+service+"&ticket="+st;CloseableHttpClient httpClient = null;SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),NoopHostnameVerifier.INSTANCE);httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build();HttpGet httpget = new HttpGet(url);HttpResponse response = httpClient.execute(httpget);String res = readResponse(response);return res == null ? null : (res == "" ? null : res);} catch (Exception e) {e.printStackTrace();}return "";}
2.得到cas服务端返回数据并yongxml工具类解析用户信息(下面方法不完整)
final String principal = XmlUtils.getTextForElement(res, "user");
public static String getTextForElement(final String xmlAsString, final String element) {final XMLReader reader = getXmlReader();final StringBuilder builder = new StringBuilder();final DefaultHandler handler = new DefaultHandler() {private boolean foundElement = false;@Overridepublic void startElement(final String uri, final String localName, final String qName,final Attributes attributes) throws SAXException {if (localName.equals(element)) {this.foundElement = true;}}@Overridepublic void endElement(final String uri, final String localName, final String qName) throws SAXException {if (localName.equals(element)) {this.foundElement = false;}}@Overridepublic void characters(char[] ch, int start, int length) throws SAXException {if (this.foundElement) {builder.append(ch, start, length);}}};reader.setContentHandler(handler);reader.setErrorHandler(handler);try {reader.parse(new InputSource(new StringReader(xmlAsString)));} catch (final Exception e) {log.error(e.getMessage(), e);return null;}return builder.toString();}
3.根据得到的用户去系统数据库查询是否存在该用户
if (StringUtils.isEmpty(principal)) {throw new Exception("No principal was found in the response from the CAS server.");}log.info("-------token----username---"+principal);//1. 校验用户是否有效SysUser sysUser = sysUserService.getUserByName(principal);result = sysUserService.checkUserIsEffective(sysUser);if(!result.isSuccess()) {return result;}String token = JwtUtil.sign(sysUser.getUsername(), sysUser.getPassword());// 设置超时时间redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);obj.put("token", token);obj.put("userInfo", sysUser);result.success("登录成功");