前后端分离模式下,SpringBoot + CAS 单点登录实现方案 |
您所在的位置:网站首页 › 前后端分离实现登录的方法 › 前后端分离模式下,SpringBoot + CAS 单点登录实现方案 |
1.CAS服务端构建
1.1.war包部署
cas5.3版本 https://github.com/apereo/cas-overlay-template 构建完成后将war包部署到tomcat即可 1.2.配置文件修改支持http协议 修改apache-tomcat-8.5.53\webapps\cas\WEB-INF\classes\services目录下的HTTPSandIMAPS-10000001.json,在serviceId中添加http即可 { "@class" : "org.apereo.cas.services.RegexRegisteredService", "serviceId" : "^(https|http|imaps)://.*", "name" : "HTTPS and IMAPS", "id" : 10000001, "description" : "This service definition authorizes all application urls that support HTTPS and IMAPS protocols.", "evaluationOrder" : 10000 }在apache-tomcat-8.5.53\webapps\cas\WEB-INF\classes下application.properties添加配置 cas.tgc.secure=false cas.serviceRegistry.initFromJson=true配置默认登录用户名密码及登出重定向 修改apache-tomcat-8.5.53\webapps\cas\WEB-INF\classes下application.properties配置 cas.authn.accept.users=admin::admin #配置允许登出后跳转到指定页面 cas.logout.followServiceRedirects=true 1.3.启动 2.客户端构建 2.1.pom依赖 net.unicon.cas cas-client-autoconfig-support 2.3.0-GA 2.2.yml配置client-host-url配置的地址和前端ajax调用的地址必须一致,统一使用ip:port或hostname:port;如果本地后端配置localhost,前端使用ip,会造成Ticket验证失败 cas: server-url-prefix: http://172.19.25.113:8080/cas server-login-url: http://172.19.25.113:8080/cas/login client-host-url: http://172.19.25.113:1010 validation-type: cas use-session: true authentication-url-patterns: /auth 2.3.后端代码启动类添加@EnableCasClient注解 @EnableCasClient @SpringBootApplication public class SpringbootCasDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootCasDemoApplication.class, args); } }自定义AuthenticationFilter重定向策略 public class CustomAuthRedirectStrategy implements AuthenticationRedirectStrategy { @Override public void redirect(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s) throws IOException { httpServletResponse.setCharacterEncoding("utf-8"); httpServletResponse.setContentType("application/json; charset=utf-8"); PrintWriter out = httpServletResponse.getWriter(); out.write("401"); } }Cors及CasClient相关filter初始化参数配置 @Configuration public class CasAuthConfig extends CasClientConfigurerAdapter { @Override public void configureAuthenticationFilter(FilterRegistrationBean authenticationFilter) { Map initParameters = authenticationFilter.getInitParameters(); initParameters.put("authenticationRedirectStrategyClass", "cc.jasonwang.springbootcasdemo.config.CustomAuthRedirectStrategy"); } @Override public void configureValidationFilter(FilterRegistrationBean validationFilter) { Map initParameters = validationFilter.getInitParameters(); initParameters.put("encodeServiceUrl", "false"); } @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new CorsFilter(source)); registrationBean.setOrder(-2147483648); return registrationBean; } }Controller @RestController public class HelloController { @Value("${cas.server-url-prefix}") private String casServerUrlPrefix; @GetMapping("/auth") public void auth(HttpServletRequest request, HttpServletResponse response, HttpSession session) { Assertion assertion = (Assertion) session.getAttribute("_const_cas_assertion_"); response.setHeader("Content-type", "application/json;charset=UTF-8"); response.setCharacterEncoding("utf-8"); response.setStatus(200); if (assertion != null) { String redirectUrl= request.getParameter("redirectUrl"); try { response.setHeader("Content-type", "text/html;charset=UTF-8"); response.sendRedirect(redirectUrl); } catch (IOException e) { e.printStackTrace(); } } else { try { response.getWriter().print("401"); } catch (IOException e) { e.printStackTrace(); } } } @GetMapping("/logout") public RedirectView logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) { session.invalidate(); String indexPageUrl = "http://127.0.0.1"; return new RedirectView( casServerUrlPrefix + "/logout?service=" + indexPageUrl); } } 2.4.页面 单点地址: 登录 $(".button").click(function(){ $.get("http://172.19.25.113:1010/auth", function(data){ $(".response").text(data) if(data == 401){ window.location.href = "http://localhost:8080/cas/login?service=http://172.19.25.113:1010/auth?redirectUrl=http://127.0.0.1" } }) })这里只是验证前后端分离下页面url跳转问题,页面没有放在nginx服务上 3.问题记录 3.1在前后端分离情况下,AuthenticationFilter重定向问题,导致前端发生跨域https://www.jianshu.com/p/7b51d04f3327 (1)描述 cas前后端不分离的情况下是能够直接跳转的,然而前后端分离后,前端ajax访问后端在经过AuthenticationFilter时,验证未登录会重定向到CAS登录,导致前端发生跨域问题 (2)解决思路 在AuthenticationFilter中不进行重定向,验证未登录就直接返回一个错误状态码;由前端获取到状态码后进行判断,再跳转到CAS登录地址 AuthenticationFilter public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; if (this.isRequestUrlExcluded(request)) { this.logger.debug("Request is ignored."); filterChain.doFilter(request, response); } else { // 获取Assertion 验证是否登录 HttpSession session = request.getSession(false); Assertion assertion = session != null ? (Assertion)session.getAttribute("_const_cas_assertion_") : null; if (assertion != null) { filterChain.doFilter(request, response); } else { String serviceUrl = this.constructServiceUrl(request, response); String ticket = this.retrieveTicketFromRequest(request); boolean wasGatewayed = this.gateway && this.gatewayStorage.hasGatewayedAlready(request, serviceUrl); if (!CommonUtils.isNotBlank(ticket) && !wasGatewayed) { this.logger.debug("no ticket and no assertion found"); String modifiedServiceUrl; if (this.gateway) { this.logger.debug("setting gateway attribute in session"); modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl); } else { modifiedServiceUrl = serviceUrl; } this.logger.debug("Constructed service url: {}", modifiedServiceUrl); String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, this.getProtocol().getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway); this.logger.debug("redirecting to \"{}\"", urlToRedirectTo); // 通过这个方法进行重定向 this.authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo); } else { filterChain.doFilter(request, response); } } } }DefaultAuthenticationRedirectStrategy public final class DefaultAuthenticationRedirectStrategy implements AuthenticationRedirectStrategy { public DefaultAuthenticationRedirectStrategy() { } public void redirect(HttpServletRequest request, HttpServletResponse response, String potentialRedirectUrl) throws IOException { //response重定向 response.sendRedirect(potentialRedirectUrl); } }(3)实现 自定义重定向策略,将DefaultAuthenticationRedirectStrategy替换掉 CustomAuthRedirectStrategy public class CustomAuthRedirectStrategy implements AuthenticationRedirectStrategy { @Override public void redirect(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s) throws IOException { httpServletResponse.setCharacterEncoding("utf-8"); httpServletResponse.setContentType("application/json; charset=utf-8"); PrintWriter out = httpServletResponse.getWriter(); out.write("401"); } } @Configuration public class CasAuthConfig extends CasClientConfigurerAdapter { @Override public void configureAuthenticationFilter(FilterRegistrationBean authenticationFilter) { Map initParameters = authenticationFilter.getInitParameters(); initParameters.put("authenticationRedirectStrategyClass", "cc.jasonwang.springbootcasdemo.config.CustomAuthRedirectStrategy"); } } 3.2AuthenticationFilter自定义重定向策略实现后,前端仍然发生跨域问题Spring 里那么多种 CORS 的配置方式,到底有什么区别 (1)描述 原使用WebMvcConfigurationSupport实现CORS,AuthenticationFilter输出状态码后,前端仍然发生跨域问题 @Configuration public class CorsConfig extends WebMvcConfigurationSupport { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedHeaders("*") .allowedMethods("*") .maxAge(3600) .allowCredentials(true); } }(2)解决思路 通过查找资料发现: 实现 WebMvcConfigurationSupport.addCorsMappings 方法来进行的 CORS 配置,最后会在 Spring 的 Interceptor 或 Handler 中生效 注入 CorsFilter 的方式会让 CORS 验证在 Filter 中生效 (3)实现 修改CORS实现方式 @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new CorsFilter(source)); registrationBean.setOrder(-2147483648); return registrationBean; } 3.3前端跳转CAS登录并传递redirectUrl参数,Ticket票据验证问题(1)原因 Cas20ProxyReceivingTicketValidationFilter在进行Ticket验证时,CAS重定向的service地址进行了URLEncoder编码,而CAS使用Ticket获取到存储的service地址未进行编码,导致两个service不一致,造成Ticket票据验证失败 (2)debug定位问题 AbstractTicketValidationFilter AbstractUrlBasedTicketValidator 找到CAS服务器接口地址后,便想到在CAS服务器端看下接口是怎么实现的,下面就是在CAS服务器debug后的结果 CAS Server 在web.xml中找到了servlet映射 定位到SafeDispatcherServlet,根据目录结构和类文件名称找到了ServiceValidateController ServiceValidateController (3)实现 对Cas20ProxyReceivingTicketValidationFilter添加encodeServiceUrl=false初始化参数 @Configuration public class CasAuthConfig extends CasClientConfigurerAdapter { @Override public void configureAuthenticationFilter(FilterRegistrationBean authenticationFilter) { Map initParameters = authenticationFilter.getInitParameters(); initParameters.put("authenticationRedirectStrategyClass", "cc.jasonwang.springbootcasdemo.config.CustomAuthRedirectStrategy"); } @Override public void configureValidationFilter(FilterRegistrationBean validationFilter) { Map initParameters = validationFilter.getInitParameters(); initParameters.put("encodeServiceUrl", "false"); } }
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |