Java Code Examples for org.apache.shiro.authc.UsernamePasswordToken#setRememberMe()

The following examples show how to use org.apache.shiro.authc.UsernamePasswordToken#setRememberMe() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoginController.java    From yyblog with MIT License 6 votes vote down vote up
@Log("登陆验证")
@PostMapping("/login")
@ResponseBody
public YYBlogResult login(String username, String password, Boolean rememberMe) {
    if (rememberMe == null) {
        rememberMe = false;
    }
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    Subject subject = SecurityUtils.getSubject();
    try {
        token.setRememberMe(rememberMe);
        subject.login(token);
    } catch (Exception e) {
        return YYBlogResult.build(ResultEnum.UNKONW_ERROR.getCode(), e.getMessage());
    }
    return YYBlogResult.ok();
}
 
Example 2
Source File: UserController.java    From MyBlog with Apache License 2.0 6 votes vote down vote up
@PostMapping("login")
@ResponseBody
public MyResponse login(@NotBlank String username, @NotBlank String password, boolean rememberMe) {
    try {
        //shiro通过SecurityUtils.getSubject()获得主体,主体可以理解为客户端实例,原理在后面讲
        Subject subject = SecurityUtils.getSubject();
        //已经认证过,也就是该客户端已经登陆过
        if (subject.isAuthenticated()) {
            return MyResponse.createResponse(ResponseEnum.ALREADY_LOGIN);
        }
        //一般都使用UsernamePasswordToken,shiro的token中有Principal和Credentials的概念
        //Principal代表当前客户端要登录的用户,Credentials代表证明该用户身份的凭证
        //UsernamePasswordToken将username作为Principal,password作为Credentials
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //rememberMe功能后面讲
        token.setRememberMe(rememberMe);
        subject.login(token);
        return MyResponse.createResponse(ResponseEnum.SUCC);
    } catch (AuthenticationException e) {
        // 用户名或密码错误,不应该明确返回到底是用户不存在还是密码错误
        return MyResponse.createResponse(ResponseEnum.ILLEGAL_PARAM);
    }
}
 
Example 3
Source File: SecurityManagerAssociatingFilter.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
private Response authenticate(UriInfo info, String user, String password) {
    
    _LOG.debug("Received a login request for user {}", user);
    
    Subject currentUser = SecurityUtils.getSubject();
    
    ResponseBuilder rb;
    
    if (!currentUser.isAuthenticated()) {
        _LOG.debug("Authenticating user {}", user);
        UsernamePasswordToken token = new UsernamePasswordToken(user, password);
        token.setRememberMe(true);
        currentUser.login(token);
        
        rb = Response.ok()
                .cookie(new NewCookie(SESSION_COOKIE_NAME, currentUser.getSession().getId().toString(), 
                        info.getBaseUri().getPath(), null, -1, null, -1, null, false, true));
    } else {
        _LOG.debug("The login request for user {} was already authenticated as user {}", user, currentUser.getPrincipal());
        rb = Response.status(Status.CONFLICT);
    }
    return rb.build();
}
 
Example 4
Source File: ApiServiceImpl.java    From wangmarket with Apache License 2.0 6 votes vote down vote up
public UserVO identityVerifyAndSession(String key) {
	UserVO vo = identityVerify(key);
	if(vo.getResult() - UserVO.FAILURE == 0){
		return vo;
	}
	
	UsernamePasswordToken token = new UsernamePasswordToken(vo.getUser().getUsername(), vo.getUser().getUsername());
       token.setRememberMe(false);
	Subject currentUser = SecurityUtils.getSubject();  
	
	try {  
		currentUser.login(token);  
	} catch ( UnknownAccountException uae ) {
		uae.printStackTrace();
	} catch ( IncorrectCredentialsException ice ) {
		ice.printStackTrace();
	} catch ( LockedAccountException lae ) {
		lae.printStackTrace();
	} catch ( ExcessiveAttemptsException eae ) {
		eae.printStackTrace();
	} catch ( org.apache.shiro.authc.AuthenticationException ae ) { 
		ae.printStackTrace();
	}
	
	return vo;
}
 
