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:it.freedomotic.security.AuthImpl.java

License:Open Source License

@Override
public boolean login(String subject, String password) {
    UsernamePasswordToken token = new UsernamePasswordToken(subject, password);
    token.setRememberMe(true);/*from   w w w  . j  a  v  a 2  s  .  c om*/
    Subject currentUser = SecurityUtils.getSubject();
    try {
        currentUser.login(token);
        currentUser.getSession().setTimeout(-1);
        return true;
    } catch (Exception e) {
        LOG.warning(e.getLocalizedMessage());
        return false;
    }
}

From source file:JavaMvc.Controllers.SecurityController.java

License:Apache License

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, @ModelAttribute LoginCommand command, BindingResult errors) {
    loginValidator.validate(command, errors);

    if (errors.hasErrors()) {
        return showLoginForm(model, command);
    }/*from  w  ww  .j  ava 2s  . c o  m*/
    final Subject currentUser = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken(command.getUsername(), command.getPassword(),
            command.isRememberMe());
    try {
        currentUser.login(token);
    } catch (AuthenticationException e) {
        errors.reject("error.login.generic", "Invalid username or password.  Please try again.");
    }

    if (errors.hasErrors()) {
        return showLoginForm(model, command);
    } else {
        return "redirect:/";
    }
}

From source file:juzu.plugin.shiro.impl.ShiroAuthenticator.java

License:Open Source License

public Response doLogin(Stage.Handler stage) {
    Request request = stage.getRequest();
    Login loginAnnotation = request.getHandler().getMethod().getAnnotation(Login.class);
    Subject subject = SecurityUtils.getSubject();

    boolean remember = request.getParameterArguments().get(loginAnnotation.rememberMe()) != null ? true : false;
    String username = null;/*from w w w  .  j  av  a  2s  .  c o m*/
    String password = null;
    try {
        username = request.getParameterArguments().get(loginAnnotation.username()).getValue();
        password = request.getParameterArguments().get(loginAnnotation.password()).getValue();
    } catch (NullPointerException e) {
        List<ControlParameter> parameters = request.getHandler().getParameters();
        for (ControlParameter parameter : parameters) {
            if (parameter instanceof ContextualParameter) {
                if (AuthenticationException.class.isAssignableFrom(parameter.getType())) {
                    request.getContextualArguments().put((ContextualParameter) parameter,
                            new AuthenticationException(e.getCause()));
                    return stage.invoke();
                }
            }
        }

        //
        return new Response.Error(e);
    }

    try {
        subject.login(new UsernamePasswordToken(username, password.toCharArray(), remember));

        //
        Response resp = stage.invoke();
        if (remember && rememberMeSupported) {
            RememberMeUtil.forgetIdentity();
            RememberMeUtil.rememberSerialized();
        }
        return resp;
    } catch (AuthenticationException e) {
        List<ControlParameter> parameters = request.getHandler().getParameters();
        for (ControlParameter parameter : parameters) {
            if (parameter instanceof ContextualParameter) {
                if (AuthenticationException.class.isAssignableFrom(parameter.getType())) {
                    request.getContextualArguments().put((ContextualParameter) parameter, e);
                    Response resp = stage.invoke();
                    if (remember) {
                        RememberMeUtil.forgetIdentity();
                    }
                    return resp;
                }
            }
        }

        return new Response.Error(e);
    }
}

From source file:kamsky.app.Main.java

public static void main(String[] args) {
    log.info("My First Apache Shiro Application");

    IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    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")) {
        log.info("Retrieved the correct value! [" + value + "]");
    }/*  w w w . j a v  a 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:kg.cloud.acc.MyVaadinApplication.java

License:Apache License

public void login(String username, String password) {
    UsernamePasswordToken token;/*from w  w w.  j ava  2s .  c  om*/

    token = new UsernamePasswordToken(username, password);
    // ?Remember Me? built-in, just do this:
    token.setRememberMe(true);

    // With most of Shiro, you'll always want to make sure you're working
    // with the currently executing user,
    // referred to as the subject
    Subject currentUser = SecurityUtils.getSubject();

    // Authenticate
    currentUser.login(token);

}

From source file:kg.cloud.hospital.MyVaadinApplication.java

License:Apache License

