Example usage for org.apache.shiro.authc UsernamePasswordToken clear

List of usage examples for org.apache.shiro.authc UsernamePasswordToken clear

Introduction

In this page you can find the example usage for org.apache.shiro.authc UsernamePasswordToken clear.

Prototype

public void clear() 

Source Link

Document

Clears out (nulls) the username, password, rememberMe, and inetAddress.

Usage

From source file:beans.ShiroLoginBean.java

/**
 * Try and authenticate the user// w ww .  ja  va 2s.  c  o m
 */
public void doLogin() {
    Subject subject = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try {
        subject.login(token);

        if (subject.hasRole("admin")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("admin/index.xhtml");
        } else {
            FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
        }
    } catch (UnknownAccountException ex) {
        facesError("Unknown account");
        //log.error(ex.getMessage(), ex);
    } catch (IncorrectCredentialsException ex) {
        facesError("Wrong password");
        //log.error(ex.getMessage(), ex);
    } catch (LockedAccountException ex) {
        facesError("Locked account");
        //log.error(ex.getMessage(), ex);
    } catch (AuthenticationException | IOException ex) {
        facesError("Unknown error: " + ex.getMessage());
        //log.error(ex.getMessage(), ex);
    } finally {
        token.clear();
    }
}

From source file:br.uff.ic.security.ShiroLoginBean.java

/**
 * Try and authenticate the user/*from w  w  w .j  ava 2s  .  c om*/
 */
public void doLogin() {
    Subject subject = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken(getUsername(), getPassword(), getRememberMe());

    try {
        subject.login(token);
        SessionUtil.setParam("usuario", usuarioFacade.autentificar(getUsername(), getPassword()));
        if (subject.hasRole("ADMINISTRADOR")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("admin/index.xhtml");
        } else if (subject.hasRole("GERENTE")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("gerente/index.xhtml");
        } else if (subject.hasRole("ASSISTENTE")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("assistente/index.xhtml");
        } else if (subject.hasRole("PROFESSOR")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("professor/index.xhtml");
        } else {
            FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
        }
    } catch (UnknownAccountException ex) {
        facesError("Unknown account");
        log.error(ex.getMessage(), ex);
    } catch (IncorrectCredentialsException ex) {
        facesError("Wrong password");
        log.error(ex.getMessage(), ex);
    } catch (LockedAccountException ex) {
        facesError("Locked account");
        log.error(ex.getMessage(), ex);
    } catch (AuthenticationException | IOException ex) {
        facesError("Unknown error: " + ex.getMessage());
        log.error(ex.getMessage(), ex);
    } catch (Exception ex) {
        facesError("Unknown error: " + ex.getMessage());
        log.error(ex.getMessage(), ex);
    } finally {
        token.clear();
    }
}

From source file:com.blazarquant.bfp.web.bean.user.LoginBean.java

License:Apache License

public void doLogin() {
    UsernamePasswordToken token = new UsernamePasswordToken(getUsername(), getPassword(), getRememberMe());
    try {/*from  w  w  w .j  ava  2  s .  c  o  m*/
        if (!userService.isUserActive(getUsername())) {
            facesUtils.addMessage(FacesMessage.SEVERITY_ERROR, ACCOUNT_NOT_ACTIVE);
            return;
        }

        Subject currentUser = shiroUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            currentUser.login(token);

            UserID userID = ((UserDetails) currentUser.getPrincipal()).getUserID();
            parserService.loadProvidersForUser(userID);
            userService.getUserSettingsCache().loadParameters(userID);
            userService.loginUser(userID);

            redirectToPreviousPage();
        } else {
            redirectToPreviousPage();
        }
    } catch (Exception e) {
        facesUtils.addMessage(FacesMessage.SEVERITY_ERROR, LOGIN_FAILED);
        LOGGER.error(LOGIN_FAILED, e);
    } finally {
        token.clear();
    }
}

From source file:com.curiousby.baoyou.cn.action.UserAciton.java

License:Open Source License

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(User currUser, HttpServletRequest request) {
    logger.debug("======login==========");
    //        String code = (String) session.getAttribute("validateCode");
    //        String submitCode = WebUtils.getCleanParam(request, "validateCode");

    Subject user = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(currUser.getUserName(), currUser.getPassword());
    token.setRememberMe(true);//  w ww  .ja v  a 2s.co  m
    try {
        user.login(token);
        logger.debug("======login success==========");
        return "/web/user/new";
    } catch (AuthenticationException e) {
        token.clear();
        logger.debug("======login error==========");
        return "/web/user/tologin";
    }

}

From source file:com.github.richardwilly98.esdms.services.AuthenticationProvider.java

License:Open Source License

