前后端分离集成CAS单点登录

修改nginx

复制代码
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location /api/ {
            proxy_pass http://127.0.0.1:9001/; # 后端
        }
        location / {
            proxy_pass http://127.0.0.1:3000/; # 前端
        }
    }
}

改写redirect返回401

java 复制代码
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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;

/**
 * <p>Title: </p>
 * <p>Description: CAS统一身份认证集成配置,session过期或未认证时返回结果处理</p>
 * <p>Copyright: Copyright  (c) 2023</p>
 * <p>Company: </p>
 *
 * @author yanfh
 * @version 1.0
 * @date 2023/4/14  10:11
 */
@Component
public class CustomAuthRedirectStrategy implements AuthenticationRedirectStrategy {

    /**
     * 重定向策略,由原来自动跳转url,改为返回json
     *
     * @param httpServletRequest request请求
     * @param httpServletResponse response请求
     * @param potentialRedirectUrl 重定向URL
     * @throws IOException IO异常
     */
    @Override
    public void redirect(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String potentialRedirectUrl) throws IOException {
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setHeader("content-type", "text/html;charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        PrintWriter out = httpServletResponse.getWriter();
        ObjectMapper om = new ObjectMapper();
        ObjectNode node = om.createObjectNode();
        node.put("code", HttpStatus.UNAUTHORIZED.value());
        node.put("message", "Unauthorized");
        out.write(om.writeValueAsString(node));
    }
}

cas 配置忽略拦截

java 复制代码
@Bean
    public FilterRegistrationBean filterAuthenticationRegistration() {
        final FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new AuthenticationFilter());
        // 设定匹配的路径
        registration.addUrlPatterns("/*");
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("casServerLoginUrl", serverLoginUrl);
        initParameters.put("serverName", clientHostUrl);

        if (ignorePattern != null && !"".equals(ignorePattern)) {
            initParameters.put("ignorePattern", ignorePattern);
        }

        //自定义UrlPatternMatcherStrategy 验证规则
        if (ignoreUrlPatternType != null && !"".equals(ignoreUrlPatternType)) {
            initParameters.put("ignoreUrlPatternType", ignoreUrlPatternType);
        }
        initParameters.put("authenticationRedirectStrategyClass", CustomAuthRedirectStrategy.class.getName());
        registration.setInitParameters(initParameters);
        // 设定加载的顺序
        registration.setOrder(2);
        return registration;
    }

前端请求后端接口判断是否返回401,若返回401,手动拼接认证地址跳转window.location.href='http://CAS服务端/cas/login?service='+encodeURIComponent('http://后端/api/login'),由后端 response.sendRedirect("http://前端页面")

java 复制代码
@GetMapping("/login")
    public void casRedirect(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.sendRedirect(clientUrl);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
    }
相关推荐
CodeStats6 分钟前
《源纹天书》第一百六十一章至第一百六十五章:开源化宣言、元定义的力量、栈帧重构、容器道场升级、技术债的化身!
java·源纹天书
不良手残11 分钟前
MyBatisPlus代码自动生成器
java
SamDeepThinking15 分钟前
一次线程池线上故障复盘:四层防线如何避免数据丢失
java·后端·程序员
花生智源28 分钟前
Java实现Prompt工程的技巧——从模板到工程化,告别字符串拼接
java·人工智能
折哥的程序人生 · 物流技术专研31 分钟前
Java 23 种设计模式:从踩坑到精通 | 番外:策略 vs 模板方法 —— 组合与继承的终极对决
java·策略模式·java面试·comparator·模版方法模式·java设计模式·从踩坑到精通
库克克38 分钟前
【C++】类和对象--this指针详解
java·开发语言·c++
SL_staff1 小时前
JVS低代码完整源码解析:如何二次开发自己的表单组件?
java·低代码·vuex
QN1幻化引擎1 小时前
Gravity-Anchored Cognitive Field Architecture: The DalinX V8/V10 Implementation
java·前端·算法
一生有你20201 小时前
Spring AI ChatMemory 监控与排查:从指标到排错全链路
java·人工智能·spring
程序员黎剑1 小时前
我把算卦变成了一段if-else
java·vue.js·spring boot·后端·ai编程