util
public class CasUtil {private static final Logger LOGGER = LoggerFactory.getLogger(CasUtil.class);/*** cas client 默认的session key*/public final static String CAS = "_const_cas_assertion_";/*** 封装UserInfo** @param request* @return*/public static UserInfo getUserInfoFromCas (HttpServletRequest request) {Object object = request.getSession().getAttribute(CAS);if ( null == object ) {return null;}Assertion assertion = ( Assertion ) object;return buildUserInfoByCas(assertion);}/*** 构建UserInfo** @param assertion* @return*/private static UserInfo buildUserInfoByCas (Assertion assertion) {if ( null == assertion ) {LOGGER.error("cas对接buildUserInfoByCas没有获取到用户");return null;}UserInfo userInfo = new UserInfo();String userName = assertion.getPrincipal().getName();LOGGER.info("cas对接登录用户buildUserInfoByCas:" + userName);userInfo.setUserAccount(userName);//获取属性值Map<String, Object> attributes = assertion.getPrincipal().getAttributes();Object name = attributes.get("cn");userInfo.setUserName(name == null ? userName : name.toString());userInfo.setAttributes(attributes);return userInfo;}}
bean
public class UserInfo {/*** 用户姓名*/private String userName = null;/*** 用户账户*/private String userAccount = null;/*** 返回的其他用户属性*/private Map<String,Object> attributes;public String getUserName () {return userName;}public void setUserName (String userName) {this.userName = userName;}public String getUserAccount () {return userAccount;}public void setUserAccount (String userAccount) {this.userAccount = userAccount;}public Map<String, Object> getAttributes () {return attributes;}public void setAttributes (Map<String, Object> attributes) {this.attributes = attributes;} }
config
package com.ls.cas.config;import org.jasig.cas.client.authentication.DefaultGatewayResolverImpl; import org.jasig.cas.client.authentication.GatewayResolver; import org.jasig.cas.client.util.AbstractCasFilter; import org.jasig.cas.client.util.CommonUtils; import org.jasig.cas.client.validation.Assertion; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.annotation.Order;import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException;@Order(1) @WebFilter(filterName = "AuthenticationFilter", urlPatterns = { "/cas/*" }) public class AuthenticationFilter extends AbstractCasFilter {@Value("${cas.appUrl}")private String serverName ;@Value("${cas.url}")private String loginServer ;private boolean renew = false;private boolean gateway = false;private GatewayResolver gatewayStorage = new DefaultGatewayResolverImpl();@Overrideprotected void initInternal(FilterConfig filterConfig) throws ServletException {if (!isIgnoreInitConfiguration()) {super.initInternal(filterConfig);setCasServerLoginUrl(loginServer+"/login");if(serverName!=null){super.setServerName(serverName);}final String gatewayStorageClass = getPropertyFromInitParams(filterConfig, "gatewayStorageClass", null);if (gatewayStorageClass != null) {try {this.gatewayStorage = (GatewayResolver) Class.forName(gatewayStorageClass).newInstance();} catch (final Exception e) {log.error(e,e);throw new ServletException(e);}}}}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest)servletRequest;HttpServletResponse response = (HttpServletResponse)servletResponse;final HttpSession session = request.getSession(false);final Assertion assertion = session != null ? (Assertion) session.getAttribute(CONST_CAS_ASSERTION) : null;if (assertion != null) {filterChain.doFilter(request, response);return;}final String serviceUrl = constructServiceUrl(request, response);final String ticket = CommonUtils.safeGetParameter(request,getArtifactParameterName());final boolean wasGatewayed = this.gatewayStorage.hasGatewayedAlready(request, serviceUrl);if (CommonUtils.isNotBlank(ticket) || wasGatewayed) {filterChain.doFilter(request, response);return;}final String modifiedServiceUrl;log.debug("no ticket and no assertion found");if (this.gateway) {log.debug("setting gateway attribute in session");modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl);} else {modifiedServiceUrl = serviceUrl;}if (log.isDebugEnabled()) {log.debug("Constructed service url: " + modifiedServiceUrl);}final String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway);if (log.isDebugEnabled()) {log.debug("redirecting to \"" + urlToRedirectTo + "\"");}response.sendRedirect(urlToRedirectTo);}/*** The URL to the CAS Server login.*/private String casServerLoginUrl;public final void setCasServerLoginUrl(final String casServerLoginUrl) {this.casServerLoginUrl = casServerLoginUrl;}public final void setGatewayStorage(final GatewayResolver gatewayStorage) {this.gatewayStorage = gatewayStorage;}}package com.ls.cas.config;import org.jasig.cas.client.proxy.*; import org.jasig.cas.client.util.CommonUtils; import org.jasig.cas.client.util.ReflectUtils; import org.jasig.cas.client.validation.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*;@Order(2) @Component @WebFilter(filterName = "Cas20ProxyReceivingTicketValidationFilter", urlPatterns = { "/cas/*" }) public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketValidationFilter {@Value("${cas.appUrl}")private String serverName ;@Value("${cas.url}")private String validateServer ;private static final String[] RESERVED_INIT_PARAMS = new String[] {"proxyGrantingTicketStorageClass", "proxyReceptorUrl", "acceptAnyProxy", "allowedProxyChains", "casServerUrlPrefix", "proxyCallbackUrl", "renew", "exceptionOnValidationFailure", "redirectAfterValidation", "useSession", "service", "artifactParameterName", "serviceParameterName", "encodeServiceUrl", "millisBetweenCleanUps", "hostnameVerifier", "encoding", "config"};private static final int DEFAULT_MILLIS_BETWEEN_CLEANUPS = 60 * 1000;/*** The URL to send to the CAS server as the URL that will process proxying requests on the CAS client.*/private String proxyReceptorUrl;private Timer timer;private TimerTask timerTask;private int millisBetweenCleanUps;private ProxyGrantingTicketStorage proxyGrantingTicketStorage = new ProxyGrantingTicketStorageImpl();@Overrideprotected void initInternal(final FilterConfig filterConfig) throws ServletException {super.setServerName(serverName);setProxyReceptorUrl(getPropertyFromInitParams(filterConfig, "proxyReceptorUrl", null));final String proxyGrantingTicketStorageClass = getPropertyFromInitParams(filterConfig, "proxyGrantingTicketStorageClass", null);if (proxyGrantingTicketStorageClass != null) {this.proxyGrantingTicketStorage = ReflectUtils.newInstance(proxyGrantingTicketStorageClass);if (this.proxyGrantingTicketStorage instanceof AbstractEncryptedProxyGrantingTicketStorageImpl) {final AbstractEncryptedProxyGrantingTicketStorageImpl p = (AbstractEncryptedProxyGrantingTicketStorageImpl) this.proxyGrantingTicketStorage;final String cipherAlgorithm = getPropertyFromInitParams(filterConfig, "cipherAlgorithm", AbstractEncryptedProxyGrantingTicketStorageImpl.DEFAULT_ENCRYPTION_ALGORITHM);final String secretKey = getPropertyFromInitParams(filterConfig, "secretKey", null);p.setCipherAlgorithm(cipherAlgorithm);try {if (secretKey != null) {p.setSecretKey(secretKey);}} catch (final Exception e) {throw new RuntimeException(e);}}}log.trace("Setting proxyReceptorUrl parameter: " + this.proxyReceptorUrl);this.millisBetweenCleanUps = Integer.parseInt(getPropertyFromInitParams(filterConfig, "millisBetweenCleanUps", Integer.toString(DEFAULT_MILLIS_BETWEEN_CLEANUPS)));super.initInternal(filterConfig);}@Overridepublic void init() {super.init();CommonUtils.assertNotNull(this.proxyGrantingTicketStorage, "proxyGrantingTicketStorage cannot be null.");if (this.timer == null) {this.timer = new Timer(true);}if (this.timerTask == null) {this.timerTask = new CleanUpTimerTask(this.proxyGrantingTicketStorage);}this.timer.schedule(this.timerTask, this.millisBetweenCleanUps, this.millisBetweenCleanUps);}/*** Constructs a Cas20ServiceTicketValidator or a Cas20ProxyTicketValidator based on supplied parameters.** @param filterConfig the Filter Configuration object.* @return a fully constructed TicketValidator.*/@Overrideprotected final TicketValidator getTicketValidator(final FilterConfig filterConfig) {final String allowAnyProxy = getPropertyFromInitParams(filterConfig, "acceptAnyProxy", null);final String allowedProxyChains = getPropertyFromInitParams(filterConfig, "allowedProxyChains", null);final String casServerUrlPrefix = validateServer ;final Cas20ServiceTicketValidator validator;if (CommonUtils.isNotBlank(allowAnyProxy) || CommonUtils.isNotBlank(allowedProxyChains)) {final Cas20ProxyTicketValidator v = new Cas20ProxyTicketValidator(casServerUrlPrefix);v.setAcceptAnyProxy(parseBoolean(allowAnyProxy));v.setAllowedProxyChains(CommonUtils.createProxyList(allowedProxyChains));validator = v;} else {validator = new Cas20ServiceTicketValidator(casServerUrlPrefix);}validator.setProxyCallbackUrl(getPropertyFromInitParams(filterConfig, "proxyCallbackUrl", null));validator.setProxyGrantingTicketStorage(this.proxyGrantingTicketStorage);validator.setProxyRetriever(new Cas20ProxyRetriever(casServerUrlPrefix, getPropertyFromInitParams(filterConfig, "encoding", null)));validator.setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false")));validator.setEncoding(getPropertyFromInitParams(filterConfig, "encoding", "UTF-8"));final Map<String, String> additionalParameters = new HashMap<String, String>();final List<String> params = Arrays.asList(RESERVED_INIT_PARAMS);for (final Enumeration<?> e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {final String s = (String) e.nextElement();if (!params.contains(s)) {additionalParameters.put(s, filterConfig.getInitParameter(s));}}validator.setCustomParameters(additionalParameters);validator.setHostnameVerifier(getHostnameVerifier(filterConfig));return validator;}@Overridepublic void destroy() {super.destroy();this.timer.cancel();}/*** This processes the ProxyReceptor request before the ticket validation code executes.*/@Overrideprotected final boolean preFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {final HttpServletRequest request = (HttpServletRequest) servletRequest;final HttpServletResponse response = (HttpServletResponse) servletResponse;final String requestUri = request.getRequestURI();if (CommonUtils.isEmpty(this.proxyReceptorUrl) || !requestUri.endsWith(this.proxyReceptorUrl)) {return true;}try {CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage);} catch (final RuntimeException e) {log.error(e.getMessage(), e);throw e;}return false;}public final void setProxyReceptorUrl(final String proxyReceptorUrl) {this.proxyReceptorUrl = proxyReceptorUrl;}public void setProxyGrantingTicketStorage(final ProxyGrantingTicketStorage storage) {this.proxyGrantingTicketStorage = storage;}public void setTimer(final Timer timer) {this.timer = timer;}public void setTimerTask(final TimerTask timerTask) {this.timerTask = timerTask;}public void setMillisBetweenCleanUps(final int millisBetweenCleanUps) {this.millisBetweenCleanUps = millisBetweenCleanUps;}@Overrideprotected void onSuccessfulValidation(HttpServletRequest request, HttpServletResponse response,Assertion assertion) {}}这个里面的
@Value("${cas.appUrl}")@Value("${cas.url}")这两个是yml文件里面的,url是cas登录界面的地址,appUrl是自己系统的地址举个例子吧
cas: url: https://域名或者ip/authserver appUrl: http://域名或者ip/prod-api/
controller
@GetMapping("/cas/ascLogin") public void loginByNameAndCardNo(HttpServletRequest request, HttpServletResponse response) {Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);String loginName = null;if (assertion != null) {AttributePrincipal principal = assertion.getPrincipal();loginName = principal.getName();System.out.println("访问者:" + loginName);}SysUser user = new SysUser();user.setUserName(loginName);SysUser sysUser = sysUserService.selectUserByUserName(user.getUserName());if (null == sysUser){throw new RuntimeException("当前用户" + loginName + "在系统中不存在");}// 校验用户信息并返回String token = sysLoginService.ssoLogin(sysUser.getUserName(), sysUser.getPassword(), null, null);log.info("token--------------" + token);if (ObjectUtil.isNotEmpty(sysUser) && token !=null){try {String portal = CacheUtils.get(SYS_CONFIG, "sys.config.portal");response.sendRedirect(portal + token);} catch (IOException e) {e.printStackTrace();}} }这个里面的 String portal = CacheUtils.get(SYS_CONFIG, "sys.config.portal");,这个是属于自己系统的地址与token的拼接地址,举个例子:http://域名或者ip/?token=