1.配置security-context.xml文件

  1.  
  1. <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
    default-lazy-init="true">
  2.  
  3. <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
    <constructor-arg value="rememberMe"/>
    <property name="httpOnly" value="true"/>
    <property name="maxAge" value="2592000"/><!-- 30天 -->
    </bean>
  4.  
  5. <!-- rememberMe管理器 -->
    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
    <!-- rememberMe cookie加密的密钥 每个项目都不一样 默认AES算法 用下面的代码产生不同的密码
    AesCipherService aes = new AesCipherService();
    byte[] key = aes.generateNewKey().getEncoded();
    String base64 = Base64.encodeToString(key);
    -->
    <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('kbFQXD6nkE8QuvzqlV9UYA==')}"/>
    <property name="cookie" ref="rememberMeCookie"/>
    </bean>
  6.  
  7. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="securityService"/>
    <!-- 可以配置多个Realm,其实会把realms属性赋值给ModularRealmAuthenticator的realms属性 -->
    <!--<property name="realms">-->
    <!--<list>-->
    <!--<ref bean="securityService" />-->
    <!--<ref bean="frontSecurityService"/>-->
    <!--</list>-->
    <!--</property>-->
    <property name="rememberMeManager" ref="rememberMeManager"/>
    <property name="sessionManager" ref="sessionManager"/>
    <!--单点登陆的配置代码开始-->
    <property name="authenticator.authenticationListeners">
    <list>
    <ref bean="securityService"/>
    </list>
    </property>
    <!--单点登陆代码结束-->
    </bean>
  8.  
  9. <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    <property name="sessionValidationInterval" value="60000"/>
    <property name="globalSessionTimeout" value="300000"/>
    </bean>
  10.  
  11. <!-- 配置使用自定义认证器,可以实现多Realm认证,并且可以指定特定Realm处理特定类型的验证 -->
    <!--<bean id="authenticator" class="im.lsn.oss.exhibition.shiro.CustomizedModularRealmAuthenticator">-->
    <!--&lt;!&ndash; 配置认证策略,只要有一个Realm认证成功即可,并且返回所有认证成功信息 &ndash;&gt;-->
    <!--<property name="authenticationStrategy">-->
    <!--<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>-->
    <!--</property>-->
    <!--</bean>-->
  12.  
  13. <!--<bean id="frontSecurityService" class="im.lsn.oss.exhibition.service.FrontSecurityService">-->
    <!--&lt;!&ndash; 配置密码匹配器 &ndash;&gt;-->
    <!--<property name="credentialsMatcher">-->
    <!--<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">-->
    <!--&lt;!&ndash; 加密算法为MD5 &ndash;&gt;-->
    <!--<property name="hashAlgorithmName" value="MD5"></property>-->
    <!--&lt;!&ndash; 加密次数 &ndash;&gt;-->
    <!--<property name="hashIterations" value="1024"></property>-->
    <!--</bean>-->
    <!--</property>-->
    <!--</bean>-->
  14.  
  15. <bean id="formAuthenticationTenantFilter" class="im.lsn.oss.exhibition.web.admin.Security.AdminFilter"/>
    <bean id="frontFilter" class="im.lsn.oss.exhibition.web.front.Security.FrontFilter"/> <bean id="authShiroFilter" class="im.lsn.oss.exhibition.web.filter.AuthShiroFilter"/> <bean id="logout" class="im.lsn.oss.exhibition.web.MyLogoutFilter"> <property name="redirectUrl" value="/jsp/login.jsp"/> <property name="frontRedirectUrl" value="/front/index.do"/> </bean> <bean id="shiroSecurityFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="/jsp/login.jsp"/> <property name="successUrl" value="/jsp/login_success.jsp"/> <property name="filters"> <map> <entry key="authc" value-ref="formAuthenticationTenantFilter"/> <entry key="rolesor" value-ref="authShiroFilter"/> <entry key="logout" value-ref="logout"/> <entry key="front" value-ref="frontFilter"/> </map> </property> <property name="filterChainDefinitions"> <value> /jsp/login.jsp = authc /logout = logout <!--/f/logout = logout--> <!--/jsp/front/user_login.jsp = front--> <!--/front/visitor/user/*= front--> <!--/front/visitor/user_favorites.do=front--> /admin/index.do = rolesor[admin,operator_admin,venue_admin,organizer_admin,exhibitors_admin] /admin/organizer/exhibitorInfoListing.do = rolesor[admin,operator_admin,venue_admin,organizer_admin] /admin/organizer/exhibitorInfoList.do = rolesor[admin,operator_admin,venue_admin,organizer_admin] /admin/organizer/verify.do = rolesor[admin,operator_admin,venue_admin,organizer_admin] /admin/organizer/save_verify.do = rolesor[admin,operator_admin,venue_admin] /admin/organizer/exhibitor_info_index.do = rolesor[admin,operator_admin,venue_admin,organizer_admin] /admin/organizer/fail_exhibitorInfoList.do = rolesor[admin,operator_admin,venue_admin,organizer_admin] /admin/organizer/hotRecommend.do = rolesor[admin,operator_admin,venue_admin] /admin/organizer/identifierList.do = rolesor[admin,operator_admin,venue_admin,organizer_admin] /admin/exhibitors/wait_index.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/booth_index.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/fail_index.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/booth_preview.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/mark.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/save_mark.do = rolesor[admin,operator_admin,organizer_admin] /admin/exhibitors/edit_booth_venue_branch.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/wait_product.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/product_index.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/fail_product.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/product_preview.do = rolesor[admin,operator_admin,organizer_admin,exhibitors_admin] /admin/exhibitors/ProductHotRecommend.do = rolesor[admin,operator_admin,organizer_admin] /admin/information/** = rolesor[admin,operator_admin] /admin/log/** = rolesor[admin,operator_admin] /admin/user/** = rolesor[admin,operator_admin,venue_admin,organizer_admin,exhibitors_admin] /admin/user/index.do = rolesor[admin,operator_admin] /admin/venue/** = rolesor[admin,operator_admin,venue_admin] /admin/organizer/** = rolesor[admin,venue_admin,organizer_admin] /admin/exhibitors/** = rolesor[admin,organizer_admin,exhibitors_admin] /admin/venue/index.do = rolesor[admin,operator_admin] /admin/organizer/index.do = rolesor[admin,venue_admin] /admin/operator/edit.do = rolesor[admin,operator_admin] /admin/** = rolesor[admin] </value> </property> </bean></beans>
  1.  

