shiro实现账号同一时间只能在一处登录(非单点登录)

<bean id="myRealm" class="com.sys.shiro.MyRealm" />

    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO">
    </bean>

<bean id="sessionManager"
        class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="globalSessionTimeout" value="1800000" />
        <property name="deleteInvalidSessions" value="true" />
        <property name="sessionValidationSchedulerEnabled" value="true" />
        <property name="sessionValidationInterval" value="1800000" />
        <property name="sessionIdCookie" ref="sessionIdCookie" />
        <property name="sessionDAO" ref="sessionDAO"/>
    </bean>


<!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->
    <!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->
    <!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="shiroCacheManager" />
        <property name="realm" ref="myRealm" />
        <property name="sessionManager" ref="sessionManager" />
    </bean>
/***
     * 实现用户登录
     * 
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "doLogin")
    public ModelAndView Login(String username, String password) {
        ModelAndView mav = new ModelAndView();
        User user = loginService.getUser(username);
        if (user == null) {
            mav.setViewName("login");
            mav.addObject("msg", "用户不存在");
            return mav;
        }
        if (!user.getPassword().equals(password)) {
            mav.setViewName("login");
            mav.addObject("msg", "账号密码错误");
            return mav;
        }
        Collection<Session> sessions = sessionDao.getActiveSessions();
        for (Session session : sessions) {

            System.out.println("登录用户" + session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
            if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) != null) {
                mav.setViewName("login");
                mav.addObject("msg", "该用户已登录");
                return mav;
            }
        }

        /*
         * SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject())
         * ;
         */
        // 登录后存放进shiro token
        UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);

        // 登录成功后会跳转到successUrl配置的链接,不用管下面返回的链接。
        mav.setViewName("redirect:home");
        return mav;
    }

 

posted @ 2017-09-26 08:53  陈扬天  阅读(7875)  评论(0编辑  收藏  举报