前言:接上一篇,已经搭建好cas服务器,现在开始集成springboot客户端,由于使用的框架是开源热门springboot项目bootdo,这里直接用bootdo作演示,另外提供一个简单的springboot的demo用作参考。

1.导入所需maven包

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<dependency>

<groupId>org.apache.shiro</groupId>

<artifactId>shiro-spring</artifactId>

<version>1.4.0</version>

</dependency>

<dependency>

<groupId>org.pac4j</groupId>

<artifactId>pac4j-cas</artifactId>

<version>3.0.2</version>

</dependency>

<dependency>

<groupId>io.buji</groupId>

<artifactId>buji-pac4j</artifactId>

<version>4.0.0</version>

<exclusions>

<exclusion>

<artifactId>shiro-web</artifactId>

<groupId>org.apache.shiro</groupId>

</exclusion>

</exclusions>

</dependency>

2.修改shiro配置文件,shiroConfig.java:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

import com.cecjx.system.filter.LoginFilter;

import com.cecjx.system.shiro.UserRealm;

import io.buji.pac4j.filter.CallbackFilter;

import io.buji.pac4j.filter.LogoutFilter;

import io.buji.pac4j.filter.SecurityFilter;

import io.buji.pac4j.subject.Pac4jSubjectFactory;

import org.apache.shiro.session.mgt.SessionManager;

import org.apache.shiro.session.mgt.eis.MemorySessionDAO;

import org.apache.shiro.session.mgt.eis.SessionDAO;

import org.apache.shiro.spring.LifecycleBeanPostProcessor;

import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;

import org.apache.shiro.web.mgt.DefaultWebSecurityManager;

import org.apache.shiro.web.servlet.SimpleCookie;

import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

import org.pac4j.core.config.Config;

import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.web.servlet.FilterRegistrationBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.DependsOn;

import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.DispatcherType;

import javax.servlet.Filter;

import java.util.HashMap;

import java.util.LinkedHashMap;

import java.util.Map;

/**

@Configuration

public class ShiroConfig {

/** 项目工程路径 */

@Value("${cas.project.url}")

private String projectUrl;

/** 项目cas服务路径 */

@Value("${cas.server.url}")

private String casServerUrl;

/** 客户端名称 */

@Value("${cas.client-name}")

private String clientName;

@Value("${server.session-timeout}")

private int tomcatTimeout;

@Bean

public ShiroDialect shiroDialect() {

return new ShiroDialect();

}

@Bean("securityManager")

public DefaultWebSecurityManager securityManager(Pac4jSubjectFactory subjectFactory, SessionManager sessionManager, UserRealm casRealm){

DefaultWebSecurityManager manager = new DefaultWebSecurityManager();

manager.setRealm(casRealm);

manager.setSubjectFactory(subjectFactory);

manager.setSessionManager(sessionManager);

return manager;

}

@Bean

public UserRealm casRealm(){

UserRealm realm = new UserRealm();

// 使用自定义的realm

realm.setClientName(clientName);

realm.setCachingEnabled(false);

//暂时不使用缓存

realm.setAuthenticationCachingEnabled(false);

realm.setAuthorizationCachingEnabled(false);

//realm.setAuthenticationCacheName("authenticationCache");

//realm.setAuthorizationCacheName("authorizationCache");

return realm;

}

/**

@Bean

public Pac4jSubjectFactory subjectFactory(){

return new Pac4jSubjectFactory();

}

@Bean

public FilterRegistrationBean filterRegistrationBean() {

FilterRegistrationBean filterRegistration = new FilterRegistrationBean();

filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));

// 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理

filterRegistration.addInitParameter("targetFilterLifecycle", "true");

filterRegistration.setEnabled(true);

filterRegistration.addUrlPatterns("/*");

filterRegistration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD);

return filterRegistration;

}

/**

private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean){

/*下面这些规则配置最好配置到配置文件中 */

Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

filterChainDefinitionMap.put("/css/**", "anon");

filterChainDefinitionMap.put("/js/**", "anon");

filterChainDefinitionMap.put("/fonts/**", "anon");

filterChainDefinitionMap.put("/img/**", "anon");

filterChainDefinitionMap.put("/docs/**", "anon");

filterChainDefinitionMap.put("/druid/**", "anon");

filterChainDefinitionMap.put("/upload/**", "anon");

filterChainDefinitionMap.put("/files/**", "anon");

filterChainDefinitionMap.put("/", "anon");

filterChainDefinitionMap.put("/kaptcha", "anon");

filterChainDefinitionMap.put("/api/**", "anon");

filterChainDefinitionMap.put("/callback", "callbackFilter");

filterChainDefinitionMap.put("/logout", "logout");

filterChainDefinitionMap.put("/index","securityFilter");

filterChainDefinitionMap.put("/**","securityFilter");