@Override
public String login(Credential credential) throws ServiceException {
    String login = credential.getUsername();
    char[] password = credential.getPassword();
    boolean rememberMe = credential.isRememberMe();
    try {/*from   www .j  av  a2s . c o m*/
        if (log.isTraceEnabled()) {
            log.trace(String.format("login - %s", credential));
        }
        UsernamePasswordToken token = new UsernamePasswordToken(login, password, rememberMe);
        AuthenticationInfo info = securityManager.authenticate(token);
        if (log.isTraceEnabled()) {
            if (info instanceof SimpleAuthenticationInfo) {
                PrincipalCollection principals = ((SimpleAuthenticationInfo) info).getPrincipals();
                for (Object principal : principals.asList()) {
                    log.trace("Principal: " + principal);
                }
            }
        }
        token.clear();
        // Create subject for the current principal
        Subject subject = new Subject.Builder().principals(info.getPrincipals()).buildSubject();
        // log.trace("subject.getPrincipal(): " + subject.getPrincipal());
        // Create session
        org.apache.shiro.session.Session session = subject.getSession(true);
        if (session == null) {
            throw new ServiceException(String.format("Unable to create session for ", login));
        }
        session.setAttribute(ES_DMS_LOGIN_ATTRIBUTE, login);
        session.setAttribute(ES_DMS_ID_ATTRIBUTE, ((User) subject.getPrincipal()).getId());
        ThreadContext.bind(subject);
        // if (log.isTraceEnabled()) {
        // Subject currentUser = SecurityUtils.getSubject();
        // log.trace("currentUser.getPrincipal(): " +
        // currentUser.getPrincipal());
        // }
        return session.getId().toString();
    } catch (AuthenticationException aEx) {
        String message = String.format("Authentication failed for %s", login);
        log.error(message, aEx);
        throw new ServiceException(message);
    }
}

From source file:com.google.constructor.cip.shiro.examples.Login.java

License:Apache License

/**
 * Return true if the control and page processing should continue, or false otherwise. 
 * @return//from w w w . ja v a 2s.  c  o  m
 */
public boolean onOkClicked() {
    System.out.println("\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ STARTING Authentication");
    if (form.isValid()) {
        User user = new User();
        form.copyTo(user);
        //create a UsernamePasswordToken using the username and password provided by the user
        //See:  http://incubator.apache.org/shiro/static/current/apidocs/org/apache/shiro/authc/UsernamePasswordToken.html
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            //get the user (aka subject) associated with this request.
            //See: http://incubator.apache.org/shiro/static/current/apidocs/org/apache/shiro/subject/Subject.html#login(org.apache.shiro.authc.AuthenticationToken)
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            //clear the information stored in the token
            //see: http://incubator.apache.org/shiro/static/current/apidocs/org/apache/shiro/authc/UsernamePasswordToken.html#clear()
            token.clear();
            String redirect = redirectField.getValue();
            if (StringUtils.isNotBlank(redirect)) {
                setRedirect(redirect);
            } else {
                setRedirect("/secure/index.html");
            }
        } catch (UnknownAccountException uae) {
            //no account for the submitted username  retry?
            uae.printStackTrace();
            form.setError(uae.getMessage());
        } catch (IncorrectCredentialsException ice) {
            //submitted password was incorrect - retry?
            ice.printStackTrace();
            form.setError(ice.getMessage());
        } catch (LockedAccountException lae) {
            //account currently locked  unusable  nice error msg.
            lae.printStackTrace();
            form.setError(lae.getMessage());
        } catch (ExcessiveAttemptsException eae) {
            //too many unsuccessful login accounts. Lock it?
            eae.printStackTrace();
            form.setError(eae.getMessage());
        } catch (AuthenticationException ae) {
            //unexpected error?
            ae.printStackTrace();
            form.setError("Login NOT SUCCESSFUL - cause not known!");
        }
    }
    return true;
}

From source file:com.jfaker.framework.security.web.UserController.java

License:Apache License

public void dologin() {
    String error = "";
    String username = getPara("user.username");
    String password = getPara("user.password");
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        error = "???";
    }/*w w  w . j  a va2  s  .  c  om*/
    if (StringUtils.isEmpty(error)) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException ue) {
            token.clear();
            error = "??";
        } catch (IncorrectCredentialsException ie) {
            ie.printStackTrace();
            token.clear();
            error = "???";
        } catch (RuntimeException re) {
            re.printStackTrace();
            token.clear();
            error = "";
        }
    }
    if (StringUtils.isEmpty(error)) {
        redirect("/");
    } else {
        keepModel(User.class);
        setAttr("error", error);
        render("login.jsp");
    }
}

From source file:com.once.crosscloud.controllers.IndexController.java

License:Apache License

/**
 * /*ww w .j a v  a  2 s. c  o  m*/
 * ?
 * 1??Subject,?shiro?,?
 * 2???,UsernamePasswordToken,?shiro?
 * 3??ShiroDbRealmdoGetAuthenticationInfo?
 * 4?????,?
 * 
 * @param accountName   ??
 * @param password   ?
 * @return
 */
