CAS在前后端不分離項目中可以輕松對接,但是在分離項目中我們需要進行一些改造才能完成,本文以Springboot項目為例進行講解
后端配置
- 引入依賴
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-support-springboot</artifactId>
<version>3.6.4</version>
</dependency>
- 配置
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
- 重寫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());
}
}
- 編寫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ù)的對接~