2.security

  1. import im.lsn.framework.BusinessLogicException;
  2. import im.lsn.framework.jpa.JpaRepositoryImpl;
  3. import im.lsn.framework.shrio.CustomSecurityException;
  4. import im.lsn.oss.exhibition.entity.*;
  5. import im.lsn.oss.exhibition.entity.enumerate.LoginType;
  6. import im.lsn.oss.exhibition.entity.enumerate.VistorType;
  7. import org.apache.shiro.SecurityUtils;
  8. import org.apache.shiro.authc.*;
  9. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
  10. import org.apache.shiro.authz.AuthorizationInfo;
  11. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  12. import org.apache.shiro.realm.AuthorizingRealm;
  13. import org.apache.shiro.session.Session;
  14. import org.apache.shiro.session.mgt.DefaultSessionManager;
  15. import org.apache.shiro.subject.PrincipalCollection;
  16. import org.apache.shiro.subject.Subject;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.context.event.ContextRefreshedEvent;
  21. import org.springframework.context.event.EventListener;
  22. import org.springframework.stereotype.Service;
  23. import org.springframework.transaction.annotation.Transactional;
  24. import org.springframework.util.Assert;
  25. import org.springframework.util.DigestUtils;
  26.  
  27. import javax.annotation.PostConstruct;
  28. import javax.persistence.EntityManager;
  29. import javax.persistence.PersistenceContext;
  30. import java.util.Collection;
  31. import java.util.Date;
  32.  
  33. /**
  34. * Created by fireflyc on 2017/4/26.
  35. */
  36. @Service
  37. @Transactional
  38. public class SecurityService extends AuthorizingRealm implements AuthenticationListener{
  39. private Logger LOGGER = LoggerFactory.getLogger(SecurityService.class);
  40.  
  41. @Autowired
  42. UserService userService;
  43. @Autowired
  44. private ClickedCountService clickedCountService;
  45.  
  46. @Autowired
  47. private DefaultSessionManager sessionManager;
  48.  
  49. @PersistenceContext
  50. protected EntityManager entityManager;
  51. private JpaRepositoryImpl<TbUser, Long> userRepository;
  52. private JpaRepositoryImpl<TbRole, Long> roleRepository;
  53. private JpaRepositoryImpl<TbUserState, Long> userStateLongJpaRepository;
  54. private JpaRepositoryImpl<TbType, Long> typeLongJpaRepository;
  55. private JpaRepositoryImpl<TbExhibitionUser, Long> exhibitionUserLongJpaRepository;
  56.  
  57. @PostConstruct
  58. public void initSecurityService() {
  59. this.userRepository = new JpaRepositoryImpl<TbUser, Long>(TbUser.class, entityManager);
  60. this.roleRepository = new JpaRepositoryImpl<TbRole, Long>(TbRole.class, entityManager);
  61. this.userStateLongJpaRepository = new JpaRepositoryImpl<TbUserState, Long>(TbUserState.class, entityManager);
  62. this.exhibitionUserLongJpaRepository = new JpaRepositoryImpl<TbExhibitionUser, Long>(TbExhibitionUser.class, entityManager);
  63.  
  64. this.typeLongJpaRepository = new JpaRepositoryImpl<TbType, Long>(TbType.class, entityManager);
  65. HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("MD5");
  66. setCredentialsMatcher(matcher);
  67. }
  68.  
  69. @EventListener
  70. public void createAdminAccount(ContextRefreshedEvent event) {
  71. TbRole role = roleRepository.findOne(QTbRole.tbRole.id.eq(1L));
  72. if (role == null) {
  73. role = new TbRole();
  74. role.setRoleName("系统管理员");
  75. role.setRoleCnName("admin");
  76. roleRepository.save(role);
  77. LOGGER.info("创建系统管理员角色");
  78. }
  79.  
  80. TbUser user = userRepository.findOne(QTbUser.tbUser.id.eq(1L));
  81. TbUserState userState = userStateLongJpaRepository.findOne(1L);
  82. TbType type = typeLongJpaRepository.findOne(1L);
  83. if (user == null) {
  84. user = new TbUser();
  85. user.setId(1L);
  86. user.setCreateTime(new Date());
  87. user.setRole(role);
  88. user.setUsername("admin_tontron");
  89. user.setNickname("系统管理员");
  90. String password = "admin_tontron" + DigestUtils.md5DigestAsHex("Tontron1169".getBytes());
  91. user.setPassword(password);
  92. user.setState(userState);
  93. user.setType(type);
  94. userRepository.save(user);
  95. LOGGER.info("创建系统管理员");
  96. }
  97. }
  98.  
  99. @Override
  100. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  101. UserLoginToken userToken = (UserLoginToken) principals.getPrimaryPrincipal();
  102. SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  103. if (userToken.getType().equals(LoginType.ADMIN.toString())) {
  104. authorizationInfo.addRole(userToken.getRole().getRoleName());
  105. } else {
  106. authorizationInfo.addRole(userToken.getFrontRole());
  107. }
  108. return authorizationInfo;
  109. }
  110.  
  111. public void logout() {
  112. SecurityUtils.getSubject().logout();
  113. }
  114.  
  115. @Override
  116. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
  117. if (authcToken instanceof UsernamePasswordToken) {
  118. CustomizedToken token = (CustomizedToken) authcToken;
  119. if (token.getLoginType().equals(LoginType.ADMIN.toString())) {
  120. try {
  121. QTbUser qUser = QTbUser.tbUser;
  122. TbUser user = userRepository.findOne(qUser.username.eq(token.getUsername()));
  123. TbUserState userState = userStateLongJpaRepository.findOne(2L);
  124. if (user == null) {
  125. throw new UnknownAccountException();
  126. }
  127. if (user.getState().getStateName().equals(userState.getStateName())) {
  128. throw new BusinessLogicException("账号被禁用,无法登录");
  129. }
  130. if(null != user.getClickedCount() && 5<user.getClickedCount()){
  131. Integer count = user.getClickedCount();
  132. count++;
  133. clickedCountService.updateClickedCount(user.getId(),count);
  134. throw new BusinessLogicException("登陆失败次数过多,请明天再尝试");
  135. }
  136. LOGGER.info("用户{} 存在", user.getNickname());
  137. String showName = user.getNickname();
  138. if (null == showName || showName.length() == 0) {
  139. showName = userService.searchShowNameForUser(user);
  140. }
  141. UserLoginToken loginToken = new UserLoginToken();
  142. loginToken.setUserId(user.getId());
  143. loginToken.setUserName(user.getUsername());
  144. loginToken.setNickName(user.getNickname());
  145. loginToken.setRole(user.getRole());
  146. loginToken.setShowName(showName);
  147. loginToken.setType(token.getLoginType());
  148. loginToken.setSubUser(user.getSubUser());
  149. return new SimpleAuthenticationInfo(loginToken,
  150. user.getPassword(), getName());
  151. } catch (BusinessLogicException e) {
  152. throw new CustomSecurityException(e.getMessage());
  153. } catch (Exception e) {
  154. LOGGER.error(e.getMessage(), e);
  155. if (e instanceof UnknownAccountException) {
  156. throw new UnknownAccountException();
  157. } else {
  158. throw new CustomSecurityException("用户名或密码错误");
  159. }
  160.  
  161. }
  162. } else {
  163. try {
  164. QTbExhibitionUser qTbExhibitionUser = QTbExhibitionUser.tbExhibitionUser;
  165. TbExhibitionUser exhibitionUser = exhibitionUserLongJpaRepository.findOne(qTbExhibitionUser.phone.eq(token.getUsername()));
  166.  
  167. if (exhibitionUser == null) {
  168. throw new UnknownAccountException();
  169. }
  170. LOGGER.info("用户{} 存在", exhibitionUser.getPhone());
  171. UserLoginToken loginToken = new UserLoginToken();
  172. loginToken.setUserId(exhibitionUser.getId());
  173. loginToken.setUserName(exhibitionUser.getPhone());
  174. loginToken.setFrontRole(VistorType.EXHIBITOR_USER.getName());
  175. loginToken.setShowName(exhibitionUser.getPhone());
  176. loginToken.setType(token.getLoginType());
  177. return new SimpleAuthenticationInfo(loginToken,
  178. exhibitionUser.getPassword(), getName());
  179. } catch (BusinessLogicException e) {
  180. throw new CustomSecurityException(e.getMessage());
  181. } catch (Exception e) {
  182. LOGGER.error(e.getMessage(), e);
  183. throw new CustomSecurityException("用户名或密码错误");
  184. }
  185.  
  186. }
  187.  
  188. }
  189. return null;
  190. }
  191.  
  192. public UserLoginToken getLoginToken() {
  193. try {
  194. Subject subject = SecurityUtils.getSubject();
  195. if (subject == null) {
  196. return null;
  197. }
  198. return (UserLoginToken) subject.getPrincipal();
  199. } catch (Exception e) {
  200. LOGGER.error(e.getMessage(), e);
  201. return null;
  202. }
  203. }
  204.  
  205. public TbUser getLoginUser() {
  206. UserLoginToken loginToken = getLoginToken();
  207. Assert.notNull(loginToken);
  208. TbUser tbUser = userRepository.selectFrom(QTbUser.tbUser)
  209. .where(QTbUser.tbUser.id.eq(loginToken.getUserId())).fetchOne();
  210. return tbUser;
  211. }
  212.  
  213. public TbExhibitionUser getFrontLoginUser() {
  214. UserLoginToken loginToken = getLoginToken();
  215. Assert.notNull(loginToken);
  216. TbExhibitionUser exhibitionUser = exhibitionUserLongJpaRepository.selectFrom(QTbExhibitionUser.tbExhibitionUser)
  217. .where(QTbExhibitionUser.tbExhibitionUser.id.eq(loginToken.getUserId())).fetchOne();
  218. return exhibitionUser;
  219. }
  220.  
  221. //单点登陆的java代码
  222. public void onSuccess(AuthenticationToken token, AuthenticationInfo info){
  223. Subject subject = SecurityUtils.getSubject();
  224. UsernamePasswordToken loginToken = (UsernamePasswordToken) token;
  225. Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();
  226. for (Session session : sessions) {
  227. Subject sub = new Subject.Builder().session(session).buildSubject();
  228. if (sub.isAuthenticated()) {
  229. UserLoginToken other = (UserLoginToken) sub.getPrincipal();
  230. if (other.getUserName().equals(loginToken.getUsername())) {
  231. if (!session.getId().equals(subject.getSession().getId())) {
  232. session.stop();
  233. }
  234. }
  235. }
  236. }
  237. }
  238.  
  239. public void onFailure(AuthenticationToken var1, AuthenticationException var2){
  240.  
  241. }
  242.  
  243. public void onLogout(PrincipalCollection var1){
  244.  
  245. }
  246. //单点登陆的java代码结束
  247. }

