前后端分离后台基于springboot,shiro,auth2,前端vue集成cas

增加三个拦截

package kwc.app.filter;



import kwc.app.common.enums.NoLoginEnum;
import kwc.app.common.utils.RedisUtils;
import org.jasig.cas.client.Protocol;
import org.jasig.cas.client.configuration.ConfigurationKeys;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.ReflectUtils;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;

import javax.net.ssl.HostnameVerifier;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

/**
 * Created by fengjian on 2018/7/31.
 */
public abstract class AbstractTicketValidationFilterImpl extends AbstractCasFilter {
    private TicketValidator ticketValidator;
    private boolean redirectAfterValidation = true;
    private boolean exceptionOnValidationFailure = false;
    private boolean useSession = true;
    private RedisUtils redisUtils;

    protected AbstractTicketValidationFilterImpl(Protocol protocol, RedisUtils redisUtils) {
        super(protocol);
        this.redisUtils=redisUtils;
    }

    protected TicketValidator getTicketValidator(FilterConfig filterConfig) {
        return this.ticketValidator;
    }

    protected Properties getSSLConfig() {
        Properties properties = new Properties();
        String fileName = this.getString(ConfigurationKeys.SSL_CONFIG_FILE);
        if (fileName != null) {
            FileInputStream fis = null;

            try {
                fis = new FileInputStream(fileName);
                properties.load(fis);
                this.logger.trace("Loaded {} entries from {}", Integer.valueOf(properties.size()), fileName);
            } catch (IOException var8) {
                this.logger.error(var8.getMessage(), var8);
            } finally {
                CommonUtils.closeQuietly(fis);
            }
        }

        return properties;
    }

    protected HostnameVerifier getHostnameVerifier() {
        Class className = this.getClass(ConfigurationKeys.HOSTNAME_VERIFIER);
        String config = this.getString(ConfigurationKeys.HOSTNAME_VERIFIER_CONFIG);
        return className != null ? (config != null ? (HostnameVerifier) ReflectUtils.newInstance(className, new Object[]{config}) : (HostnameVerifier) ReflectUtils.newInstance(className, new Object[0])) : null;
    }

    protected void initInternal(FilterConfig filterConfig) throws ServletException {
        this.setExceptionOnValidationFailure(this.getBoolean(ConfigurationKeys.EXCEPTION_ON_VALIDATION_FAILURE));
        this.setRedirectAfterValidation(this.getBoolean(ConfigurationKeys.REDIRECT_AFTER_VALIDATION));
        this.setUseSession(this.getBoolean(ConfigurationKeys.USE_SESSION));
        if (!this.useSession && this.redirectAfterValidation) {
            this.logger.warn("redirectAfterValidation parameter may not be true when useSession parameter is false. Resetting it to false in order to prevent infinite redirects.");
            this.setRedirectAfterValidation(false);
        }

        this.setTicketValidator(this.getTicketValidator(filterConfig));
        super.initInternal(filterConfig);
    }

    public void init() {
        super.init();
        CommonUtils.assertNotNull(this.ticketValidator, "ticketValidator cannot be null.");
    }