Example 5
Source File: LoginController.java    From WebStack-Guns with MIT License 5 votes vote down vote up
/**
 * 点击登录执行的动作
 */
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginVali() {

    String username = super.getPara("username").trim();
    String password = super.getPara("password").trim();
    String remember = super.getPara("remember");

    //验证验证码是否正确
    if (KaptchaUtil.getKaptchaOnOff()) {
        String kaptcha = super.getPara("kaptcha").trim();
        String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
            throw new InvalidKaptchaException();
        }
    }

    Subject currentUser = ShiroKit.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());

    if ("on".equals(remember)) {
        token.setRememberMe(true);
    } else {
        token.setRememberMe(false);
    }

    currentUser.login(token);

    ShiroUser shiroUser = ShiroKit.getUser();
    super.getSession().setAttribute("shiroUser", shiroUser);
    super.getSession().setAttribute("username", shiroUser.getAccount());

    LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), getIp()));

    ShiroKit.getSession().setAttribute("sessionFlag", true);

    return REDIRECT + "/admin";
}
 
Example 6
Source File: ShiroAuthenticator.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse authenticateRequest(Channel channel, String username, String password, String isPublic, ByteBuf responseContentIfSuccess) {
   UsernamePasswordToken token = new UsernamePasswordToken(username, password);
   token.setHost(((InetSocketAddress) channel.remoteAddress()).getHostString());
   token.setRememberMe(!"true".equalsIgnoreCase(isPublic));
   return authenticateRequest(channel, token, responseContentIfSuccess);
}
 
Example 7
Source File: UserServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
@Override
public ResponseEntity login(String name, String passwd) {
    User user =
            mongoTemplate.findOne(
                    Query.query(
                            new Criteria()
                                    .orOperator(Criteria.where("name").is(name), Criteria.where("mail").is(name))),
                    User.class,
                    "user");
    if (user == null) {
        return new ResponseEntity<>(new Result<String>(ResultEnum.LOGIN_FAILED), HttpStatus.UNAUTHORIZED);
    }
    String inputName = user.getName();
    String encodedPassword = new Md5Hash(passwd, inputName).toHex();
    Subject subject = SecurityUtils.getSubject();

    User tempUser = userRepository.findByName(inputName);
    if (tempUser == null) {
        return new ResponseEntity<>(new Result(ResultEnum.LOGIN_FAILED), HttpStatus.UNAUTHORIZED);
    }

    if (tempUser.getPassword() == null) {
        tempUser.setPassword(encodedPassword);
        userRepository.save(tempUser);
    }

    UsernamePasswordToken token = new UsernamePasswordToken(inputName, encodedPassword);
    token.setRememberMe(true);
    subject.login(token);
    String role = getRole(inputName);
    UserServiceImpl.logger.info("{}:{} 登录成功", role, inputName);
    return new ResponseEntity<>(new Result(ResultEnum.LOGIN_SUCCEED, getUserInfo()), HttpStatus.OK);
}
 
Example 8
Source File: LoginController.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
/**
 * 点击登录执行的动作
 */
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginVali() {

    String username = super.getPara("username").trim();
    String password = super.getPara("password").trim();
    String remember = super.getPara("remember");

    //验证验证码是否正确
    if (KaptchaUtil.getKaptchaOnOff()) {
        String kaptcha = super.getPara("kaptcha").trim();
        String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
            throw new InvalidKaptchaException();
        }
    }

    Subject currentUser = ShiroKit.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());

    if ("on".equals(remember)) {
        token.setRememberMe(true);
    } else {
        token.setRememberMe(false);
    }

    currentUser.login(token);

    ShiroUser shiroUser = ShiroKit.getUser();
    super.getSession().setAttribute("shiroUser", shiroUser);
    super.getSession().setAttribute("username", shiroUser.getAccount());

    LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), getIp()));

    ShiroKit.getSession().setAttribute("sessionFlag", true);

    return REDIRECT + "/";
}
 
Example 9
Source File: AccountServiceImpl.java    From VideoMeeting with Apache License 2.0 5 votes vote down vote up
@Transactional
@Override
public User login(String username, String password) throws IncorrectCredentialsException{
	UsernamePasswordToken token = new UsernamePasswordToken();
	token.setUsername(username);
	token.setPassword(password.toCharArray());
	token.setRememberMe(true);
	SecurityUtils.getSubject().login(token);
	if (SecurityUtils.getSubject().isAuthenticated()) {
		SecurityUtils.getSubject().getSession().setAttribute("username", username);
		return userDao.get("from User u where u.username = ?",
				new String[] { username });
	}
	return null;
}
 