sessionId控制单点登陆的更多相关文章

  1. 集成基于OAuth协议的单点登陆

    在之前的一篇文章中,我们已经介绍了如何为一个应用添加对CAS协议的支持,进而使得我们的应用可以与所有基于CAS协议的单点登陆服务通讯.但是现在的单点登陆服务实际上并不全是通过实现CAS协议来完成的.例 ...

  2. Lind.DDD.SSO单点登陆组件的使用(原创)

    回到目录 一般sso的说明 在Lind.DDD框架里,有对单点登陆的集成,原理就是各个网站去sso网站统一登陆授权,之后在sso网站将登陆的token进行存储,存储方式随你(cache,redis,m ...

  3. cookie+memcached实现单点登陆

    10年的时候在iteye的第一篇文章记录了一下当时怎么实现我们系统的单点登陆.不过那个时候文章写的不好,思路也很浮躁,很难看懂,在csdn的第一篇技术博客打算重新温顾一下当时实现单点登陆的思路.先来看 ...

  4. 在tomcat集群下利用redis实现单点登陆

    场景:比如说我们要实现一个集群环境,无非是把多个项目部署到多个tomcat下,然后按照一定的算法,轮询什么的随机访问多个tomcat服务器,但是问题也会有许多,比如说,我们最开始是把登陆人的信息存放到 ...

  5. PHP单点登陆

    本文主要介绍了利用webservice,session,cookie技术,来进行通用的单点登录系统的分析与设计.具体实现语言为PHP.单点 登录,英文名为Single Sign On,简称为 SSO, ...

  6. 在多点环境下使用cas实现单点登陆及登出

    CAS 介绍 CAS 是 Yale 大学发起的一个开源项目,旨在为 Web 应用系统提供一种可靠的单点登录方法,CAS 在 2004 年 12 月正式成为 JA-SIG 的一个项目.CAS 具有以下特 ...

  7. session问题总既然(深入理解)&Token问题理解&sso单点登陆理解实现

    一.Session使http协议成为有状态协议(浏览器cookie本地这个session,服务器端也有这个session) 1.ajax前端登陆无法保存session,造成无法维持登陆状态(http本 ...

  8. 单点登陆(SSO)

    一.背景 在企业发展初期,企业使用的系统很少,通常一个或者两个,每个系统都有自己的登录模块,运营人员每天用自己的账号登录,很方便.但随着企业的发展,用到的系统随之增多,运营人员在操作不同的系统时,需要 ...

  9. 集成基于CAS协议的单点登陆

    相信大家对单点登陆(SSO,Single Sign On)这个名词并不感到陌生吧?简单地说,单点登陆允许多个应用使用同一个登陆服务.一旦一个用户登陆了一个支持单点登陆的应用,那么在进入其它使用同一单点 ...

随机推荐

  1. 推荐WEB 端批量移动设备管理控制工具STF

    推荐WEB 端批量移动设备管理控制工具STF 1 官方网站 https://openstf.io/ 2 github https://github.com/openstf/stf 后面有时间了,抽空也 ...

  2. 关于App收集个人信息基本规范,这里公开征求你的意见!

    关于App收集个人信息基本规范,这里公开征求你的意见! https://www.thepaper.cn/newsDetail_forward_4122573 以后国家开始规范App收集个信息基本规范, ...

  3. 去掉DataGridView最后一行的空白行,删除空白行

    //不显示出dataGridView1的最后一行空白   dataGridView1.AllowUserToAddRows = false;       直接在LODE事件

  4. Nginx php上传文件大小的设置

  5. centos7.x下环境搭建(一)--yum方式安装mysql5.7

    前两天因为数据库被黑客攻击,导致数据被删除,数据库被损坏,系统重新安装了一下,所以环境也需要重新再搭一遍,包括mysql.nodejs.git.nginx和redis的安装.由于之前安装的mysql安 ...

  6. [原创]SpringSecurity控制授权(鉴权)功能介绍

    1.spring security 过滤器链 ​ spring security中的除了用户登录校验相关的过滤器,最后还包含了鉴权功能的过滤器,还有匿名资源访问的过滤器链,相关的图解如下: 2.控制授 ...

  7. C#通过字符串分割字符串Split

    string[] strArr = str.Split(new[] {"****==="},StringSplitOptions.None); 更多内容关注公众号 洛水梅家

  8. 使用XSSFWorkbook 读取excel

    工作中用到 使用XSSFWorkbook 读取excel 具体代码如下, private (List<(string columnName, string colomnDescription)& ...

  9. [個人紀錄] RabbitMQ安裝

    參考資料 https://blog.csdn.net/tjcyjd/article/details/77150893 https://blog.csdn.net/u014308482/article/ ...

  10. python3 + robotframework ride 乱码问题

    执行ride时乱码问题 如果被执行的文件所在路径中含有中文,执行时可能会报如下错误 robotframework版本:robotframework-ride 1.7.3.1python 3.7.3 解 ...