    protected boolean preFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        return true;
    }

    protected void onFailedValidation(HttpServletRequest request, HttpServletResponse response) {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (this.preFilter(servletRequest, servletResponse, filterChain)) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String ticket = this.retrieveTicketFromRequest(request);
            if (CommonUtils.isNotBlank(ticket)) {
                this.logger.debug("Attempting to validate ticket: {}", ticket);

                try {
                    Assertion e = this.ticketValidator.validate(ticket, this.constructServiceUrl(request, response));
                    this.logger.debug("Successfully authenticated user: {}", e.getPrincipal().getName());
                    request.setAttribute("_const_cas_assertion_", e);
                    if (this.useSession) {
                        request.getSession().setAttribute("_const_cas_assertion_", e);
                    }

                    this.onSuccessfulValidation(request, response, e);
                    if (this.redirectAfterValidation) {
                        this.logger.debug("Redirecting after successful ticket validation.");
                        response.sendRedirect(this.constructServiceUrl(request, response));
                        return;
                    }
                } catch (TicketValidationException var8) {
                    this.logger.debug(var8.getMessage(), var8);
                    this.onFailedValidation(request, response);
                    PrintWriter printWriter = servletResponse.getWriter();
                    printWriter.write("{\"status\":40199,\"data\":" + NoLoginEnum.NO_LOGIN.getMsg() + ",\"message\":\"no login\",\"cas_cookie\":\"\"}");
                    return;
                }
            }
            filterChain.doFilter(request, response);
        }
    }


    protected void onSuccessfulValidation(HttpServletRequest request, HttpServletResponse response, Assertion assertion) {
        try {
            logger.info("通过ticket验证跳转到首页");
            String sessionId=request.getSession().getId();
            logger.info("========sessionId========="+sessionId);
            Object refer = redisUtils.hashGet("sessionIds", sessionId);
            if(refer!=null){
                redisUtils.hashRemove("sessionIds", sessionId);
                response.sendRedirect(String.valueOf(refer));
                logger.info("========threadLocal.set(referer)========" + String.valueOf(refer) + "=========================");
            }else{
                response.sendRedirect(NoLoginEnum.INDEX.getMsg());
            }
            setRedirectAfterValidation(false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public final void setTicketValidator(TicketValidator ticketValidator) {
        this.ticketValidator = ticketValidator;
    }

    public final void setRedirectAfterValidation(boolean redirectAfterValidation) {
        this.redirectAfterValidation = redirectAfterValidation;
    }

    public final void setExceptionOnValidationFailure(boolean exceptionOnValidationFailure) {
        this.exceptionOnValidationFailure = exceptionOnValidationFailure;
    }

    public final void setUseSession(boolean useSession) {
        this.useSession = useSession;
    }
}
package kwc.app.filter;

import kwc.app.common.enums.NoLoginEnum;
import kwc.app.common.utils.RedisUtils;
import org.apache.commons.lang.StringUtils;
import org.jasig.cas.client.Protocol;
import org.jasig.cas.client.authentication.*;
import org.jasig.cas.client.configuration.ConfigurationKeys;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.util.AssertionHolder;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.ReflectUtils;
import org.jasig.cas.client.validation.Assertion;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class AuthenticationFilterImpl extends AbstractCasFilter {
    private RedisUtils redisUtils;
    private String casServerLoginUrl;
    private boolean renew;
    private boolean gateway;
    private GatewayResolver gatewayStorage;
    private AuthenticationRedirectStrategy authenticationRedirectStrategy;
    private UrlPatternMatcherStrategy ignoreUrlPatternMatcherStrategyClass;
    private static final Map> PATTERN_MATCHER_TYPES = new HashMap();

    public AuthenticationFilterImpl(RedisUtils redisUtils) {
        this(Protocol.CAS2);
        this.redisUtils = redisUtils;
    }


    protected AuthenticationFilterImpl(Protocol protocol) {
        super(protocol);
        this.renew = false;
        this.gateway = false;
        this.gatewayStorage = new DefaultGatewayResolverImpl();
        this.authenticationRedirectStrategy = new DefaultAuthenticationRedirectStrategy();
        this.ignoreUrlPatternMatcherStrategyClass = null;
    }

    protected void initInternal(FilterConfig filterConfig) throws ServletException {
        if (!this.isIgnoreInitConfiguration()) {
            super.initInternal(filterConfig);
            this.setCasServerLoginUrl(this.getString(ConfigurationKeys.CAS_SERVER_LOGIN_URL));
            this.setRenew(this.getBoolean(ConfigurationKeys.RENEW));
            this.setGateway(this.getBoolean(ConfigurationKeys.GATEWAY));
            String ignorePattern = this.getString(ConfigurationKeys.IGNORE_PATTERN);
            String ignoreUrlPatternType = this.getString(ConfigurationKeys.IGNORE_URL_PATTERN_TYPE);
            Class gatewayStorageClass;
            if (ignorePattern != null) {
                gatewayStorageClass = (Class) PATTERN_MATCHER_TYPES.get(ignoreUrlPatternType);
                if (gatewayStorageClass != null) {
                    this.ignoreUrlPatternMatcherStrategyClass = (UrlPatternMatcherStrategy) ReflectUtils.newInstance(gatewayStorageClass.getName(), new Object[0]);
                } else {
                    try {
                        this.logger.trace("Assuming {} is a qualified class name...", ignoreUrlPatternType);
                        this.ignoreUrlPatternMatcherStrategyClass = (UrlPatternMatcherStrategy) ReflectUtils.newInstance(ignoreUrlPatternType, new Object[0]);
                    } catch (IllegalArgumentException var6) {
                        this.logger.error("Could not instantiate class [{}]", ignoreUrlPatternType, var6);
                    }
                }

                if (this.ignoreUrlPatternMatcherStrategyClass != null) {
                    this.ignoreUrlPatternMatcherStrategyClass.setPattern(ignorePattern);
                }
            }

            gatewayStorageClass = this.getClass(ConfigurationKeys.GATEWAY_STORAGE_CLASS);
            if (gatewayStorageClass != null) {
                this.setGatewayStorage((GatewayResolver) ReflectUtils.newInstance(gatewayStorageClass, new Object[0]));
            }

            Class authenticationRedirectStrategyClass = this.getClass(ConfigurationKeys.AUTHENTICATION_REDIRECT_STRATEGY_CLASS);
            if (authenticationRedirectStrategyClass != null) {
                this.authenticationRedirectStrategy = (AuthenticationRedirectStrategy) ReflectUtils.newInstance(authenticationRedirectStrategyClass, new Object[0]);
            }
        }

    }

    public void init() {
        super.init();
        CommonUtils.assertNotNull(this.casServerLoginUrl, "casServerLoginUrl cannot be null.");
    }

    public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        if (this.isRequestUrlExcluded(request) || (!StringUtils.isBlank(requestURI) && requestURI.contains("/api/sqlOnline/"))) {
            this.logger.debug("Request is ignored.");
            filterChain.doFilter(request, response);
        } else {
            HttpSession session = request.getSession(false);
            Assertion assertion = session != null ? (Assertion) session.getAttribute("_const_cas_assertion_") : null;

            if (assertion != null) {
                filterChain.doFilter(request, response);
            } else {
                String serviceUrl = this.constructServiceUrl(request, response);
                String ticket = this.retrieveTicketFromRequest(request);
                boolean wasGatewayed = this.gateway && this.gatewayStorage.hasGatewayedAlready(request, serviceUrl);
                if (!CommonUtils.isNotBlank(ticket) && !wasGatewayed) {
                    this.logger.debug("no ticket and no assertion found");
                    String modifiedServiceUrl;
                    if (this.gateway) {
                        this.logger.debug("setting gateway attribute in session");
                        modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl);
                    } else {
                        modifiedServiceUrl = serviceUrl;
                    }
                    //新添加
                    String sessionId = request.getSession().getId();
                    String referer = request.getHeader("referer");
                    logger.info("========referer=========" + referer);
                    if (!StringUtils.isBlank(referer)) {
                        redisUtils.hashPut("sessionIds",sessionId,referer);
                    } else {
                        redisUtils.hashPut("sessionIds",sessionId, NoLoginEnum.INDEX.getMsg());
                    }
                    //新添加
                    this.logger.debug("Constructed service url: {}", modifiedServiceUrl);
                    String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, this.getProtocol().getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway);
                    this.logger.debug("redirecting to \"{}\"", urlToRedirectTo);
                    PrintWriter printWriter = servletResponse.getWriter();
                    printWriter.write("{\"status\":40199,\"data\":" + "\"" + urlToRedirectTo + "\"" + ",\"message\":\"no login\",\"cas_cookie\":\"\"}");                    //this.authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo);

                } else {

                    filterChain.doFilter(request, response);
                }
            }
        }
    }

    public final void setRenew(boolean renew) {
        this.renew = renew;
    }

    public final void setGateway(boolean gateway) {
        this.gateway = gateway;
    }

    public final void setCasServerLoginUrl(String casServerLoginUrl) {
        this.casServerLoginUrl = casServerLoginUrl;
    }

    public final void setGatewayStorage(GatewayResolver gatewayStorage) {
        this.gatewayStorage = gatewayStorage;
    }

    private boolean isRequestUrlExcluded(HttpServletRequest request) {
        if (this.ignoreUrlPatternMatcherStrategyClass == null) {
            return false;
        } else {
            StringBuffer urlBuffer = request.getRequestURL();
            if (request.getQueryString() != null) {
                urlBuffer.append("?").append(request.getQueryString());
            }

            String requestUri = urlBuffer.toString();
            return this.ignoreUrlPatternMatcherStrategyClass.matches(requestUri);
        }
    }

    static {
        PATTERN_MATCHER_TYPES.put("CONTAINS", ContainsPatternUrlPatternMatcherStrategy.class);
        PATTERN_MATCHER_TYPES.put("REGEX", RegexUrlPatternMatcherStrategy.class);
        PATTERN_MATCHER_TYPES.put("EXACT", ExactUrlPatternMatcherStrategy.class);
    }
}
package kwc.app.filter;

