在前后端分离项目中应用CAS

CAS在前后端不分离项目中可以轻松对接,但是在分离项目中我们需要进行一些改造才能完成,本文以Springboot项目为例进行讲解

        <dependency>
            <groupId>org.jasig.cas.client</groupId>
            <artifactId>cas-client-support-springboot</artifactId>
            <version>3.6.4</version>
        </dependency>
  server-url-prefix: https://sso.xxx.com/cas # sso服务前缀
  server-login-url: https://sso.xxx.com/cas/login # sso服务登陆地址
  client-host-url: http://xxx.com # 对接sso登陆的前端域名
  validation-type: CAS3 # cas校验版本
  authentication-url-patterns:
    - /policy/* # 需要验证登陆的地址,如果配置了context-path,忽略context-path
  • 重写redirect逻辑
    cas-client的filter默认实现为未登录后端302跳转到sso登录页面,但是在sso单独部署的场景下,前端会出现跨域问题,所以需要重写逻辑
  • 实现AuthenticationRedirectStrategy

    import com.alibaba.fastjson.JSONObject;
    import lombok.extern.slf4j.Slf4j;
    import org.jasig.cas.client.authentication.AuthenticationRedirectStrategy;
    import org.springframework.http.HttpStatus;
    import org.springframework.stereotype.Component;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    @Component
    public class CustomAuthRedirectStrategy implements AuthenticationRedirectStrategy {
        @Override
        public void redirect(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s) throws IOException {
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            httpServletResponse.setHeader("content-type", "text/html;charset=UTF-8");
            httpServletResponse.setCharacterEncoding("UTF-8");
            PrintWriter out = httpServletResponse.getWriter();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", HttpStatus.UNAUTHORIZED.value());
            jsonObject.put("message", "未登录");
            String res = jsonObject.toJSONString();
            out.write(res);
    

    实现CasClientConfigurer

    import org.jasig.cas.client.boot.configuration.CasClientConfigurer;
    import org.jasig.cas.client.boot.configuration.EnableCasClient;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Configuration;
    @Configuration
    @EnableCasClient // 开启cas-client
    public class CasAuthConfig implements CasClientConfigurer {
        @Override
        public void configureAuthenticationFilter(FilterRegistrationBean authenticationFilter) {
            // 源码中使用反射初始化authenticationRedirectStrategyClass, 用自定义的跳转类覆盖默认的authenticationRedirectStrategyClass
            authenticationFilter.getInitParameters().put("authenticationRedirectStrategyClass", CustomAuthRedirectStrategy.class.getName());
    
  • 编写cas相关接口
  • 为了避免ticket丢失问题,需要将回调地址设置为后端接口,再redirect到前端首页

    import lombok.SneakyThrows;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import javax.servlet.http.HttpServletResponse;
    @Controller
    @RequestMapping("/cas/v1")
    public class CasController {
        @Value("${cas.client-host-url}")
        private String clientUrl;
         * 用于前端登陆后回调,跳转回前端首页
        @SneakyThrows
        @GetMapping
        public void casRedirect(HttpServletResponse response) {
            response.sendRedirect(clientUrl);
    

    以axios为例

    axios.interceptors.response.use(function (response) {
              if (response.status === 401) {
                  location.href = 'https://sso.xxx.com/cas/login?service=' + encodeURIComponent(window.location.origin + '/auth/api/auth/cas/v1');
              return response;
    

    nginx配置

    如果出现了跨多个nginx或者部署多台的情况,需要特殊配置

    worker_processes  1;
    events {
        worker_connections  1024;
    http {
        include       mime.types;
        default_type  application/octet-stream;
        sendfile        on;
        keepalive_timeout  65;
        upstream authBe {
            server server1:10010;
            server server2:10010;
            iphash; # cas使用session模式,避免多台出现session丢失的问题
        upstream authFe {
            server server1:10020;
        server {
            listen       10000;
            server_name  localhost;
            location ^~ /api {
                proxy_pass   http://authBe;
                    # 当出现多nginx路由或者修改path时,会出现cookie丢失的  情况,需要进行以下配置
                    proxy_cookie_path /api/ /;
                    proxy_cookie_path /api /;
                    proxy_set_header Cookie $http_cookie
            location / {
                proxy_pass   http://authFe;