龙空技术网

SpringBoot接入CAS的问题解决

COPY侠 601

前言:

而今咱们对“nginx代理cas”都比较关怀,兄弟们都需要了解一些“nginx代理cas”的相关资讯。那么小编也在网上搜集了一些对于“nginx代理cas””的相关资讯,希望小伙伴们能喜欢,各位老铁们一起来了解一下吧!

项目背景前后端分离负载均衡gateway转发使用

基于springboot

<dependency>  <groupId>org.jasig.cas.client</groupId>  <artifactId>cas-client-support-springboot</artifactId>  <version>3.6.1</version></dependency>

基本的接入

    // 注册验证bean@Beanpublic FilterRegistrationBean filterAuthenticationRegistration() {    FilterRegistrationBean registration = new FilterRegistrationBean();    registration.setFilter(new AuthenticationFilter());    registration.addUrlPatterns("/*");    Map<String, String> initParameters = new HashMap<String, String>(3);    initParameters.put("casServerLoginUrl", casProperties.getCasServerUrl());    initParameters.put("serverName", casProperties.getClientHostUrl());    // 自定义重定向策略    initParameters.put("authenticationRedirectStrategyClass", "package.CustomAuthenticationRedirectStrategy");    initParameters.put("ignorePattern", casProperties.getIgnoreUrl());    registration.setInitParameters(initParameters);    registration.setOrder(1);    return registration;}

配置信息

cas:  server-url-prefix:   server-login-url:   client-host-url:  // cas服务器通过这个关联ticket信息,需要保证后续请求cas服务器的host都是这个  validation-type: CAS

接入中遇到的问题

前后端分离未登录情况下,前端处理重定向地址

通过自定义重定向策略实现返回json给前端值跳转,与前端约定规则做跳转即可

public class CustomAuthenticationRedirectStrategy implements AuthenticationRedirectStrategy {    @Override    public void redirect(final HttpServletRequest request, final HttpServletResponse response,                         final String potentialRedirectUrl) throws IOException {            CasProperties casProperties = SpringUtils.getBean("casProperties", CasProperties.class);            response.setContentType("application/json");            response.setStatus(401);            BaseResponse baseResponse = BaseResponse.success();            baseResponse.setCode(10401);            Map<String, String> re = new HashMap<>(2);            // 封转 返回重定向地址:cas登录的地址,service 为后端接口,用作登录成功后跳转到前端页面逻辑处理            re.put("redirect", casProperties.getCasServerLoginUrl() + "?service=" + casProperties.getClientHostUrl()+"/cas");            baseResponse.setData(re);            try (                    final PrintWriter writer = response.getWriter()            ) {                writer.write(new ObjectMapper().writeValueAsString(baseResponse));                writer.flush();            }    }}
负载均衡

由于cas是使用session做票据的存储,当架构为nginx负载多台服务器情况下,需要做session共享处理,否则一台机子有票据信息,一台没有,当同一个用的的请求负载到不同服务器会出现登录失败情况。

gateway 条状的架构

gateway条状的情况下使用的服务调用,目前的实现方式都是调用注册中心的服务列表,使用ip:port的形式调用。查看源码AbstractTicketValidationFilter源码

  @Override    public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,                               final FilterChain filterChain) throws IOException, ServletException {            // 省略代码...            try {                // 问题在这里的url校验,构造之后url会待上端口信息,导致在cas服务器上校验不通过                final Assertion assertion = this.ticketValidator.validate(ticket,                        constructServiceUrl(request, response));                         } catch (final TicketValidationException e) {              // ...        }        filterChain.doFilter(request, response);    }

直接看CommonUtils.constructServiceUrl

 public static String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response,                                             final String service, final String serverNames, final String serviceParameterName,                                             final String artifactParameterName, final boolean encode) {        if (CommonUtils.isNotBlank(service)) {            return encode ? response.encodeURL(service) : service;        }        final String serverName = findMatchingServerName(request, serverNames);        final URIBuilder originalRequestUrl = new URIBuilder(request.getRequestURL().toString(), encode);        originalRequestUrl.setParameters(request.getQueryString());        final URIBuilder builder;        if (!serverName.startsWith(";) && !serverName.startsWith(";)) {            final String scheme = request.isSecure() ? "; : ";;            builder = new URIBuilder(scheme + serverName, encode);        } else {            builder = new URIBuilder(serverName, encode);        }      // 判断了端口不是80,443就拼接上端口        if (builder.getPort() == -1 && !requestIsOnStandardPort(request)) {           builder.setPort(request.getServerPort());        }        builder.setEncodedPath(builder.getEncodedPath() + request.getRequestURI());        final List<String> serviceParameterNames = Arrays.asList(serviceParameterName.split(","));        if (!serviceParameterNames.isEmpty() && !originalRequestUrl.getQueryParams().isEmpty()) {            for (final URIBuilder.BasicNameValuePair pair : originalRequestUrl.getQueryParams()) {                final String name = pair.getName();                if (!name.equals(artifactParameterName) && !serviceParameterNames.contains(name)) {                    if (name.contains("&") || name.contains("=")) {                        final URIBuilder encodedParamBuilder = new URIBuilder();                        encodedParamBuilder.setParameters(name);                        for (final URIBuilder.BasicNameValuePair pair2 : encodedParamBuilder.getQueryParams()) {                            final String name2 = pair2.getName();                            if (!name2.equals(artifactParameterName) && !serviceParameterNames.contains(name2)) {                                builder.addParameter(name2, pair2.getValue());                            }                        }                    } else {                        builder.addParameter(name, pair.getValue());                    }                }            }        }        final String result = builder.toString();        final String returnValue = encode ? response.encodeURL(result) : result;        LOGGER.debug("serviceUrl generated: {}", returnValue);        return returnValue;    }

直接下载源码改写

总结

基于公司项目的接入情况遇到的问题解决。相对于前期接入方案较单一,从而导致接入过程磕磕绊绊,记录一下。

标签: #nginx代理cas