一、启用Cas支持包
<!-- security 对CAS支持 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
</dependency>
二、yml进行自定义cas参数配置
#cas相关
cas:
enabled: true
server:
##cas服务前缀
baseUrl: http://localhost:8085/cas
##cas服务登录url
loginUrl: ${cas.server.baseUrl}/login
## 本地tomcat启动的cas 需要在解出来的文件application.properties 添加 cas.logout.followServiceRedirects=true 配置,即可实现退出cas后跳转至service后的callback页面
logoutUrl: ${cas.server.baseUrl}/logout?service=${cas.client.baseUrl}${cas.client.loginUrl}
client:
##cas客户端根地址
baseUrl: http://localhost:8801/eladmin
##登录地址
loginUrl: /api/cas/login
##首页地址
indexUrl: /api/cas/index
##登出地址、注册LogoutFilter同步触发cas logout
logoutUrl: /api/cas/logout
三、Security配置类SecurityCasConfig
package com.sf.vsolution.hn.el.modules.security.config;
import cn.hutool.core.collection.CollUtil;
import com.sf.vsolution.hn.el.annotation.AnonymousAccess;
import com.sf.vsolution.hn.el.modules.security.security.JwtAccessDeniedHandler;
import com.sf.vsolution.hn.el.modules.test.rest.config.CasProperties;
import com.sf.vsolution.hn.el.modules.test.rest.config.CustomUserDetailsServiceImpl;
import com.sf.vsolution.hn.el.utils.enums.RequestMethodEnum;
import lombok.RequiredArgsConstructor;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.*;
/**
* @author wangzai
*/
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
// 启用判断
@ConditionalOnProperty(name = {"cas.enabled"}, havingValue = "true")
public class SecurityCasConfig extends WebSecurityConfigurerAdapter {
private final CorsFilter corsFilter;
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
private final ApplicationContext applicationContext;
@Autowired
private CasProperties casProperties;
@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
// 去除 ROLE_ 前缀
return new GrantedAuthorityDefaults("");
}
@Bean
public PasswordEncoder passwordEncoder() {
// 密码加密方式
return new BCryptPasswordEncoder();
}
/**
* 定义认证用户信息获取来源,密码校验规则等
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
auth.authenticationProvider(casAuthenticationProvider());
}
/**
* 认证的入口
*/
@Bean
public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {
CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint();
// cas登录服务
casAuthenticationEntryPoint.setLoginUrl(casProperties.getCasServerLoginUrl());
casAuthenticationEntryPoint.setServiceProperties(serviceProperties());
return casAuthenticationEntryPoint;
}
/**
* cas 认证成功控制器
*
*/
/* @Bean
public SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler() {
SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
successHandler.setAlwaysUseDefaultTargetUrl(false);
successHandler.setDefaultTargetUrl(casProperties.getCasClientIndexUrl());
return successHandler;
}*/
/**
* 指定service相关信息
*/
@Bean
public ServiceProperties serviceProperties() {
ServiceProperties serviceProperties = new ServiceProperties();
// 本机服务,访问该路径时时进行cas校验登录
serviceProperties.setService(casProperties.getCasClientBaseUrl() + casProperties.getCasClientLoginUrl());
serviceProperties.setAuthenticateAllArtifacts(true);
return serviceProperties;
}
/**
* CAS认证过滤器
*/
@Bean
public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
casAuthenticationFilter.setAuthenticationManager(authenticationManager());
casAuthenticationFilter.setFilterProcessesUrl(casProperties.getCasClientLoginUrl());
// 认证成功后的处理(跳转默认targetUrl)
casAuthenticationFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(casProperties.getCasClientIndexUrl()));
return casAuthenticationFilter;
}
/**
* cas 认证 Provider
*/
@Bean
public CasAuthenticationProvider casAuthenticationProvider() {
CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
casAuthenticationProvider.setAuthenticationUserDetailsService(customUserDetailsService());
casAuthenticationProvider.setServiceProperties(serviceProperties());
casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator());
casAuthenticationProvider.setKey("casAuthenticationProviderKey");
return casAuthenticationProvider;
}
/**
* 用户自定义的AuthenticationUserDetailsService
* 对用户进行映射或绑定
*/
@Bean
public AuthenticationUserDetailsService<CasAssertionAuthenticationToken> customUserDetailsService() {
return new CustomUserDetailsServiceImpl();
}
@Bean
public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
// 指定cas校验器, 进行ticket校验
return new Cas20ServiceTicketValidator(casProperties.getCasServerBaseUrl());
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// 搜寻匿名标记 url: @AnonymousAccess
Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
// 获取匿名标记
Map<String, Set<String>> anonymousUrls = getAnonymousUrl(handlerMethodMap);
httpSecurity
// 禁用 CSRF
.csrf().disable()
.headers().frameOptions().disable()
.and()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
// 授权异常
.exceptionHandling()
.authenticationEntryPoint(casAuthenticationEntryPoint())
.accessDeniedHandler(jwtAccessDeniedHandler)
// 防止iframe 造成跨域
.and()
.addFilter(casAuthenticationFilter())
.addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class)
.addFilterBefore(casLogoutFilter(), LogoutFilter.class)
.sessionManagement()
// 框架从不创建session,但如果已经存在,会使用该session
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.authorizeRequests()
// 静态资源等等
.antMatchers(
HttpMethod.GET,
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/webSocket/**"
).permitAll()
// 文件
.antMatchers("/avatar/**").permitAll()
.antMatchers("/file/**").permitAll()
// 放行OPTIONS请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// 自定义匿名访问所有url放行:允许匿名和带Token访问,细腻化到每个 Request 类型
// GET
.antMatchers(HttpMethod.GET, anonymousUrls.get(RequestMethodEnum.GET.getType()).toArray(new String[0])).permitAll()
// POST
.antMatchers(HttpMethod.POST, anonymousUrls.get(RequestMethodEnum.POST.getType()).toArray(new String[0])).permitAll()
// PUT
.antMatchers(HttpMethod.PUT, anonymousUrls.get(RequestMethodEnum.PUT.getType()).toArray(new String[0])).permitAll()
// PATCH
.antMatchers(HttpMethod.PATCH, anonymousUrls.get(RequestMethodEnum.PATCH.getType()).toArray(new String[0])).permitAll()
// DELETE
.antMatchers(HttpMethod.DELETE, anonymousUrls.get(RequestMethodEnum.DELETE.getType()).toArray(new String[0])).permitAll()
// 所有类型的接口都放行
.antMatchers(anonymousUrls.get(RequestMethodEnum.ALL.getType()).toArray(new String[0])).permitAll()
// 所有请求都需要认证
.anyRequest().authenticated();
}
private Map<String, Set<String>> getAnonymousUrl(Map<RequestMappingInfo, HandlerMethod> handlerMethodMap) {
Map<String, Set<String>> anonymousUrls = new HashMap<>(6);
Set<String> get = new HashSet<>();
Set<String> post = new HashSet<>();
Set<String> put = new HashSet<>();
Set<String> patch = new HashSet<>();
Set<String> delete = new HashSet<>();
Set<String> all = new HashSet<>();
for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
HandlerMethod handlerMethod = infoEntry.getValue();
AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
if (null != anonymousAccess) {
List<RequestMethod> requestMethods = new ArrayList<>(infoEntry.getKey().getMethodsCondition().getMethods());
RequestMethodEnum request = RequestMethodEnum.find(CollUtil.isEmpty(requestMethods) ? RequestMethodEnum.ALL.getType() : requestMethods.get(0).name());
switch (Objects.requireNonNull(request)) {
case GET:
get.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
break;
case POST:
post.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
break;
case PUT:
put.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
break;
case PATCH:
patch.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
break;
case DELETE:
delete.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
break;
default:
all.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
break;
}
}
}
anonymousUrls.put(RequestMethodEnum.GET.getType(), get);
anonymousUrls.put(RequestMethodEnum.POST.getType(), post);
anonymousUrls.put(RequestMethodEnum.PUT.getType(), put);
anonymousUrls.put(RequestMethodEnum.PATCH.getType(), patch);
anonymousUrls.put(RequestMethodEnum.DELETE.getType(), delete);
anonymousUrls.put(RequestMethodEnum.ALL.getType(), all);
return anonymousUrls;
}
/**
* 单点登出过滤器
*/
@Bean
public SingleSignOutFilter singleSignOutFilter() {
SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter();
singleSignOutFilter.setLogoutCallbackPath(casProperties.getCasServerBaseUrl());
singleSignOutFilter.setIgnoreInitConfiguration(true);
return singleSignOutFilter;
}
/**
* 请求单点退出过滤器
*/
@Bean
public LogoutFilter casLogoutFilter() {
// cas 退出转发路径
LogoutFilter logoutFilter = new LogoutFilter(casProperties.getCasServerLogoutUrl(), new SecurityContextLogoutHandler());
// cas 退出
logoutFilter.setFilterProcessesUrl(casProperties.getCasClientLogoutUrl());
return logoutFilter;
}
}
四、关联配置类
1)CustomUserDetailsServiceImpl:生成 UserDetails 类信息,可以在此进行校验然后保存用户信息,之后将这个UserDetails的实现类放在Authentication中,通过Authentication.getPrincipal()结合重写loadUserByUsername 获取当前登录用户的信息。
package com.sf.vsolution.hn.el.modules.test.rest.config;
import com.sf.vsolution.hn.el.modules.security.service.dto.JwtUserDto;
import com.sf.vsolution.hn.el.modules.system.service.dto.UserDto;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class CustomUserDetailsServiceImpl implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {
@Override
public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
System.out.println("当前的用户名是:" + token.getName());
List<GrantedAuthority> authorities = new ArrayList<>();
UserDto userDto = new UserDto();
userDto.setUsername("admin");
userDto.setEnabled(true);
AuthorityInfo authorityInfo = new AuthorityInfo("TEST");
authorities.add(authorityInfo);
JwtUserDto userInfo = new JwtUserDto(userDto, new ArrayList<>(), authorities);
return userInfo;
}
}
2)cas 配置参数类
package com.sf.vsolution.hn.el.modules.test.rest.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* CAS 配置参数
*/
@Component
@Data
public class CasProperties {
@Value("${cas.server.baseUrl}")
private String casServerBaseUrl;
@Value("${cas.server.loginUrl}")
private String casServerLoginUrl;
@Value("${cas.server.logoutUrl}")
private String casServerLogoutUrl;
@Value("${cas.client.baseUrl}")
private String casClientBaseUrl;
@Value("${cas.client.loginUrl}")
private String casClientLoginUrl;
@Value("${cas.client.indexUrl}")
private String casClientIndexUrl;
@Value("${cas.client.logoutUrl}")
private String casClientLogoutUrl;
}
3)权限继承类
package com.sf.vsolution.hn.el.modules.test.rest.config;
import org.springframework.security.core.GrantedAuthority;
public class AuthorityInfo implements GrantedAuthority {
private static final long serialVersionUID = -1;
/**
* 权限命名
*/
private String authority;
public AuthorityInfo(String authority) {
this.authority = authority;
}
@Override
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
4)测试接口
package com.sf.vsolution.hn.el.modules.test.rest;
import com.sf.vsolution.hn.el.annotation.rest.AnonymousGetMapping;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/cas")
public class TestController {
@RequestMapping(value = "/index", produces = MediaType.APPLICATION_JSON_VALUE)
public String index() {
return "访问了首页哦";
}
@AnonymousGetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_VALUE)
public String hello() {
return "不验证哦";
}
@PreAuthorize("@el.check('TEST')")
@RequestMapping("/security")
public String security() {
return "hello world security";
}
@PreAuthorize("@el.check()")
@RequestMapping(value = "/authorize", produces = MediaType.APPLICATION_JSON_VALUE)
public String authorize() {
return "有权限访问";
}
}