Example usage for org.apache.shiro.subject Subject login

List of usage examples for org.apache.shiro.subject Subject login

Introduction

In this page you can find the example usage for org.apache.shiro.subject Subject login.

Prototype

void login(AuthenticationToken token) throws AuthenticationException;

Source Link

Document

Performs a login attempt for this Subject/user.

Usage

From source file:com.josue.shiro.jsf.LoginController.java

public String authenticate() {

    // Example using most common scenario of username/password pair:
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    // "Remember Me" built-in:
    token.setRememberMe(rememberMe);/*  ww w . j a  va  2s.c  om*/

    Subject currentUser = SecurityUtils.getSubject();

    log.log(Level.INFO, "Submitting login with username of {0} and password of {1}",
            new Object[] { username, password });

    try {
        currentUser.login(token);
    } catch (Exception e) {
        // Could catch a subclass of AuthenticationException if you like
        log.warning(e.getMessage());
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage("Login Failed: " + e.getMessage(), e.toString()));
        return "/login.xhtml";
    }
    return "/secured/dashboard.xhtml?faces-redirect=true";

}

From source file:com.jythonui.server.security.impl.SubjectCache.java

License:Apache License

private Result authenticate(SessionEntry se, String tokenS) {
    SecurityManager securityManager = constructManager(se.getRealm());
    SecurityUtils.setSecurityManager(securityManager);
    Subject currentUser = buildSubject();
    PasswordSecurityToken token = new PasswordSecurityToken(se.getUser(), se.getPassword(), se.getiCustom());
    info(gMess.getMessN(ILogMess.AUTHENTICATEUSER, se.getUser(), se.getRealm()));
    try {//  ww w . ja  v  a  2  s .c  o  m
        currentUser.login(token);
    } catch (UnknownAccountException uae) {
        info(gMess.getMess(IErrorCode.ERRORCODE3, ILogMess.AUTHENTICATENOUSER, se.getUser()));
        return null;
    } catch (IncorrectCredentialsException ice) {
        info(gMess.getMess(IErrorCode.ERRORCODE4, ILogMess.AUTHENTICATEINCORECTPASSWORD, se.getUser()));
        return null;
    } catch (LockedAccountException lae) {
        info(gMess.getMess(IErrorCode.ERRORCODE5, ILogMess.AUTHENTOCATELOCKED, se.getUser()));
        return null;
    } catch (AuthenticationException ae) {
        severe(gMess.getMess(IErrorCode.ERRORCODE6, ILogMess.AUTHENTICATEOTHERERROR, se.getUser(),
                ae.getMessage()), ae);
        ae.printStackTrace();
        return null;
    } catch (UnknownSessionException ae) {
        info(gMess.getMess(IErrorCode.ERRORCODE22, ILogMess.AUTHENTICATEOTHERERROR, se.getUser(),
                ae.getMessage()));
        return null;
    }

    info(gMess.getMessN(ILogMess.OKAUTHENTICATED));
    if (tokenS == null) {
        UUID i = UUID.randomUUID();
        tokenS = i.toString();
        iCache.put(tokenS, se);
    }
    CurrentSubject subS = new CurrentSubject();
    subS.se = se;
    subS.sManager = securityManager;
    subS.currentUser = currentUser;
    lastS.set(subS);
    return new Result(currentUser, tokenS);
}

From source file:com.kelson.keeku.security.MyFormAuthenticationFilter.java

License:Apache License

@Override
protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
    String username = getUsername(request);
    String password = getPassword(request);
    boolean isAjaxLogin = StringUtils.equals(WebUtils.getCleanParam(request, "ajaxLogin"), "1");
    boolean rememberMe = isRememberMe(request);
    String host = getHost(request);
    UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe, host);

    try {//from  www  . j a  va 2s  .  c  o  m
        Subject subject = getSubject(request, response);
        subject.login(token);
        Session session = subject.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        LoggerUtil.operation(Operation.Login, String.valueOf(userId) + "has logined",
                (HttpServletRequest) request);
        if (isAjaxLogin) {
            if (StringUtils.equals(WebUtils.getCleanParam(request, "needRedirect"), "1")) {//when login successfully by ajax login and redirect to backurl
                SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
                if (savedRequest != null
                        && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) {
                    request.setAttribute("backUrl", savedRequest.getRequestUrl());
                }
            }
            return true;
        } else {
            return onLoginSuccess(token, subject, request, response);
        }
    } catch (AuthenticationException e) {
        if (SecurityUtils.getSubject().getSession(false) != null) {
            SecurityUtils.getSubject().getSession(false).removeAttribute("userId");
        }
        return onLoginFailure(token, e, request, response);
    }
}