import kwc.app.common.utils.RedisUtils;
import org.jasig.cas.client.Protocol;
import org.jasig.cas.client.configuration.ConfigurationKeys;
import org.jasig.cas.client.proxy.*;
import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
import org.jasig.cas.client.ssl.HttpsURLConnectionFactory;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.ReflectUtils;
import org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter;
import org.jasig.cas.client.validation.Cas20ProxyTicketValidator;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidator;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static org.jasig.cas.client.configuration.ConfigurationKeys.*;

/**
 * Creates either a CAS20ProxyTicketValidator or a CAS20ServiceTicketValidator depending on whether any of the
 * proxy parameters are set.
 * 

* This filter can also pass additional parameters to the ticket validator. Any init parameter not included in the * reserved list {@link Cas20ProxyReceivingTicketValidationFilter#RESERVED_INIT_PARAMS}. * * @author Scott Battaglia * @author Brad Cupit (brad [at] lsu {dot} edu) * @version $Revision$ $Date$ * @since 3.1 */ public class Cas20ProxyReceivingTicketValidationFilterImpl extends AbstractTicketValidationFilterImpl { private static final String[] RESERVED_INIT_PARAMS = new String[]{ARTIFACT_PARAMETER_NAME.getName(), SERVER_NAME.getName(), SERVICE.getName(), RENEW.getName(), LOGOUT_PARAMETER_NAME.getName(), ARTIFACT_PARAMETER_OVER_POST.getName(), EAGERLY_CREATE_SESSIONS.getName(), ENCODE_SERVICE_URL.getName(), SSL_CONFIG_FILE.getName(), ROLE_ATTRIBUTE.getName(), IGNORE_CASE.getName(), CAS_SERVER_LOGIN_URL.getName(), GATEWAY.getName(), AUTHENTICATION_REDIRECT_STRATEGY_CLASS.getName(), GATEWAY_STORAGE_CLASS.getName(), CAS_SERVER_URL_PREFIX.getName(), ENCODING.getName(), TOLERANCE.getName(), IGNORE_PATTERN.getName(), IGNORE_URL_PATTERN_TYPE.getName(), HOSTNAME_VERIFIER.getName(), HOSTNAME_VERIFIER_CONFIG.getName(), EXCEPTION_ON_VALIDATION_FAILURE.getName(), REDIRECT_AFTER_VALIDATION.getName(), USE_SESSION.getName(), SECRET_KEY.getName(), CIPHER_ALGORITHM.getName(), PROXY_RECEPTOR_URL.getName(), PROXY_GRANTING_TICKET_STORAGE_CLASS.getName(), MILLIS_BETWEEN_CLEAN_UPS.getName(), ACCEPT_ANY_PROXY.getName(), ALLOWED_PROXY_CHAINS.getName(), TICKET_VALIDATOR_CLASS.getName(), PROXY_CALLBACK_URL.getName(), FRONT_LOGOUT_PARAMETER_NAME.getName(), RELAY_STATE_PARAMETER_NAME.getName() }; /** * 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; protected Class defaultServiceTicketValidatorClass; protected Class defaultProxyTicketValidatorClass; /** * Storage location of ProxyGrantingTickets and Proxy Ticket IOUs. */ private ProxyGrantingTicketStorage proxyGrantingTicketStorage = new ProxyGrantingTicketStorageImpl(); public Cas20ProxyReceivingTicketValidationFilterImpl(RedisUtils redisUtils) { this(Protocol.CAS2,redisUtils); this.defaultServiceTicketValidatorClass = Cas20ServiceTicketValidator.class; this.defaultProxyTicketValidatorClass = Cas20ProxyTicketValidator.class; } protected Cas20ProxyReceivingTicketValidationFilterImpl(final Protocol protocol, RedisUtils redisUtils) { super(protocol,redisUtils); } protected void initInternal(final FilterConfig filterConfig) throws ServletException { setProxyReceptorUrl(getString(ConfigurationKeys.PROXY_RECEPTOR_URL)); final Class proxyGrantingTicketStorageClass = getClass(ConfigurationKeys.PROXY_GRANTING_TICKET_STORAGE_CLASS); if (proxyGrantingTicketStorageClass != null) { this.proxyGrantingTicketStorage = ReflectUtils.newInstance(proxyGrantingTicketStorageClass); if (this.proxyGrantingTicketStorage instanceof AbstractEncryptedProxyGrantingTicketStorageImpl) { final AbstractEncryptedProxyGrantingTicketStorageImpl p = (AbstractEncryptedProxyGrantingTicketStorageImpl) this.proxyGrantingTicketStorage; final String cipherAlgorithm = getString(ConfigurationKeys.CIPHER_ALGORITHM); final String secretKey = getString(ConfigurationKeys.SECRET_KEY); p.setCipherAlgorithm(cipherAlgorithm); try { if (secretKey != null) { p.setSecretKey(secretKey); } } catch (final Exception e) { throw new RuntimeException(e); } } } this.millisBetweenCleanUps = getInt(ConfigurationKeys.MILLIS_BETWEEN_CLEAN_UPS); super.initInternal(filterConfig); } public 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); } private T createNewTicketValidator(final Class ticketValidatorClass, final String casServerUrlPrefix, final Class clazz) { if (ticketValidatorClass == null) { return ReflectUtils.newInstance(clazz, casServerUrlPrefix); } return (T) ReflectUtils.newInstance(ticketValidatorClass, casServerUrlPrefix); } /** * Constructs a Cas20ServiceTicketValidator or a Cas20ProxyTicketValidator based on supplied parameters. * * @param filterConfig the Filter Configuration object. * @return a fully constructed TicketValidator. */ protected final TicketValidator getTicketValidator(final FilterConfig filterConfig) { final boolean allowAnyProxy = getBoolean(ConfigurationKeys.ACCEPT_ANY_PROXY); final String allowedProxyChains = getString(ConfigurationKeys.ALLOWED_PROXY_CHAINS); final String casServerUrlPrefix = getString(ConfigurationKeys.CAS_SERVER_URL_PREFIX); final Class ticketValidatorClass = getClass(ConfigurationKeys.TICKET_VALIDATOR_CLASS); final Cas20ServiceTicketValidator validator; if (allowAnyProxy || CommonUtils.isNotBlank(allowedProxyChains)) { final Cas20ProxyTicketValidator v = createNewTicketValidator(ticketValidatorClass, casServerUrlPrefix, this.defaultProxyTicketValidatorClass); v.setAcceptAnyProxy(allowAnyProxy); v.setAllowedProxyChains(CommonUtils.createProxyList(allowedProxyChains)); validator = v; } else { validator = createNewTicketValidator(ticketValidatorClass, casServerUrlPrefix, this.defaultServiceTicketValidatorClass); } validator.setProxyCallbackUrl(getString(ConfigurationKeys.PROXY_CALLBACK_URL)); validator.setProxyGrantingTicketStorage(this.proxyGrantingTicketStorage); final HttpURLConnectionFactory factory = new HttpsURLConnectionFactory(getHostnameVerifier(), getSSLConfig()); validator.setURLConnectionFactory(factory); validator.setProxyRetriever(new Cas20ProxyRetriever(casServerUrlPrefix, getString(ConfigurationKeys.ENCODING), factory)); validator.setRenew(getBoolean(ConfigurationKeys.RENEW)); validator.setEncoding(getString(ConfigurationKeys.ENCODING)); final Map additionalParameters = new HashMap(); final List 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); return validator; } public void destroy() { super.destroy(); this.timer.cancel(); } /** * This processes the ProxyReceptor request before the ticket validation code executes. */ protected 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) { logger.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; } }