Example 10
Source File: Main.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        IniRealm realm = new IniRealm();
        Ini ini = Ini.fromResourcePath(Main.class.getResource("/com/baeldung/shiro/permissions/custom/shiro.ini").getPath());
        realm.setIni(ini);
        realm.setPermissionResolver(new PathPermissionResolver());
        realm.init();
        SecurityManager securityManager = new DefaultSecurityManager(realm);

        SecurityUtils.setSecurityManager(securityManager);
        Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
          UsernamePasswordToken token = new UsernamePasswordToken("paul.reader", "password4");
          token.setRememberMe(true);
          try {
              currentUser.login(token);
          } catch (UnknownAccountException uae) {
              log.error("Username Not Found!", uae);
          } catch (IncorrectCredentialsException ice) {
              log.error("Invalid Credentials!", ice);
          } catch (LockedAccountException lae) {
              log.error("Your Account is Locked!", lae);
          } catch (AuthenticationException ae) {
              log.error("Unexpected Error!", ae);
          }
        }

        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        if (currentUser.hasRole("admin")) {
            log.info("Welcome Admin");
        } else if(currentUser.hasRole("editor")) {
            log.info("Welcome, Editor!");
        } else if(currentUser.hasRole("author")) {
            log.info("Welcome, Author");
        } else {
            log.info("Welcome, Guest");
        }

        if(currentUser.isPermitted("/articles/drafts/new-article")) {
            log.info("You can access articles");
        } else {
            log.info("You cannot access articles!");
        }
        currentUser.logout();
    }
 
Example 11
Source File: Main.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        Realm realm = new MyCustomRealm();
        SecurityManager securityManager = new DefaultSecurityManager(realm);

        SecurityUtils.setSecurityManager(securityManager);
        Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
          UsernamePasswordToken token 
            = new UsernamePasswordToken("user", "password");
          token.setRememberMe(true);
          try {
              currentUser.login(token);
          } catch (UnknownAccountException uae) {
              log.error("Username Not Found!", uae);
          } catch (IncorrectCredentialsException ice) {
              log.error("Invalid Credentials!", ice);
          } catch (LockedAccountException lae) {
              log.error("Your Account is Locked!", lae);
          } catch (AuthenticationException ae) {
              log.error("Unexpected Error!", ae);
          }
        }

        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        if (currentUser.hasRole("admin")) {
            log.info("Welcome Admin");
        } else if(currentUser.hasRole("editor")) {
            log.info("Welcome, Editor!");
        } else if(currentUser.hasRole("author")) {
            log.info("Welcome, Author");
        } else {
            log.info("Welcome, Guest");
        }

        if(currentUser.isPermitted("articles:compose")) {
            log.info("You can compose an article");
        } else {
            log.info("You are not permitted to compose an article!");
        }

        if(currentUser.isPermitted("articles:save")) {
            log.info("You can save articles");
        } else {
            log.info("You can not save articles");
        }

        if(currentUser.isPermitted("articles:publish")) {
            log.info("You can publish articles");
        } else {
            log.info("You can not publish articles");
        }

        Session session = currentUser.getSession();
        session.setAttribute("key", "value");
        String value = (String) session.getAttribute("key");
        if (value.equals("value")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        currentUser.logout();

        System.exit(0);
    }
 