From source file:com.lieve.online.shiro.Quickstart.java

License:Apache License

public static void main(String[] args) {

    // The easiest way to create a Shiro SecurityManager with configured
    // realms, users, roles and permissions is to use the simple INI config.
    // We'll do that by using a factory that can ingest a .ini file and
    // return a SecurityManager instance:

    // Use the shiro.ini file at the root of the classpath
    // (file: and url: prefixes load from files and urls respectively):
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();

    // for this simple example quickstart, make the SecurityManager
    // accessible as a JVM singleton.  Most applications wouldn't do this
    // and instead rely on their container configuration or web.xml for
    // webapps.  That is outside the scope of this simple quickstart, so
    // we'll just do the bare minimum so you can continue to get a feel
    // for things.
    SecurityUtils.setSecurityManager(securityManager);

    // Now that a simple Shiro environment is set up, let's see what you can do:

    // 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");
    if (value.equals("aValue")) {
        log.info("Retrieved the correct value! [" + value + "]");
    }// www  . j a  va  2s.  c  o m

    // 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) {
            log.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("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?
        }
    }

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

    //test a role:
    if (currentUser.hasRole("schwartz")) {
        log.info("May the Schwartz be with you!");
    } else {
        log.info("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 {
        log.info("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 {
        log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }

    //all done - log out!
    currentUser.logout();

    System.exit(0);
}

From source file:com.liferay.blade.samples.authenticator.shiro.ShiroAuthenticatorPre.java

License:Apache License

@Override
public int authenticateByEmailAddress(long companyId, String emailAddress, String password,
        Map<String, String[]> headerMap, Map<String, String[]> parameterMap) throws AuthException {

    if (_log.isInfoEnabled()) {
        _log.info("authenticateByEmailAddress");
    }//w ww .  j  av a  2  s  .c o m

    UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(emailAddress, password);

    Subject currentUser = SecurityUtils.getSubject();

    try {
        currentUser.login(usernamePasswordToken);

        boolean authenticated = currentUser.isAuthenticated();

        if (authenticated) {
            if (_log.isInfoEnabled()) {
                _log.info("authenticated");
            }

            return SKIP_LIFERAY_CHECK;
        } else {
            return FAILURE;
        }
    } catch (AuthenticationException ae) {
        _log.error(ae.getMessage(), ae);
        throw new AuthException(ae.getMessage(), ae);
    }
}

From source file:com.local.ask.controller.spring.LoginController.java

@RequiresGuest
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String submitLoginForm(@Valid LoginUser loginUser, BindingResult result, Model m,
        HttpServletRequest request) {//from w w  w .  ja  va 2s  .  com
    if (!result.hasErrors()) {
        try {
            UserTemp userTemp = new UserTemp(loginUser);
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(userTemp.getEmail(), userTemp.getPassword(),
                    loginUser.getRememberMe()));
            Session session = subject.getSession(true);
            session.setAttribute("user", userTemp);
            session.setTimeout(24 * 3600000);
            m.addAttribute("message", "Successfully logged in person");
            String referer = request.getHeader("referer");
            if (referer != null && !referer.isEmpty()) {
                return REDIRECT + referer;
            }
            referer = (String) SecurityUtils.getSubject().getSession().getAttribute("fallback");
            if (referer != null && !referer.isEmpty()) {
                return REDIRECT + referer;
            }
        } catch (AuthenticationException ex) {
            ex.printStackTrace();
            m.addAttribute("message", "It seems your email is not registered.");
        }
    }
    return "login";
}

From source file:com.max.shiro.Tutorial.java

public static void main(String[] args) {
    System.out.println("start....");
    logger.info("My First Apache Shiro Application");

    // 1./*from  w w  w. ja v a  2  s .  c o m*/
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

    // 2.
    SecurityManager securityManager = factory.getInstance();

    // 3.
    SecurityUtils.setSecurityManager(securityManager);

    // 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");
    if (value.equals("aValue")) {
        logger.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) {
            logger.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            logger.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            logger.info("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?
        }
    }

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

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

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

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

    // all done - log out!
    currentUser.logout();

    System.exit(0);
}

From source file:com.metropolitan.methotels727.pages.Login.java