cas config

package kwc.app.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

@ConfigurationProperties(prefix = "cas")
public class CasConfig {
    /**
     * CAS server URL E.g. https://example.com/cas or https://cas.example. Required.
     */
    @NotNull
    private String serverUrlPrefix;

    /**
     * CAS server login URL E.g. https://example.com/cas/login or https://cas.example/login. Required.
     */
    @NotNull
    private String serverLoginUrl;

    /**
     *
     */
    private boolean loginFilterEnable = true;

    /**
     * ajax 的请求标志值
     */
    private String ajaxFlag = "XMLHttpRequest";

    /**
     * 需要登陆的时候的 response 数据的状态码
     */
    private int needLoginCode = 409;

    /**
     * 登陆失败页面地址
     */
    @NotNull
    private String loginFailureUrl;

    //    @NotNull
    private String serverLogoutUrl;

    /**
     * CAS-protected client application host URL E.g. https://myclient.example.com Required.
     */
    @NotNull
    private String clientHostUrl;
    static final String separator = ",";

    private String validateFilters = "/*";
    private String signOutFilters = "/logout";
    private String authFilters = "/*";
    private String assertionFilters = "/*";
    private String requestWrapperFilters = "/*";

    @NotNull
    private String serverName;
    private boolean useSession = true;
    private boolean redirectAfterValidation = true;

