在前后端分離項目中應(yīng)用CAS

CAS在前后端不分離項目中可以輕松對接,但是在分離項目中我們需要進行一些改造才能完成,本文以Springboot項目為例進行講解

后端配置

  1. 引入依賴
        <dependency>
            <groupId>org.jasig.cas.client</groupId>
            <artifactId>cas-client-support-springboot</artifactId>
            <version>3.6.4</version>
        </dependency>
  1. 配置
cas:
  server-url-prefix: https://sso.xxx.com/cas # sso服務(wù)前綴
  server-login-url: https://sso.xxx.com/cas/login # sso服務(wù)登陸地址
  client-host-url: http://xxx.com # 對接sso登陸的前端域名
  validation-type: CAS3 # cas校驗版本
  authentication-url-patterns:
    - /policy/* # 需要驗證登陸的地址,如果配置了context-path,忽略context-path
  1. 重寫redirect邏輯
    cas-client的filter默認實現(xiàn)為未登錄后端302跳轉(zhuǎn)到sso登錄頁面,但是在sso單獨部署的場景下,前端會出現(xiàn)跨域問題,所以需要重寫邏輯

實現(xiàn)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);
    }
}

實現(xiàn)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, 用自定義的跳轉(zhuǎn)類覆蓋默認的authenticationRedirectStrategyClass
        authenticationFilter.getInitParameters().put("authenticationRedirectStrategyClass", CustomAuthRedirectStrategy.class.getName());
    }
}
  1. 編寫cas相關(guān)接口

為了避免ticket丟失問題,需要將回調(diào)地址設(shè)置為后端接口,再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;

    /**
     * 用于前端登陸后回調(diào),跳轉(zhuǎn)回前端首頁
     **/
    @SneakyThrows
    @GetMapping
    public void casRedirect(HttpServletResponse response) {
        response.sendRedirect(clientUrl);
    }
}

前端配置

以axios為例

axios.interceptors.response.use(function (response) {
          if (response.status === 401) {
              location. + encodeURIComponent(window.location.origin + '/auth/api/auth/cas/v1');
          }
          return response;
        });

nginx配置

如果出現(xiàn)了跨多個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模式,避免多臺出現(xiàn)session丟失的問題
    }

    upstream authFe {
        server server1:10020;
    }

    server {
        listen       10000;
        server_name  localhost;

        location ^~ /api {
            proxy_pass   http://authBe;
                # 當出現(xiàn)多nginx路由或者修改path時,會出現(xiàn)cookie丟失的  情況,需要進行以下配置
                proxy_cookie_path /api/ /;
                proxy_cookie_path /api /;
                proxy_set_header Cookie $http_cookie
        }

        location / {
            proxy_pass   http://authFe;
        }

    }

    include servers/*;
}

經(jīng)過以上步驟就完成了cas-client與sso服務(wù)的對接~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容