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.mitewater.test.ShrioTest.java

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 + "]");
    }/*  ww w.  ja  v a2s . 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:wield")) {
        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.mobileman.kuravis.core.services.user.impl.UserServiceImpl.java

License:Apache License

@Override
public DBObject signin(String email, String password, String captchaAnswer, boolean rememberMe) {
    if (log.isTraceEnabled()) {
        log.trace("signin(" + email + "," + password + "," + captchaAnswer + "," + rememberMe + "," + ")");
    }//  w  w w.j  a  v  a2  s . c om
    if (email == null) {
        email = "";
    }
    if (password == null) {
        password = "";
    }
    DBObject result = null;
    DBObject account = findDBUserAccountByEmail(email);
    if (account == null) {
        result = ErrorUtils.error("Unauthorized", ErrorCodes.UNAUTHORIZED);
        if (captchaData.size() > 1000) {
            captchaData.clear();
        }

        Integer unsuccessful_login_count = captchaData.get(email);
        if (unsuccessful_login_count == null) {
            unsuccessful_login_count = 1;
        } else {
            unsuccessful_login_count = unsuccessful_login_count.intValue() + 1;
            if (unsuccessful_login_count.intValue() >= this.configurationService
                    .getMaxUnsuccessfulLoginsCount()) {
                result.put("show_captcha", true);
            }
        }

        captchaData.put(email, unsuccessful_login_count);
        return result;
    }

    Integer unsuccessful_login_count = (Integer) account.get("unsuccessful_login_count");
    if (unsuccessful_login_count == null) {
        unsuccessful_login_count = 0;
    }

    UsernamePasswordToken token = new UsernamePasswordToken(email, password, rememberMe);
    Subject currentUser = SecurityUtils.getSubject();
    DBObject user = null;

    try {

        currentUser.login(token);
        user = (DBObject) currentUser.getPrincipal();

    } catch (UnknownAccountException e) {
        log.error("signin(...)", e);
        result = ErrorUtils.error("Unknown email", ErrorCodes.UNKNOWN_EMAIL);
    } catch (IncorrectCredentialsException e) {
        log.error("signin(...)", e);
        result = handleCaptchaError(account);

    } catch (LockedAccountException e) {
        log.error("signin(...)", e);
        result = ErrorUtils.error(e.getMessage(), ErrorCodes.ACCOUNT_LOCKED);
    } catch (ExcessiveAttemptsException e) {
        log.error("signin(...)", e);
        result = handleCaptchaError(account);
    } catch (AuthenticationException e) {
        log.error("signin(...)", e);
        result = handleCaptchaError(account);
    }

    if (user != null) {

        if (unsuccessful_login_count.intValue() >= this.configurationService.getMaxUnsuccessfulLoginsCount()) {
            // max usuccesssful logins coun reached - check answer
            if (!ObjectUtils.nullSafeEquals(captchaAnswer, account.get("captcha_answer"))) {
                result = ErrorUtils.error("Unauthorized", ErrorCodes.UNAUTHORIZED);
                result.put("show_captcha", true);
                return result;
            }
        }

        Date lastLoginDate = new Date();
        user.put("lastLoginDate", lastLoginDate);
        user.put("unsuccessful_login_count", 0);

        getCollection().update(new BasicDBObject(EntityUtils.ID, user.get(EntityUtils.ID)),
                new BasicDBObject("$set", new BasicDBObject("lastLoginDate", user.get("lastLoginDate"))
                        .append("unsuccessful_login_count", 0)));

        getCollection(EntityUtils.USERACCOUNT).update(
                new BasicDBObject(EntityUtils.ID, account.get(EntityUtils.ID)), new BasicDBObject("$set",
                        new BasicDBObject("unsuccessful_login_count", 0).append("captcha_answer", "")));

        result = ErrorUtils.success();
        result.put("roles", getUserRoles());
        result.put("email", user.get("email"));
        result.put("name", user.get("name"));
        result.put("gender", user.get("gender"));
        result.put("yearOfBirth", user.get("yearOfBirth"));
        result.put("state", user.get("state"));
        result.put("unsuccessful_login_count", user.get("unsuccessful_login_count"));
        result.put("lastLoginDate", user.get("lastLoginDate"));
        result.put(EntityUtils.ID, user.get(EntityUtils.ID));
        result.put("settings", user.get("settings"));
        result.put("state", user.get("state"));
    }
    return result;
}

From source file:com.monkeyk.os.web.ShiroTest.java

License:Open Source License

@Test(enabled = false)
public void login() {
    String username = "abc";
    //init SecurityManager
    SimpleAccountRealm realm = new SimpleAccountRealm("simple-realm");
    realm.addAccount(username, "abc", "USER");

    SimpleAccountRealm realm2 = new SimpleAccountRealm("simple-realm2");
    realm2.addAccount(username, "abc", "USER", "ADMIN");

    List<Realm> realmList = new ArrayList<>();
    realmList.add(realm);/*from   w w w  . j  a  v a  2s  . co  m*/
    realmList.add(realm2);

    SecurityManager securityManager = new DefaultSecurityManager(realmList);
    SecurityUtils.setSecurityManager(securityManager);

    UsernamePasswordToken token = new UsernamePasswordToken(username, "abcdd");

    final Subject subject = SecurityUtils.getSubject();
    subject.login(token);

    final Subject subject1 = SecurityUtils.getSubject();
    assertTrue(subject1.isAuthenticated());

    assertFalse(subject1.isPermitted("OK"));
    assertTrue(subject1.hasRole("USER"));

    //        assertTrue(subject1.isPermitted("USER:c,u"));

}