    public List getValidateFilters() {
        return Arrays.asList(validateFilters.split(separator));
    }

    public void setValidateFilters(String validateFilters) {
        this.validateFilters = validateFilters;
    }

    public List getSignOutFilters() {
        return Arrays.asList(signOutFilters.split(separator));
    }

    public void setSignOutFilters(String signOutFilters) {
        this.signOutFilters = signOutFilters;
    }

    public List getAuthFilters() {
        return Arrays.asList(authFilters.split(separator));
    }

    public void setAuthFilters(String authFilters) {
        this.authFilters = authFilters;
    }

    public List getAssertionFilters() {
        return Arrays.asList(assertionFilters.split(separator));
    }

    public void setAssertionFilters(String assertionFilters) {
        this.assertionFilters = assertionFilters;
    }

    public List getRequestWrapperFilters() {
        return Arrays.asList(requestWrapperFilters.split(separator));
    }

    public void setRequestWrapperFilters(String requestWrapperFilters) {
        this.requestWrapperFilters = requestWrapperFilters;
    }

    public String getServerName() {
        return serverName;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public boolean isRedirectAfterValidation() {
        return redirectAfterValidation;
    }

    public void setRedirectAfterValidation(boolean redirectAfterValidation) {
        this.redirectAfterValidation = redirectAfterValidation;
    }

    public boolean isUseSession() {
        return useSession;
    }

    public void setUseSession(boolean useSession) {
        this.useSession = useSession;
    }

    public String getServerUrlPrefix() {
        return serverUrlPrefix;
    }

    public void setServerUrlPrefix(String serverUrlPrefix) {
        this.serverUrlPrefix = serverUrlPrefix;
    }

    public String getServerLoginUrl() {
        return serverLoginUrl;
    }

    public void setServerLoginUrl(String serverLoginUrl) {
        this.serverLoginUrl = serverLoginUrl;
    }

    public String getClientHostUrl() {
        return clientHostUrl;
    }

    public void setClientHostUrl(String clientHostUrl) {
        this.clientHostUrl = clientHostUrl;
    }

    public boolean isLoginFilterEnable() {
        return loginFilterEnable;
    }

    public void setLoginFilterEnable(boolean loginFilterEnable) {
        this.loginFilterEnable = loginFilterEnable;
    }

    public String getAjaxFlag() {
        return ajaxFlag;
    }

    public void setAjaxFlag(String ajaxFlag) {
        this.ajaxFlag = ajaxFlag;
    }

    public int getNeedLoginCode() {
        return needLoginCode;
    }

    public void setNeedLoginCode(int needLoginCode) {
        this.needLoginCode = needLoginCode;
    }

    public String getLoginFailureUrl() {
        return loginFailureUrl;
    }

    public void setLoginFailureUrl(String loginFailureUrl) {
        this.loginFailureUrl = loginFailureUrl;
    }

    public String getServerLogoutUrl() {
        return serverLogoutUrl;
    }

    public void setServerLogoutUrl(String serverLogoutUrl) {
        this.serverLogoutUrl = serverLogoutUrl;
    }
}

 

package kwc.app.config;

import kwc.app.common.utils.RedisUtils;
import kwc.app.filter.AuthenticationFilterImpl;
import kwc.app.filter.Cas20ProxyReceivingTicketValidationFilterImpl;
import org.jasig.cas.client.util.AssertionThreadLocalFilter;
import org.jasig.cas.client.util.HttpServletRequestWrapperFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class FilterCasConfig {
    @Autowired
    CasConfig autoconfig;
    @Autowired
    private RedisUtils redisUtils;

    private static boolean casEnabled  = true;

    public FilterCasConfig() {
    }

    @Bean
    public CasConfig getSpringCasAutoconfig(){
        return new CasConfig();
    }
    /**
     * 该过滤器负责用户的认证工作
     */
    @Bean
    public FilterRegistrationBean authenticationFilter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        filterRegistration.setFilter(new AuthenticationFilterImpl(redisUtils));
        filterRegistration.setEnabled(casEnabled);
        if(autoconfig.getAuthFilters().size()>0)
            filterRegistration.setUrlPatterns(autoconfig.getAuthFilters());
        else
            filterRegistration.addUrlPatterns("/*");
        //serverLoginUrl:cas服务的登陆url
        filterRegistration.addInitParameter("casServerLoginUrl", autoconfig.getServerLoginUrl());
        //本项目登录ip+port
        filterRegistration.addInitParameter("serverName", autoconfig.getServerName());
        filterRegistration.addInitParameter("useSession", autoconfig.isUseSession()?"true":"false");
        filterRegistration.addInitParameter("redirectAfterValidation", autoconfig.isRedirectAfterValidation()?"true":"false");
        filterRegistration.setOrder(1);
        return filterRegistration;
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration =  new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("true");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",buildConfig());
        return new CorsFilter(source);
    }