// filterChainDefinitionMap.put("/**","loginFilter");

// filterChainDefinitionMap.put("/user/edit/**", "authc,perms[user:edit]");

shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

}

/**

@Bean("shiroFilter")

public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager, Config config) {

ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

// 必须设 SecurityManager

shiroFilterFactoryBean.setSecurityManager(securityManager);

shiroFilterFactoryBean.setUnauthorizedUrl("/403");

// 添加casFilter到shiroFilter
loadShiroFilterChain(shiroFilterFactoryBean);

Map<String, Filter> filters = new HashMap<>(4);

//cas 资源认证拦截器

SecurityFilter securityFilter = new SecurityFilter();

securityFilter.setConfig(config);

securityFilter.setClients(clientName);

filters.put("securityFilter", securityFilter);

//cas 认证后回调拦截器

CallbackFilter callbackFilter = new CallbackFilter();

callbackFilter.setConfig(config);

callbackFilter.setDefaultUrl(projectUrl);

filters.put("callbackFilter", callbackFilter);

// 注销 拦截器

LogoutFilter logoutFilter = new LogoutFilter();

logoutFilter.setConfig(config);

logoutFilter.setCentralLogout(true);

logoutFilter.setLocalLogout(true);

logoutFilter.setDefaultUrl(casServerUrl + "/logout?service=" + projectUrl);

filters.put("logout",logoutFilter);

shiroFilterFactoryBean.setFilters(filters);

LoginFilter loginFilter=new LoginFilter();

filters.put("loginFilter",loginFilter);

return shiroFilterFactoryBean;

}

@Bean

public SessionDAO sessionDAO(){

return new MemorySessionDAO();

}

/**

@Bean

public SimpleCookie sessionIdCookie(){

SimpleCookie cookie = new SimpleCookie("sid");

cookie.setMaxAge(-1);

cookie.setPath("/");

cookie.setHttpOnly(false);

return cookie;

}

@Bean

public DefaultWebSessionManager sessionManager(SimpleCookie sessionIdCookie, SessionDAO sessionDAO){

DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();

sessionManager.setSessionIdCookie(sessionIdCookie);

sessionManager.setSessionIdCookieEnabled(true);

sessionManager.setGlobalSessionTimeout(tomcatTimeout * 1000);

sessionManager.setSessionDAO(sessionDAO);

sessionManager.setDeleteInvalidSessions(true);

sessionManager.setSessionValidationSchedulerEnabled(true);

return sessionManager;

}

/**

@Bean

@DependsOn("lifecycleBeanPostProcessor")

public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {

DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();

// 强制使cglib,防止重复代理和可能引起代理出错的问题

// https://zhuanlan.zhihu.com/p/29161098

defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);

return defaultAdvisorAutoProxyCreator;

}

@Bean

public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {

return new LifecycleBeanPostProcessor();

}

@Bean

public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {

AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();

advisor.setSecurityManager(securityManager);

return advisor;

}

}

3.添加pac4j的配置文件,Pac4JConfig.java:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
import io.buji.pac4j.context.ShiroSessionStore;

import org.pac4j.cas.config.CasConfiguration;

import org.pac4j.cas.config.CasProtocol;

import org.pac4j.core.config.Config;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

/**

@Configuration

public class Pac4jConfig {

/** 地址为:cas地址 */

@Value("${cas.server.url}")

private String casServerUrl;

/** 地址为:验证返回后的项目地址:http://localhost:8081 */

@Value("${cas.project.url}")

private String projectUrl;

/** 相当于一个标志,可以随意 */

@Value("${cas.client-name}")

private String clientName;