public void login(String username, String password) {
    UsernamePasswordToken token;/*w  w  w  . j  ava 2  s.c o  m*/

    token = new UsernamePasswordToken(username, password);
    // ?Remember Me? built-in, just do this:
    token.setRememberMe(true);

    // With most of Shiro, you'll always want to make sure you're working with the currently executing user,
    // referred to as the subject
    Subject currentUser = SecurityUtils.getSubject();

    // Authenticate
    currentUser.login(token);

}

From source file:local.zcw.demo.shiro.shiro.hello.Client.java

public static void main(String[] args) {

    //??SecurityManager
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();

    //securityManger?
    SecurityUtils.setSecurityManager(securityManager);

    //???// w  w w. j av a  2s. c o m
    Subject currentUser = SecurityUtils.getSubject();

    //?session??web
    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 + "]");
    }

    //???
    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:me.leep.wf.actions.LoginAction.java

License:Apache License

@Override
public String execute() throws Exception {
    if (username == null)
        return INPUT;
    else {//from   w  ww .  j  av a  2  s  .c o  m
        // Example using most common scenario of username/password pair:
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        // ?Remember Me? built-in:
        token.setRememberMe(rememberMe);

        Subject currentUser = SecurityUtils.getSubject();

        try {
            currentUser.login(token);
            logger.info("" + username + "?");
            return "INDEX";
        } catch (UnknownAccountException uae) {
            // ???
            return SUCCESS;
        } catch (IncorrectCredentialsException ice) {
            // ?
            return SUCCESS;
        } catch (LockedAccountException lae) {
            // ?
            return SUCCESS;
        } catch (AuthenticationException ae) {
            // ?
            return SUCCESS;
        }

    }
}

From source file:module.controller.SystemCtrl.java

License:Apache License

@Before(SigninValidator.class)
public void signin() {
    if ("GET".equalsIgnoreCase(this.getRequest().getMethod().toUpperCase())) {
        forwardAction(SYSTEM_LOGIN_PAGE);
    } else if ("POST".equalsIgnoreCase(this.getRequest().getMethod().toUpperCase())) {
        String username = getPara("username");
        String password = getPara("password");
        String rememberMe = getPara("rememberMe");
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,
                "on".equalsIgnoreCase(rememberMe));
        try {//from  ww  w  .j  a v  a2 s .  co m
            currentUser.login(token);
            redirect(getCookie("_redrictUrl", SYSTEM_LOGIN_SUCCESS));
        } catch (Exception e) {
            // 
            String esn = e.getClass().getSimpleName();
            if ("IncorrectCredentialsException".equalsIgnoreCase(esn)) {
                setAttr("errorMsg", "?????");
            } else if ("UnknownAccountException".equalsIgnoreCase(esn)) {
                setAttr("errorMsg", "???");
            } else if ("LockedAccountException".equalsIgnoreCase(esn)) {
                setAttr("errorMsg", "??");
            } else if ("AuthenticationException".equalsIgnoreCase(esn)) {
                setAttr("errorMsg", "??");
            } else if ("ExcessiveAttemptsException".equalsIgnoreCase(esn)) {
                setAttr("errorMsg", "10??");
            } else if ("DisabledAccountException".equalsIgnoreCase(esn)) {
                setAttr("errorMsg", "??");
            } else if ("ExpiredCredentialsException".equalsIgnoreCase(esn)) {
                setAttr("errorMsg", "?");
            } else {
                setAttr("errorMsg", "?");
            }
            setAttr("username", username);
            setAttr("rememberMe", rememberMe);
            forwardAction(SYSTEM_LOGIN_PAGE);
        }
    }

}

From source file:name.brucephillips.rolesecurity.QuickstartSpring.java

License:Apache License

public static void main(String... args) {

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("shiro.spring.xml");

    SecurityManager securityManager = (SecurityManager) applicationContext.getBean("securityManager");
    ;/*from  w  ww .  j  av  a2s .co m*/

    SecurityUtils.setSecurityManager(securityManager);

    Subject currentUser = SecurityUtils.getSubject();

    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 + "]");
    }

    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("sue@hotmail.com", "sue");
        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 (AuthenticationException ae) {
            ae.printStackTrace();
        }
    }

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

    if (currentUser.hasRole("user")) {
        log.info("====> ROLE OK");
    } else {
        log.info("====> ROLE KO");
    }

    if (currentUser.isPermitted("winnebago:drive:eagle7")) {
        log.info("===> PERM OK");
    } else {
        log.info("==> PERM KO");
    }

    currentUser.logout();

}