    /**
     * 该过滤器负责对Ticket的校验工作
     */
   /* @Bean
    public FilterRegistrationBean cas20ProxyReceivingTicketValidationFilter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        Cas20ProxyReceivingTicketValidationFilter cas20ProxyReceivingTicketValidationFilter = new Cas20ProxyReceivingTicketValidationFilter();
        cas20ProxyReceivingTicketValidationFilter.setServerName(autoconfig.getServerName());
        filterRegistration.setFilter(cas20ProxyReceivingTicketValidationFilter);
        filterRegistration.setEnabled(casEnabled);
        if(autoconfig.getValidateFilters().size()>0)
            filterRegistration.setUrlPatterns(autoconfig.getValidateFilters());
        else
            filterRegistration.addUrlPatterns("/*");
        filterRegistration.addInitParameter("casServerUrlPrefix", autoconfig.getServerUrlPrefix());
        filterRegistration.addInitParameter("serverName", autoconfig.getServerName());
        filterRegistration.setOrder(2);
        return filterRegistration;
    }*/
    @Bean
    public FilterRegistrationBean cas20ProxyReceivingTicketValidationFilter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        Cas20ProxyReceivingTicketValidationFilterImpl cas20ProxyReceivingTicketValidationFilter = new Cas20ProxyReceivingTicketValidationFilterImpl(redisUtils);
        cas20ProxyReceivingTicketValidationFilter.setServerName(autoconfig.getServerName());
        filterRegistration.setFilter(cas20ProxyReceivingTicketValidationFilter);
        filterRegistration.setEnabled(casEnabled);
        if(autoconfig.getValidateFilters().size()>0)
            filterRegistration.setUrlPatterns(autoconfig.getValidateFilters());
        else
            filterRegistration.addUrlPatterns("/*");
        filterRegistration.addInitParameter("casServerUrlPrefix", autoconfig.getServerUrlPrefix());
        filterRegistration.addInitParameter("serverName", autoconfig.getServerName());
        filterRegistration.setOrder(2);
        return filterRegistration;
    }


    /**
     * 该过滤器对HttpServletRequest请求包装, 可通过HttpServletRequest的getRemoteUser()方法获得登录用户的登录名
     *
     */
    @Bean
    public FilterRegistrationBean httpServletRequestWrapperFilter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        filterRegistration.setFilter(new HttpServletRequestWrapperFilter());
        filterRegistration.setEnabled(true);
        if(autoconfig.getRequestWrapperFilters().size()>0)
            filterRegistration.setUrlPatterns(autoconfig.getRequestWrapperFilters());
        else
            filterRegistration.addUrlPatterns("/*");
        filterRegistration.setOrder(3);
        return filterRegistration;
    }

    /**
     * 该过滤器使得可以通过org.jasig.cas.client.util.AssertionHolder来获取用户的登录名。
     比如AssertionHolder.getAssertion().getPrincipal().getName()。
     这个类把Assertion信息放在ThreadLocal变量中,这样应用程序不在web层也能够获取到当前登录信息
     */
    @Bean
    public FilterRegistrationBean assertionThreadLocalFilter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        filterRegistration.setFilter(new AssertionThreadLocalFilter());
        filterRegistration.setEnabled(true);
        if(autoconfig.getAssertionFilters().size()>0)
            filterRegistration.setUrlPatterns(autoconfig.getAssertionFilters());
        else
            filterRegistration.addUrlPatterns("/*");
        filterRegistration.setOrder(4);
        return filterRegistration;
    }

    @Bean
    public TaskExecutor taskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(50);
        return executor;
    }

    @Bean
    public TaskScheduler taskScheduler() {

        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        return scheduler;
    }
}

