springboot集成cas单点登录

  |   0 评论   |   0 浏览

cas工具类

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import lombok.extern.slf4j.Slf4j;

/**
 * cas工具
 * @author pengzai
 *
 */
@Slf4j
public class CasUtils {

	/**
	 * 验证ticket,获取登录用户信息
	 * @param casServer
	 * @param ticket
	 * @param serviceUrl
	 * @return
	 */
	public static String getUser(String casServer,String ticket,String serviceUrl){
        try {
        	StringBuilder url = new StringBuilder(casServer);
        	url.append("/serviceValidate?ticket=");
        	url.append(ticket);
        	url.append("&service=");
        	url.append(encodeUrl(serviceUrl.toString()));
        	log.info("cas请求ticket验证: "+url.toString());
            String serverResponse = retrieveResponseFromServer(new URL(url.toString()));
            log.info("cas响应ticket验证: "+serverResponse);
            return getTextForElement(serverResponse, "user");
        } catch (Exception e) {
        	log.error("cas请求ticket验证异常",e);
        	return null;
        }
    }

	private static String retrieveResponseFromServer(final URL validationUrl) {
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) validationUrl.openConnection();
            final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringWriter writer = new StringWriter();
            char[] chars = new char[256];
            int count = 0;
            while ((count = in.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }
            return writer.toString();
        } catch (Exception e) {
        	log.error("CasUtils异常",e);
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static String encodeUrl(final String url) {
    	if (url == null) {
    		return null;
    	}
        try {
            return URLEncoder.encode(url, "UTF-8");
        } catch (final UnsupportedEncodingException e) {
        	log.error("CasUtils异常",e);
            return url;
        }
    }
  
    private static String getTextForElement(final String xmlAsString,
                                           final String element) {
        final XMLReader reader = getXmlReader();
        final StringBuffer buffer = new StringBuffer();

        final DefaultHandler handler = new DefaultHandler() {

            private boolean foundElement = false;

            public void startElement(final String uri, final String localName,
                                     final String qName, final Attributes attributes)
                    throws SAXException {
                if (localName.equals(element)) {
                    this.foundElement = true;
                }
            }

            public void endElement(final String uri, final String localName,
                                   final String qName) throws SAXException {
                if (localName.equals(element)) {
                    this.foundElement = false;
                }
            }

            public void characters(char[] ch, int start, int length)
                    throws SAXException {
                if (this.foundElement) {
                    buffer.append(ch, start, length);
                }
            }
        };

        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);

        try {
            reader.parse(new InputSource(new StringReader(xmlAsString)));
        } catch (final Exception e) {
        	log.error("CasUtils异常",e);
            return null;
        }

        return buffer.toString();
    }
  
    private static XMLReader getXmlReader() {
        try {
            return XMLReaderFactory.createXMLReader();
        } catch (final SAXException e) {
        	log.error("CasUtils异常",e);
            throw new RuntimeException("Unable to create XMLReader", e);
        }
    }
}

CAS认证控制器

@GetMapping("/auth-code")
public R authCode(HttpServletRequest request) {
	String ticket = request.getParameter("ticket");
	String serviceUrl = request.getParameter("service");
	if(StringUtil.isBlank(ticket)) {
    	return R.fail("ticket不能为空");
    }
	if(StringUtil.isBlank(serviceUrl)) {
    	return R.fail("service不能为空");
    }
	//casUser 为cas平台登录的用户名
    String casUser = CasUtils.getUser(casServer, ticket, serviceUrl);
    if(StringUtil.isBlank(casUser)) {
    	return R.fail("cas统一认证失败: ticket无效");
    }
	
	//获取到用户名,后面继续 本系统的认证 创建,然后返回 前端
	......
}