Springboot前后端分离实现CAS单点登录
1.CAS服务端构建
1.1war包部署
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启动
1.客户端构建
1.1pom依赖
<dependency>
<groupId>net.unicon.cas</groupId>
<artifactId>cas-client-autoconfig-support</artifactId>
<version>2.3.0-GA</version>
</dependency>
1.2yml配置
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
1.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<String, String> initParameters = authenticationFilter.getInitParameters();
initParameters.put("authenticationRedirectStrategyClass", "cc.jasonwang.springbootcasdemo.config.CustomAuthRedirectStrategy");
}
@Override
public void configureValidationFilter(FilterRegistrationBean validationFilter) {
Map<String, String> initParameters = validationFilter.getInitParameters();
initParameters.put("encodeServiceUrl", "false");
}
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new