From source file:com.mto.arquillian.demo.security.ShiroServlet.java

License:Open Source License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Subject s = SecurityUtils.getSubject();
    String message = "";
    if (s.getPrincipal() == null) {
        try {/*from   w w w . j  av  a2 s  .  c om*/
            s.login(new UsernamePasswordToken("root", "wrongpass"));
            message = "You have logged in as root with password wrongpass";
        } catch (Exception ex) {
            s.login(new UsernamePasswordToken("root", "secret"));
            message = "You have logged in as root with password secret";
        }
    } else {
        message = "You have logged in";
    }
    resp.getWriter().write(message);
    resp.getWriter().flush();
}

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

@Test
public void testSecurityManager() {

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

    SecurityManager securityManager = (SecurityManager) factory.getInstance();
    SecurityUtils.setSecurityManager((SecurityManager) 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 vlaue! [" + value + "]");

    if (!currentUser.isAuthenticated()) {

        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);/*from   w w w  . ja v a  2s . c o m*/

        try {
            currentUser.login(token);
        } catch (UnknownAccountException e) {
            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.");
        }

    }

    if (currentUser.hasRole("schwartz")) {
        log.info("May the Schwartz be with you!");
    } else {
        log.info("Hello, mere mortal.");

    }

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

    if (currentUser.isPermitted("winnerbago: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!");
    }

    currentUser.logout();

    System.exit(0);
}

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

@Test
public void testCustomRealm() {

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

    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");

    try {//ww w  .j av a2 s .  c  o  m
        //(?)
        subject.login(token);
    } catch (AuthenticationException e) {

        e.printStackTrace();
    }
    //subject?
    log.info(subject.isAuthenticated() + "");

    subject.logout();
}

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

@Test
public void testCustomMultiRealm() {

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

    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");

    try {/*from   w  w  w. j a  v a 2  s .c o m*/
        //4???
        subject.login(token);
    } catch (AuthenticationException e) {
        //5??
        e.printStackTrace();
    }

    System.out.println(subject.isAuthenticated());

    //6?
    subject.logout();
}

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

@Test
public void testJdbcRealm() {
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");

    try {/*from  www . j ava 2  s  . c  o  m*/
        //4???
        subject.login(token);
    } catch (AuthenticationException e) {
        //5??
        e.printStackTrace();
    }

    System.out.println(subject.isAuthenticated());

    //6?
    subject.logout();

}

From source file:com.mymanager.security.Authenticator.java

/*** Autenticates a user **/
public Subject authenticate(String username, String pass) {

    Subject currentUser = null;
    try {/* ww w .ja  va2s.c  o m*/

        Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory(
                "classpath:shiro.ini");
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        // the key "jdbcRealm" must be the same in the shiro.ini file.
        JdbcRealm realm = (JdbcRealm) ((IniSecurityManagerFactory) factory).getBeans().get("jdbcRealm");
        realm.setAuthenticationQuery(AUTHENTICATION_QUERY);
        realm.setUserRolesQuery(ROLES_QUERY);

        //realm.setPermissionsQuery("SELECT permission FROM role_permission,role WHERE role_permission.roleId=role.roleId AND role.name=?");
        //realm.setPermissionsLookupEnabled(false);
        SecurityUtils.setSecurityManager(securityManager);

        currentUser = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username, pass);

        currentUser.login(token);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return currentUser;

}

From source file:com.netease.channel.security.AuthenticatorFilter.java

License:Open Source License

private void login(String email) {
    Subject subject = SecurityUtils.getSubject();
    subject.login(new UrsToken(email));
}