跨域

package kwc.app.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @program: IntelligentDrainageSystem-app
 * @description:
 * @author: WangBin
 * @create: 2019-04-29 10:26
 **/

@Configuration
@Order(value=0) //value设置为0,执行顺序优先
@WebFilter(filterName = "CorsFilterConfig", urlPatterns = "/*")
public class CorsFilterConfig implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("===============CorsFilterConfig执行=================");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        //支持跨域请求

        String []  allowDomain= {"http://101.81.124.154:3003","http://101.81.124.154:8000"}; //多域名形式
        Set allowedOrigins= new HashSet<>(Arrays.asList(allowDomain));
        String originHeader=((HttpServletRequest) servletRequest).getHeader("Origin");
        if (allowedOrigins.contains(originHeader)) {
            res.setHeader("Access-Control-Allow-Origin", originHeader);
            res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
            res.setHeader("Access-Control-Allow-Credentials", "true");
            res.setHeader("Access-Control-Max-Age", "1728000");
            res.setHeader("Access-Control-Allow-Headers", "Authentication, Authorization, content-type, Accept, x-requested-with, Cache-Control,token");
        }
        filterChain.doFilter(servletRequest, res);
    }
    @Override
    public void destroy() {}

}

在application.yml配置

cas:
  serverUrlPrefix: http://xxx.xxx.xxx.xxx:8989
  service: http://xxx.xxx.xxx.xxx:8989
  serverLogoutUrl:  http://xxx.xxx.xxx.xxx:8989/logout
  serverLoginUrl: http://xxx.xxx.xxx.xxx:8989/login
  loginFailureUrl: http://xxx.xxx.xxx.xxx:8989/logout
  clientHostUrl: "http://xxx.xxx.xxx.xxx:8888/IntelligentDrainageSystem-app/"
  serverName: http://xxx.xxx.xxx.xxx:8888/IntelligentDrainageSystem-app/

你可能感兴趣的:(java,cas,java,前后端分离集成cas,cas服务,shiro)