Object onSuccess() {
    String sifra = getMD5Hash(korisnik.getSifra());
    Korisnik k = korisnikDAO.proveriKorisnika(korisnik.getEmail(), sifra);
    if (k != null) {
        ulogovaniKorisnik = k;//from   w w  w  . j av a2 s  . c  o  m
        ulogovaniEmail = k.getEmail();
        System.out.println("Uspeno logovanje na sistem korisnika " + ulogovaniEmail);
        Subject trenutniKorisnik = securityService.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(k.getEmail(), korisnik.getSifra());
        try {
            trenutniKorisnik.login(token);
        } catch (Exception e) {
            formalogin.recordError("Uneli ste pogrene parametre");
        }
        if (ulogovaniKorisnik.getUloga() != Uloga.Admin)
            return Index.class;
        else {
            return AdminPanel.class;
        }
    } else {
        formalogin.recordError("Uneti korisnik ne postoji ili je pogrena ifra");
        System.out.println("Neuspeno logovanje");
        return null;
    }
}

From source file:com.migo.controller.SysLoginController.java

License:Apache License

/**
 * /* www.  ja va2 s  .c  o m*/
 */
@PostMapping("/sys/login")
public R login(String username, String password, String captcha) throws IOException {
    String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
    if (!captcha.equalsIgnoreCase(kaptcha)) {
        return R.error("???");
    }

    try {
        Subject subject = ShiroUtils.getSubject();
        //sha256
        password = new Sha256Hash(password).toHex();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        subject.login(token);
    } catch (UnknownAccountException | LockedAccountException | IncorrectCredentialsException e) {
        return R.error(e.getMessage());
    } catch (AuthenticationException e) {
        return R.error("?");
    }

    return R.ok();
}

From source file:com.mingsoft.basic.action.web.LoginAction.java

License:Open Source License

/**
 * ?//from   w  w  w  . j a v a2  s . c  om
 * 
 * @param manager
 *            ?
 * @param request
 *            
 * @param response
 *            ?
 */
@RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
public void checkLogin(@ModelAttribute ManagerEntity manager, HttpServletRequest request,
        HttpServletResponse response) {
    AppEntity urlWebsite = null;
    urlWebsite = appBiz.getByUrl(this.getDomain(request)); // ?url???????
    if (urlWebsite == null) {
        this.outJson(response, ModelCode.ADMIN_LOGIN, false,
                this.getResString("err.not.exist", this.getResString("app")));
        return;
    }
    // ??????
    ManagerEntity _manager = managerBiz.queryManagerByManagerName(manager.getManagerName());
    if (_manager == null) {
        // ?
        this.outJson(response, ModelCode.ADMIN_LOGIN, false, this.getResString("err.nameEmpty"));
    } else {
        // ???
        if (StringUtil.Md5(manager.getManagerPassword()).equals(_manager.getManagerPassword())) {
            SystemSkinEntity systemSkin = systemSkinBiz.getByManagerId(_manager.getManagerId());
            // ?session
            ManagerSessionEntity managerSession = new ManagerSessionEntity();
            AppEntity website = new AppEntity();
            // ??
            RoleEntity role = (RoleEntity) roleBiz.getEntity(_manager.getManagerRoleID());
            website = (AppEntity) appBiz.getByManagerId(role.getRoleManagerId());
            // ???????
            if (website != null && urlWebsite != null && urlWebsite.getAppId() == website.getAppId()
                    && _manager.getManagerRoleID() > Const.DEFAULT_SYSTEM_MANGER_ROLE_ID) {

                List<BaseEntity> childManagerList = managerBiz
                        .queryAllChildManager(managerSession.getManagerId());
                managerSession.setBasicId(website.getAppId());
                managerSession.setManagerParentID(role.getRoleManagerId());
                managerSession.setManagerChildIDs(childManagerList);
                managerSession.setStyle(website.getAppStyle());
                // ?seesion
                setSession(request, SessionConstEnum.MANAGER_SESSION, managerSession);
            } else {
                if (!(_manager.getManagerRoleID() == Const.DEFAULT_SYSTEM_MANGER_ROLE_ID)) {
                    this.outJson(response, ModelCode.ADMIN_LOGIN, false,
                            this.getResString("err.not.exist", this.getResString("manager")));
                } else {
                    setSession(request, SessionConstEnum.MANAGER_SESSION, managerSession);
                }
            }
            BeanUtils.copyProperties(_manager, managerSession);
            if (systemSkin != null) {
                managerSession.setSystemSkin(systemSkin);
            }

            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken upt = new UsernamePasswordToken(managerSession.getManagerName(),
                    managerSession.getManagerPassword());
            subject.login(upt);
            this.outJson(response, ModelCode.ADMIN_LOGIN, true, null);
        } else {
            // ?
            this.outJson(response, ModelCode.ADMIN_LOGIN, false, this.getResString("err.password"));
        }
    }
}