Cas单点登录(整合shiro版本)

单点登录:Single Sign On,简称SSO,SSO使得在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。

CAS框架:CAS(Central Authentication Service)是实现SSO单点登录的框架。

逻辑关系图:(注:图为转载)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d2I5tyKA-1651236640645)(https://blog.csdn.net/qq_25223941/article/details/78316108)]

分析:

1.图中用户访问cas客户端;

2.需要登录时,重定向到Cas-Server(Cas服务),其中service为Cas-Client路径

(用于Cas-Server执行完后返回到指定路径);

3.cas-server认证用户信息,并生成一个ticket返回给用户;

4.用户使用此ticket访问Cas-Client(连接了Cas-Server具体应用);

5.Cas-Client使用ticket再次访问Cas-Server进行认证;

6.认证成功后返回Server指定路径到Cas-Client,并返回具体登录用户信息,流程结束。

这是原生Cas的一套流程,那么我们需要集成到已经使用Shiro框架的应用中,如何进行无缝衔接呢?

具体流程:

对于Cas-Server就不多说了,官网下载下来后,修改验证用户信息的配置(从数据库中读取数据进行

身份认证),修改配置文件-deployerConfigContext:

(其中deployerConfigContext.xml文件是CAS专门提出来的供用户修改的配置,其他配置不建议修改)

[html] view plain copy

  1. <beanid=“primaryAuthenticationHandler”

  2. class=“org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler”>

  3. <propertyname="dataSource"ref=“dataSource”/>

  4. <propertyname="sql"value=“selectpasswordfromuserwhereuserName=”/>

  5. </bean>

  6. <beanid="dataSource"class=“org.springframework.jdbc.datasource.DriverManagerDataSource”>

  7. <propertyname="driverClassName"value=“com.mysql.jdbc.Driver”/>

  8. <propertyname="url"value=“jdbc:mysql://127.0.0.1:3306/**characterEncoding=utf8”/>

  9. <propertyname=“username"value=”**"/>

  10. <propertyname=“password"value=”**"/>

  11. </bean>

注意:其中需要引入包cas-server-support-jdbc-4.0.0.jar(版本号极为重要,与cas-server-core版本一致即可)

还需要引入mysql-connector-java-5.1.34.jar(连接mysql)

连接Cas-Server的使用了Shiro的应用项目连接的整体操作流程,如下:

1.首先需要引入包shiro-cas这个包是shiro和cas连接的通道;

2.修改项目中shiroRealm(自定义的登录验证类,里面包含登录认证、权限认证)

[java] view plain copy

  1. /**

  2. *shiro登录实现类

  3. *

  4. */

  5. //重点是集成CasRealm

  6. publicclassShiroRealmextendsCasRealm{

  7. privateLoggerlog=LoggerFactory.getLogger(ShiroRealm.class);

  8. privateTicketValidatorticketValidator;

  9. protectedTicketValidatorensureTicketValidator()

  10. {

  11. if(ticketValidator==null)

  12. ticketValidator=createTicketValidator();

  13. returnticketValidator;

  14. }

  15. @Override

  16. protectedAuthenticationInfodoGetAuthenticationInfo(AuthenticationTokenauthcToken)throwsAuthenticationException{

  17. CasTokencasToken=(CasToken)authcToken;

  18. if(authcToken==null)

  19. returnnull;

  20. Stringticket=(String)casToken.getCredentials();

  21. TicketValidatorticketValidator=ensureTicketValidator();

  22. try

  23. {

  24. AssertioncasAssertion=ticketValidator.validate(ticket,getCasService());

  25. AttributePrincipalcasPrincipal=casAssertion.getPrincipal();

  26. StringuserId=casPrincipal.getName();

  27. log.debug(“Validateticket:{}inCASserver:{}toretrieveuser:{}”,newObject[]{

  28. ticket,getCasServerUrlPrefix(),userId

  29. });

  30. Map<String,Object>attributes=casPrincipal.getAttributes();

  31. casToken.setUserId(userId);

  32. StringrememberMeAttributeName=getRememberMeAttributeName();

  33. StringrememberMeStringValue=(String)attributes.get(rememberMeAttributeName);

  34. booleanisRemembered=rememberMeStringValue!=null&&Boolean.parseBoolean(rememberMeStringValue);

  35. if(isRemembered)

  36. casToken.setRememberMe(true);

  37. /**此处是封装用户信息

  38. sUsrsu=newsUsr();

  39. su.setUsrCde(userId);

  40. sUsrsusr=isUsrService.findByCode(su);

  41. AccessTokenInfoatInfo=newAccessTokenInfo();

  42. atInfo.setUsrCde(userId);

  43. //获取apikey

  44. AccessTokenInfoati=accessTokenInfoService.selectOneByObject(atInfo);

  45. //构建ShiroUserAccount

  46. ShiroUserAccountsua=newShiroUserAccount(susr,ati);

  47. */

  48. Listprincipals=CollectionUtils.asList(newObject[]{

  49. sua,attributes

  50. });

  51. PrincipalCollectionprincipalCollection=newSimplePrincipalCollection(principals,getName());

  52. returnnewSimpleAuthenticationInfo(principalCollection,ticket);

  53. }

  54. catch(TicketValidationExceptione)

  55. {

  56. thrownewCasAuthenticationException((newStringBuilder()).append(“Unabletovalidateticket[”).append(ticket).append(“]”).toString(),e);

  57. }

  58. }

  59. @Override

  60. protectedAuthorizationInfodoGetAuthorizationInfo(PrincipalCollectionprincipal){

  61. SimpleAuthorizationInfoinfo=newSimpleAuthorizationInfo();

  62. //获取登录用户的Shiro对象—主体身份信息(验权)

  63. ShiroUserAccountshiroUser=(ShiroUserAccount)principal.getPrimaryPrincipal();

  64. //断言,若对象为空则直接抛出异常

  65. Assert.notNull(shiroUser,“找不到principal中的SessionVariable—shiroUser”);

  66. //添加用户拥有的role

  67. addRoles(info,shiroUser);

  68. addPermissions(info,shiroUser);

  69. returninfo;

  70. }

  71. }

3.配置shiro.xml文件:

shiroRealm:

[html] view plain copy

  1. <beanid="shiroRealm"class=“com.**.ShiroRealm”>
  2. <propertyname="casServerUrlPrefix"value=“http://127.0.0.1:8080/SSO”/>
  3. <propertyname="casService"value=“http://127.0.0.1:8585/**/shiro-cas”/>
  4. </bean>

shiroFilter:

[html] view plain copy

  1. <beanid="shiroFilter"class=“org.apache.shiro.spring.web.ShiroFilterFactoryBean”>

  2. <propertyname="securityManager"ref=“securityManager”/>

  3. <spanstyle=“white-space:pre;”></span>

  4. <propertyname="loginUrl"value=“http://127.0.0.1:8080/SSO/loginservice=http://127.0.0.1:8585/**/shiro-cas”/>

  5. <propertyname=“successUrl"value=”"/>

  6. <propertyname=“unauthorizedUrl"value=”/"/>

  7. <propertyname=“filters”>

  8. <spanstyle=“white-space:pre;”></span><map>

  9. <spanstyle=“white-space:pre;”></span><entrykey="casFilter"value-ref=“casFilter”/>

  10. <spanstyle=“white-space:pre;”></span>

  11. <spanstyle=“white-space:pre;”></span><entrykey="logoutFilter"value-ref=“logoutFilter”/>

  12. <spanstyle=“white-space:pre;”></span></map>

  13. </property>

  14. <propertyname=“filterChainDefinitions”>

  15. <value>

  16. /shiro-cas=casFilter

  17. /person/**=authc

  18. </value>

  19. </property>

  20. </bean>

casFilter:

[html] view plain copy

  1. <beanid="casFilter"class=“org.apache.shiro.cas.CasFilter”>
  2. <propertyname="failureUrl"value=“http://127.0.0.1:8080/SSO/loginservice=http://127.0.0.1:8585/themis_front/shiro-cas”/>
  3. <propertyname=“successUrl"value=”/themis/ReviewQuery"/>
  4. </bean>

logoutFilter:

[html] view plain copy

  1. <beanid="logoutFilter"class=“org.apache.shiro.web.filter.authc.LogoutFilter”>
  2. <propertyname="redirectUrl"value=“http://127.0.0.1:8080/SSO/logoutservice=http://127.0.0.1:8585/themis_front/shiro-cas”/>
  3. </bean>

cas针对subject工厂配置:

[html] view plain copy

  1. <beanid="casSubjectFactory"class=“org.apache.shiro.cas.CasSubjectFactory”></bean>

  2. <beanid="securityManager"class=“org.apache.shiro.web.mgt.DefaultWebSecurityManager”>

  3. <propertyname="realm"ref=“shiroRealm”/>

  4. <propertyname="sessionManager"ref=“sessionManager”/>

  5. <propertyname="cacheManager"ref=“shiroCacheManager”/>

  6. <propertyname="subjectFactory"ref=“casSubjectFactory”></property>

  7. </bean>

如下是shiro剩余的基本配置:

[html] view plain copy

  1. <beanid="sessionManager"class=“org.apache.shiro.web.session.mgt.DefaultWebSessionManager”>

  2. <propertyname="globalSessionTimeout"value=“1800000”/>

  3. <propertyname="sessionDAO"ref=“shiroSessionDao”/>

  4. <propertyname="sessionIdCookie"ref=“sharesession”/>

  5. <propertyname="sessionValidationSchedulerEnabled"value=“true”/>

  6. </bean>

  7. <beanid="sharesession"class=“org.apache.shiro.web.servlet.SimpleCookie”>

  8. <constructor-argname="name"value=“SHAREJSESSIONID”/>

  9. <propertyname="maxAge"value=“2592000”/>

  10. </bean>

  11. <beanid="shiroSessionDao"class=“org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO”/>

  12. <beanid="shiroCacheManager"class=“org.apache.shiro.cache.MemoryConstrainedCacheManager”/>

  13. <beanid="lifecycleBeanPostProcessor"class=“org.apache.shiro.spring.LifecycleBeanPostProcessor”/>

  14. <beanclass="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"depends-on=“lifecycleBeanPostProcessor”>

  15. <propertyname="proxyTargetClass"value=“true”/>

  16. </bean>

  17. <beanclass=“org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor”>

  18. <propertyname="securityManager"ref=“securityManager”/>

  19. </bean>

猜你喜欢

转载自blog.csdn.net/m0_67400972/article/details/124504139
今日推荐