Example 12
Source File: StandaloneShiroTest.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Test
public void test()
{
    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    Session session = currentUser.getSession();
    session.setAttribute( "someKey", "aValue" );
    String value = ( String ) session.getAttribute( "someKey" );
    assertEquals( "aValue", value );
    LOG.info( "Retrieved the correct value! [" + value + "]" );

    // let's login the current user so we can check against roles and permissions:
    if ( !currentUser.isAuthenticated() ) {
        UsernamePasswordToken token = new UsernamePasswordToken( "lonestarr", "vespa" );
        token.setRememberMe( true );
        try {
            currentUser.login( token );
        } catch ( UnknownAccountException uae ) {
            fail( "There is no user with username of " + token.getPrincipal() );
        } catch ( IncorrectCredentialsException ice ) {
            fail( "Password for account " + token.getPrincipal() + " was incorrect!" );
        } catch ( LockedAccountException lae ) {
            fail( "The account for username " + token.getPrincipal() + " is locked.  "
                  + "Please contact your administrator to unlock it." );
        } // ... catch more exceptions here (maybe custom ones specific to your application?
        catch ( AuthenticationException ae ) {
            //unexpected condition?  error?
            throw ae;
        }
    }

    //say who they are:
    //print their identifying principal (in this case, a username):
    assertNotNull( currentUser.getPrincipal() );
    LOG.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );

    //test a role:
    if ( currentUser.hasRole( "schwartz" ) ) {
        LOG.info( "May the Schwartz be with you!" );
    } else {
        fail( "Hello, mere mortal." );
    }

    //test a typed permission (not instance-level)
    if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
        LOG.info( "You may use a lightsaber ring.  Use it wisely." );
    } else {
        fail( "Sorry, lightsaber rings are for schwartz masters only." );
    }

    //a (very powerful) Instance Level permission:
    if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
        LOG.info( "You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                  + "Here are the keys - have fun!" );
    } else {
        fail( "Sorry, you aren't allowed to drive the 'eagle5' winnebago!" );
    }

    //all done - log out!
    currentUser.logout();
}
 
Example 13
Source File: UserServiceImpl.java    From wangmarket with Apache License 2.0 4 votes vote down vote up
public BaseVO loginForUserId(HttpServletRequest request, int userId) {
		BaseVO baseVO = new BaseVO();
		User user = sqlDAO.findById(User.class, userId);
		if(user == null){
			Log.debug("用户不存在");
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneUserNotFind"));
			return baseVO;
		}
		
		//检验此用户状态是否正常,是否被冻结
		if(user.getIsfreeze() == User.ISFREEZE_FREEZE){
			Log.debug("此用户被冻结,无法设置为登陆用户");
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze"));
			return baseVO;
		}
		
		/*******更改User状态******/
		user.setLasttime(DateUtil.timeForUnix10());
		user.setLastip(IpUtil.getIpAddress(request));
		sqlDAO.save(user);
		Log.debug("设置指定userId为登陆用户,设置后得User:"+user);
		
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername());
        token.setRememberMe(false);
		Subject currentUser = SecurityUtils.getSubject();  
		
		try {  
			currentUser.login(token);  
		} catch ( UnknownAccountException uae ) {
			uae.printStackTrace();
		} catch ( IncorrectCredentialsException ice ) {
			ice.printStackTrace();
		} catch ( LockedAccountException lae ) {
			lae.printStackTrace();
		} catch ( ExcessiveAttemptsException eae ) {
			eae.printStackTrace();
		} catch ( org.apache.shiro.authc.AuthenticationException ae ) { 
			ae.printStackTrace();
		}
		
//		logDao.insert("USER_LOGIN_SUCCESS");
		baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess"));
		return baseVO;
	}
 
Example 14
Source File: UserServiceImpl.java    From wangmarket with Apache License 2.0 4 votes vote down vote up
public BaseVO loginByUserid(HttpServletRequest request, int userid) {
		BaseVO baseVO = new BaseVO();
		
		User user = sqlDAO.findById(User.class, userid);
		if(user == null){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneUserNotFind"));
			return baseVO;
		}
		
		//ip检测
		String ip = IpUtil.getIpAddress(request);
		if(!(user.getLastip().equals(ip) || user.getRegip().equals(ip))){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneIpFailure"));
			return baseVO;
		}
		
		//检验此用户状态是否正常,是否被冻结
		if(user.getIsfreeze() == User.ISFREEZE_FREEZE){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze"));
			return baseVO;
		}
		
		/*******更改User状态******/
		user.setLasttime(DateUtil.timeForUnix10());
		user.setLastip(IpUtil.getIpAddress(request));
		sqlDAO.save(user);
		
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername());
        token.setRememberMe(false);
		Subject currentUser = SecurityUtils.getSubject();  
		
		try {  
			currentUser.login(token);  
		} catch ( UnknownAccountException uae ) {
			uae.printStackTrace();
		} catch ( IncorrectCredentialsException ice ) {
			ice.printStackTrace();
		} catch ( LockedAccountException lae ) {
			lae.printStackTrace();
		} catch ( ExcessiveAttemptsException eae ) {
			eae.printStackTrace();
		} catch ( org.apache.shiro.authc.AuthenticationException ae ) { 
			ae.printStackTrace();
		}
		