/**

@Bean("authcConfig")

public Config config(CasClient casClient, ShiroSessionStore shiroSessionStore) {

Config config = new Config(casClient);

config.setSessionStore(shiroSessionStore);

return config;

}

/**

@Bean

public ShiroSessionStore shiroSessionStore(){

return new ShiroSessionStore();

}

/**

@Bean

public CasClient casClient(CasConfiguration casConfig){

CasClient casClient = new CasClient(casConfig);

//客户端回调地址

casClient.setCallbackUrl(projectUrl + "/callback?client_name=" + clientName);

casClient.setName(clientName);

return casClient;

}

/**

@Bean

public CasConfiguration casConfig(){

final CasConfiguration configuration = new CasConfiguration();

//CAS server登录地址

configuration.setLoginUrl(casServerUrl + "/login");

//CAS 版本,默认为 CAS30,我们使用的是 CAS20

configuration.setProtocol(CasProtocol.CAS20);

configuration.setAcceptAnyProxy(true);

configuration.setPrefixUrl(casServerUrl + "/");

return configuration;

}

}

 4.cas客户端CasClient.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import org.pac4j.cas.config.CasConfiguration;

import org.pac4j.core.context.Pac4jConstants;

import org.pac4j.core.context.WebContext;

import org.pac4j.core.context.session.SessionStore;

import org.pac4j.core.redirect.RedirectAction;

import org.pac4j.core.util.CommonHelper;

public class CasClient extends org.pac4j.cas.client.CasClient {

public CasClient() {

super();

}

public CasClient(CasConfiguration configuration) {

super(configuration);

}

@Override

public RedirectAction getRedirectAction(WebContext context) {

this.init();

if (getAjaxRequestResolver().isAjax(context)) {

this.logger.info("AJAX request detected -> returning the appropriate action");

RedirectAction action = getRedirectActionBuilder().redirect(context);

this.cleanRequestedUrl(context);

return getAjaxRequestResolver().buildAjaxResponse(action.getLocation(), context);

} else {

final String attemptedAuth = (String)context.getSessionStore().get(context, this.getName() + ATTEMPTED_AUTHENTICATION_SUFFIX);

if (CommonHelper.isNotBlank(attemptedAuth)) {

this.cleanAttemptedAuthentication(context);

this.cleanRequestedUrl(context);

return this.getRedirectActionBuilder().redirect(context);

} else {

return this.getRedirectActionBuilder().redirect(context);

}

}

}

private void cleanRequestedUrl(WebContext context) {

SessionStore<WebContext> sessionStore = context.getSessionStore();

if (sessionStore.get(context, Pac4jConstants.REQUESTED_URL) != null) {

sessionStore.set(context, Pac4jConstants.REQUESTED_URL, "");

}

}

private void cleanAttemptedAuthentication(WebContext context) {

SessionStore<WebContext> sessionStore = context.getSessionStore();

if (sessionStore.get(context, this.getName() + ATTEMPTED_AUTHENTICATION_SUFFIX) != null) {

sessionStore.set(context, this.getName() + ATTEMPTED_AUTHENTICATION_SUFFIX, "");

}

}

}

5.修改原来的UserRealm为继承Pac4jRealm,修改里面的doGetAuthorizationInfo方法:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import com.cecjx.common.config.ApplicationContextRegister;

import com.cecjx.common.utils.ShiroUtils;

import com.cecjx.system.domain.UserDO;

import com.cecjx.system.service.MenuService;

import com.cecjx.system.service.UserService;

import io.buji.pac4j.realm.Pac4jRealm;

import io.buji.pac4j.subject.Pac4jPrincipal;

import io.buji.pac4j.token.Pac4jToken;

import org.apache.shiro.authc.*;

import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.authz.SimpleAuthorizationInfo;

import org.apache.shiro.subject.PrincipalCollection;

import org.apache.shiro.subject.SimplePrincipalCollection;

import org.pac4j.core.profile.CommonProfile;

import java.util.List;

import java.util.Set;

public class UserRealm extends Pac4jRealm {

private String clientName;

public String getClientName() {

return clientName;

}

public void setClientName(String clientName) {

this.clientName = clientName;

}

@Override

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection authenticationToken) {

Long userId = ShiroUtils.getUserId();

MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);

Set<String> perms = menuService.listPerms(userId);

SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

info.setStringPermissions(perms);

return info;

}

@Override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

final Pac4jToken token = (Pac4jToken) authenticationToken;

final List<CommonProfile> profiles = token.getProfiles();

final Pac4jPrincipal principal = new Pac4jPrincipal(profiles);

//登录用户
String userName = principal.getProfile().getId();

//String password = new String((char[]) token.getCredentials());

UserService userService = ApplicationContextRegister.getBean(UserService.class);

// 查询用户信息

UserDO user = userService.get(userName);

// 查询用户是否管理员

boolean isAdmin = userService.isAdmin(user.getUserId());

user.setAdmin(isAdmin);

// 账号不存在

if (user == null) {

throw new UnknownAccountException("账号不存在");

}

// 密码错
// if (!password.equals(user.getPassword())) {

// throw new IncorrectCredentialsException("账号或密码不正确");

// }

// 账号锁
// if (user.getStatus() == 0) {

// throw new LockedAccountException("账号已被锁定,请联系管理员");

// }

// SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, "123", getName());

// return info;

PrincipalCollection principalCollection = new SimplePrincipalCollection(user, this.getName());

return new SimpleAuthenticationInfo(principalCollection, profiles.hashCode());

}

}

6.cas服务器地址及客户端回调地址的配置application.yml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#cas配置

cas:

client-name: ywjk

#测试工作机地址

server:

url: http://127.0.0.1:8443/cas

#本机ip地
project:

url: http://127.0.0.1:8081/ywjk/

7.至此,bootdo客户端集成cas单点登录完成。项目demo下载https://download.csdn.net/download/qq_29467891/12548449