@RequestMapping(value = "login.html", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
public String userLogin(String accountName, String password, String captcha, Boolean rememberMe,
        HttpServletRequest request) {
    UsernamePasswordToken token = null;
    try {
        //session?servlet???text
        String expected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //????
        if (!captcha.equalsIgnoreCase(expected)) {
            request.setAttribute("error", "???");
            return "/login";
        } else {
            // ?Subject,?shiro?,?
            Subject subject = SecurityUtils.getSubject();
            token = new UsernamePasswordToken(accountName, password);
            //token.setRememberMe(rememberMe);
            subject.login(token);
            if (subject.isAuthenticated()) {
                LoginInfoEntity loginInfo = new LoginInfoEntity();
                Session session = SecurityUtils.getSubject().getSession();
                loginInfo.setUserId(Integer.valueOf(session.getAttribute("userSessionId").toString()));
                loginInfo.setAccountName(accountName);
                loginInfo.setLoginIp(session.getHost());
                loginInfoService.log(loginInfo);
                request.removeAttribute("error");
            } else {
                token.clear();
                request.setAttribute("error", "?????");
                return "/login";
            }
        }
    } catch (LockedAccountException e) {
        token.clear();
        request.setAttribute("error", "?,??10???");
        return "/login";
    } catch (ExcessiveAttemptsException e) {
        token.clear();
        request.setAttribute("error", "5,???10!");
        return "/login";
    } catch (AuthenticationException e) {
        token.clear();
        request.setAttribute("error", "?????");
        return "/login";
    } catch (Exception e) {
        token.clear();
        request.setAttribute("error", "???");
        return "/login";
    }
    return "redirect:/index.html";
}

From source file:com.thruzero.applications.faces.demo.beans.page.LoginBean.java

License:Apache License

public void loginListener(ActionEvent event) throws AbortProcessingException {
    Subject currentSubject = userService.getCurrentSubject();

    if (!currentSubject.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken(loginId, oneTimePw, nonce);

        try {//from  w w w  . ja va2 s .  c  o  m
            // assert that password has been set to "***" (prevent introduction of bugs that might expose user password in production)
            if (StringUtils.isNotEmpty(password) && !StringUtils.containsOnly(password, "*")) {
                // this will be handled below
                throw new Exception("ERROR: Regression - password has not been set to '****'.");
            }

            // attempt to log in
            currentSubject.login(token);
            if (currentSubject.isAuthenticated()) {
                MessageUtils.addInfo("Success!");
                reset();
            } else {
                // this will be handled below
                throw new Exception("ERROR: User not authorized to access this resource.");
            }
        } catch (Exception e) {
            if (e instanceof MessageIdAuthenticationException) {
                ResourceProvider resourceProvider = ProviderLocator.locate(ResourceProvider.class);
                MessageUtils.addError(resourceProvider.getResource(e.getMessage()));
            } else {
                MessageUtils.addError(e);
            }
            updateNonce();
            password = "";
            throw new AbortProcessingException("FAILED to log in.");
        }
        token.clear(); // clear encrypted password
    }
}

From source file:com.zht.common.rabc.web.RbacUserController.java

License:Apache License

@ResponseBody
@RequestMapping(value = "/login")
public Object login(HttpServletRequest request, Model model, String userName, String password,
        String jcaptchaCode) {//from   w  ww. j a v a  2 s  . c o  m
    Boolean jcodeValidate = JCaptchaFilter.validateCaptchaChallenge(request, jcaptchaCode);
    if (!jcodeValidate) {
        return ajaxDoneError("??");
    }
    UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
    // token.setRememberMe(true);  
    Subject currentUser = SecurityUtils.getSubject();
    try {
        currentUser.login(token);
    } catch (UnknownAccountException uae) {
        System.out.println("[" + userName + "]?..?,");
        return ajaxDoneError("???");

    } catch (IncorrectCredentialsException ice) {
        System.out.println("[" + userName + "]?..?,?");
        return ajaxDoneError("???");
    } catch (LockedAccountException lae) {
        System.out.println("[" + userName + "]?..?,?");
        return ajaxDoneError("?,?");
    } catch (ExcessiveAttemptsException eae) {
        System.out.println("[" + userName + "]?..?,");
        return ajaxDoneError("?,");
    } catch (AuthenticationException ae) {
        //?Shiro?AuthenticationException??  
        System.out.println("[" + userName + "]?..?,");
        return ajaxDoneError("?");
    }
    //???  
    if (currentUser.isAuthenticated()) {
        System.out.println("[" + userName
                + "]?(??????)");
        RbacUser rabcUser = rbacUserService.findUserByName(userName);
        ShiroSessionUser suser = new ShiroSessionUser();
        RbacRole role = rabcUser.getDefaultRbacRole();
        com.zht.common.sys.model.UserDetail userDetail = rabcUser.getUserDetail();
        if (userDetail == null) {
            return ajaxDoneError(" ??");
        }
        Position position = userDetail.getDefaultPosition();
        if (position == null) {
            return ajaxDoneError("?????");
        }
        com.zht.common.sys.model.Department dept = position.getDepartment();
        if (dept == null) {
            return ajaxDoneError("???");
        }
        suser.setCurrentRoleCode(role == null ? ShiroUserUtil.ANONYMOUS : role.getCode());
        currentUser.getSession().setAttribute(ShiroUserUtil.SHIROSESSIONUSER, suser);

        return ajaxDoneSuccess("?");
    } else {
        token.clear();
        return ajaxDoneError("?");
    }
}