//		logDao.insert("USER_LOGIN_SUCCESS");
		baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess"));
		return baseVO;
	}
 
Example 15
Source File: UserServiceImpl.java    From wangmarket with Apache License 2.0 4 votes vote down vote up
/**
	 * 手机号登陆,会自动检测上次登陆的ip,若上次登陆的ip跟当前的ip一样,则这个手机用户登陆成功
	 * @param request {@link HttpServletRequest} 
	 * 		<br/>登陆时form表单需提交两个参数:phone(手机号)、code(手机收到的动态验证码)
	 * @return {@link BaseVO}
	 */
	public BaseVO loginByPhone(HttpServletRequest request) {
		BaseVO baseVO = new BaseVO();
		String phone = Safety.filter(request.getParameter("phone"));
		if(phone==null){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhonePhoneFailure"));
			return baseVO;
		}else{
			phone = phone.replaceAll(" ", "");
			if(phone.length() != 11){
				baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhonePhoneFailure"));
				return baseVO;
			}
		}
		
		User user = findByPhone(phone);
		if(user == null){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneUserNotFind"));
			return baseVO;
		}
		
		//ip检测
		String ip = IpUtil.getIpAddress(request);
		if(!(user.getLastip().equals(ip) || user.getRegip().equals(ip))){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneIpFailure"));
			return baseVO;
		}
		
		//检验此用户状态是否正常,是否被冻结
		if(user.getIsfreeze() == User.ISFREEZE_FREEZE){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze"));
			return baseVO;
		}
		Log.debug("检验此用户状态是否正常,是否被冻结,未冻结,正常");
		
		/*******更改User状态******/
		user.setLasttime(DateUtil.timeForUnix10());
		user.setLastip(IpUtil.getIpAddress(request));
		sqlDAO.save(user);
		Log.debug("更新User状态,更新后的User为:"+user);
		
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername());
        token.setRememberMe(false);
		Subject currentUser = SecurityUtils.getSubject();  
		
		try {  
			currentUser.login(token);  
		} catch ( UnknownAccountException uae ) {
			uae.printStackTrace();
		} catch ( IncorrectCredentialsException ice ) {
			ice.printStackTrace();
		} catch ( LockedAccountException lae ) {
			lae.printStackTrace();
		} catch ( ExcessiveAttemptsException eae ) {
			eae.printStackTrace();
		} catch ( org.apache.shiro.authc.AuthenticationException ae ) { 
			ae.printStackTrace();
		}
		
//		logDao.insert("USER_LOGIN_SUCCESS");
		baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess"));
		return baseVO;
	}
 
Example 16
Source File: UserServiceImpl.java    From wangmarket with Apache License 2.0 4 votes vote down vote up
/**
	 * 手机号+动态验证码登陆
	 * @param request {@link HttpServletRequest} 
	 * 		<br/>登陆时form表单需提交两个参数:phone(手机号)、code(手机收到的动态验证码)
	 * @return {@link BaseVO}
	 */
	public BaseVO loginByPhoneAndCode(HttpServletRequest request) {
		BaseVO baseVO = new BaseVO();
		String phone = Safety.filter(request.getParameter("phone"));
		String code = Safety.filter(request.getParameter("code"));
		if(phone==null || phone.length() != 11){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneAndCodePhoneFailure"));
			return baseVO;
		}
		if(code==null || code.length() != 6){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneAndCodeCodeFailure"));
			return baseVO;
		}
		
		int queryAddtime = 0;
		if(SmsLog.codeValidity > 0){
			int currentTime = DateUtil.timeForUnix10();
			queryAddtime = currentTime-SmsLog.codeValidity;
		}
		SmsLog smsLog = findByPhoneAddtimeUsedTypeCode(phone, queryAddtime, SmsLog.USED_FALSE, SmsLog.TYPE_LOGIN,code);
    	if(smsLog != null){
    		User user = findByPhone(phone);
    		int userid = 0;
    		if(user != null && user.getId() != null){
    			userid = user.getId();
    		}
    		
    		/****更改SmsLog状态*****/
    		smsLog.setUserid(userid);
    		smsLog.setUsed(SmsLog.USED_TRUE);
    		sqlDAO.save(smsLog);
    		
    		//如果没有用户,则直接返回失败提示
    		if(user == null){
    			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneAndCodeRegFailure"));
    			return baseVO;
    		}
    		
    		//检验此用户状态是否正常,是否被冻结
			if(user.getIsfreeze() == User.ISFREEZE_FREEZE){
				baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze"));
				return baseVO;
			}
    		
    		
    		/*******更改User状态******/
    		user.setLasttime(DateUtil.timeForUnix10());
    		user.setLastip(IpUtil.getIpAddress(request));
    		sqlDAO.save(user);
    		
			UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername());
	        token.setRememberMe(false);
			Subject currentUser = SecurityUtils.getSubject();  
			
			try {  
				currentUser.login(token);  
			} catch ( UnknownAccountException uae ) {
				uae.printStackTrace();
			} catch ( IncorrectCredentialsException ice ) {
				ice.printStackTrace();
			} catch ( LockedAccountException lae ) {
				lae.printStackTrace();
			} catch ( ExcessiveAttemptsException eae ) {
				eae.printStackTrace();
			} catch ( org.apache.shiro.authc.AuthenticationException ae ) { 
				ae.printStackTrace();
			}
			
//			logDao.insert("USER_LOGIN_SUCCESS");
			baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess"));
			return baseVO;
    	}else{
    		baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneAndCodeCodeNotFind"));
    		return baseVO;
    	}
	}
 
Example 17
Source File: UserServiceImpl.java    From wangmarket with Apache License 2.0 4 votes vote down vote up
public BaseVO loginByUsernameAndPassword(HttpServletRequest request, String username, String password){
		username = Safety.filter(username);
		
		BaseVO baseVO = new BaseVO();
		if(username==null || username.length() == 0 ){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserOrEmailNotNull"));
			return baseVO;
		}
		if(password==null || password.length() == 0){
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginPasswordNotNull"));
			return baseVO;
		}
		
		//判断是用户名还是邮箱登陆的,进而查询邮箱或者用户名,进行登录
		List<User> l = sqlDAO.findByProperty(User.class, username.indexOf("@")>-1? "email":"username", username);
		
		if(l!=null && l.size()>0){
			User user = l.get(0);
			
			String md5Password = new Md5Hash(password, user.getSalt(),Global.USER_PASSWORD_SALT_NUMBER).toString();
			//检验密码是否正确
			if(md5Password.equals(user.getPassword())){
				//检验此用户状态是否正常,是否被冻结
				if(user.getIsfreeze() == User.ISFREEZE_FREEZE){
					baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze"));
					return baseVO;
				}
				
				user.setLasttime(DateUtil.timeForUnix10());
				user.setLastip(IpUtil.getIpAddress(request));
				sqlDAO.save(user);
				
				UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername());
		        token.setRememberMe(false);
				Subject currentUser = SecurityUtils.getSubject();  
				try {
					currentUser.login(token);  
				} catch ( UnknownAccountException uae ) {
					java.lang.System.out.println("UnknownAccountException:"+uae.getMessage());
				} catch ( IncorrectCredentialsException ice ) {
					java.lang.System.out.println("IncorrectCredentialsException:"+ice.getMessage());
				} catch ( LockedAccountException lae ) {
					java.lang.System.out.println("LockedAccountException:"+lae.getMessage());
				} catch ( ExcessiveAttemptsException eae ) {
					java.lang.System.out.println("ExcessiveAttemptsException:"+eae.getMessage());
				} catch ( org.apache.shiro.authc.AuthenticationException ae ) {  
					java.lang.System.out.println("AuthenticationException:"+ae.getMessage());
				}
//				logDao.insert("USER_LOGIN_SUCCESS");
				baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess"));
			}else{
				baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginPasswordFailure"));
			}
		}else{
			baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserNotFind"));
		}
		
		return baseVO;
	}
 
Example 18
Source File: UserServiceImpl.java    From belling-admin with Apache License 2.0 4 votes vote down vote up
@Transactional
@Override
public ResponseResult login(String ip, String account, String password, Boolean rememberMe) {
	ResponseResult result = ResponseResult.createSuccessResult();
	User user = findByAccount(account);
	if (user == null) {
		result.setCode(ResponseCode.ERROR).setMessage("登录名不存在");
	} else if (!user.getPassword().equals(password)) {
		result.setCode(ResponseCode.ERROR).setMessage("密码不正确");
	} else if (!user.getIsEnable()) {
		result.setCode(ResponseCode.ERROR).setMessage("已被管理员禁用");
	} else {
		// 是否允许多地登录
		String multLogin = settingsService.getValueByKey("mult_login");
		
		// 判断是否已登录
		boolean rs = userOnlineService.hasLogin(account);
		// 不允许
		if ("0".equals(multLogin)) {
			// 是否允许多地登录
			String killLogin = settingsService.getValueByKey("kill_login");
			// 不允许挤掉之前用户登录
			if ("0".equals(killLogin)) {
				// 判断是否已经登录
				if (rs) {
					result.setCode(ResponseCode.ERROR).setMessage("账号已在另外一处地点登录,请先下线再登录");
					return result;
				}
			} 
			// 踢出之前登录用户
			if (rs) {
				userOnlineService.kickoutByAccount(account);
			}
		} 
		
		// 登录
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), password);
		currentUser.login(token);// 登录认证 记录登陆信息
		token.setRememberMe(rememberMe);
		System.out.println("****登陆成功*****");
		
		user.setLastLoginIp(ip);
		user.setLoginCount(user.getLoginCount() + 1);
		user.setLastLoginTime(new Date());
		mapper.update(user);
		
		
		// 记录日志
		LoginLog log = new LoginLog();
		log.setUserId(user.getAccount());
		log.setLoginType((short) 1);
		log.setLoginDesc("登录成功");
		log.setIpInfoCountry(null);
		log.setIpInfoRegion(null);
		log.setIpInfoCity(null);
		log.setIpInfoIsp(null);
		log.setLoginIp(ip);
		log.setLoginTime(new Timestamp(new Date().getTime()));
		
		// 保存登录日志
		loginLogMapper.insert(log);
		
		Session session = currentUser.getSession();
		session.setAttribute("user", user);
		session.setAttribute("userid", user.getAccount());
		// session.setAttribute("kickout", false); // 标记是否下线  
	}
	return result;
}
 
Example 19
Source File: UserController.java    From demo-springmvc-shiro with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(String username, String password, HttpServletRequest request){
    System.out.println("-------------------------------------------------------");
    String rand = (String)request.getSession().getAttribute("rand");
    String captcha = WebUtils.getCleanParam(request, "captcha");
    System.out.println("用户["+username+"]登录时输入的验证码为["+captcha+"],HttpSession中的验证码为["+rand+"]");
    if(!StringUtils.equals(rand, captcha)){
        request.setAttribute("message_login", "验证码不正确");
        return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
    }
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    token.setRememberMe(true);
    System.out.print("为验证登录用户而封装的Token:");
    System.out.println(ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
    //获取当前的Subject
    Subject currentUser = SecurityUtils.getSubject();
    try {
        //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
        //每个Realm都能在必要时对提交的AuthenticationTokens作出反应
        //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
        System.out.println("对用户[" + username + "]进行登录验证...验证开始");
        currentUser.login(token);
        System.out.println("对用户[" + username + "]进行登录验证...验证通过");
    }catch(UnknownAccountException uae){
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,未知账户");
        request.setAttribute("message_login", "未知账户");
    }catch(IncorrectCredentialsException ice){
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,错误的凭证");
        request.setAttribute("message_login", "密码不正确");
    }catch(LockedAccountException lae){
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,账户已锁定");
        request.setAttribute("message_login", "账户已锁定");
    }catch(ExcessiveAttemptsException eae){
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,错误次数过多");
        request.setAttribute("message_login", "用户名或密码错误次数过多");
    }catch(AuthenticationException ae){
        //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,堆栈轨迹如下");
        ae.printStackTrace();
        request.setAttribute("message_login", "用户名或密码不正确");
    }
    //验证是否登录成功
    if(currentUser.isAuthenticated()){
        System.out.println("用户[" + username + "]登录认证通过(这里可进行一些认证通过后的系统参数初始化操作)");
        return "main";
    }else{
        token.clear();
        return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
    }
}