Search in sources :

Example 21 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project shiro by apache.

the class QuickStart method run.

public void run() {
    // get the current subject
    Subject subject = SecurityUtils.getSubject();
    // Subject is not authenticated yet
    Assert.isTrue(!subject.isAuthenticated());
    // login the subject with a username / password
    UsernamePasswordToken token = new UsernamePasswordToken("joe.coder", "password");
    subject.login(token);
    // joe.coder has the "user" role
    subject.checkRole("user");
    // joe.coder does NOT have the admin role
    Assert.isTrue(!subject.hasRole("admin"));
    // joe.coder has the "read" permission
    subject.checkPermission("read");
    // current user is allowed to execute this method.
    simpleService.readRestrictedCall();
    try {
        // but not this one!
        simpleService.writeRestrictedCall();
    } catch (AuthorizationException e) {
        log.info("Subject was NOT allowed to execute method 'writeRestrictedCall'");
    }
    // logout
    subject.logout();
    Assert.isTrue(!subject.isAuthenticated());
}
Also used : AuthorizationException(org.apache.shiro.authz.AuthorizationException) Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 22 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project shiro by apache.

the class SecurityController method login.

@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);
    }
    UsernamePasswordToken token = new UsernamePasswordToken(command.getUsername(), command.getPassword(), command.isRememberMe());
    try {
        SecurityUtils.getSubject().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:/s/home";
    }
}
Also used : AuthenticationException(org.apache.shiro.authc.AuthenticationException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 23 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project shiro by apache.

the class JdbcRealm method doGetAuthenticationInfo.

/*--------------------------------------------
    |               M E T H O D S               |
    ============================================*/
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    String username = upToken.getUsername();
    // Null username is invalid
    if (username == null) {
        throw new AccountException("Null usernames are not allowed by this realm.");
    }
    Connection conn = null;
    SimpleAuthenticationInfo info = null;
    try {
        conn = dataSource.getConnection();
        String password = null;
        String salt = null;
        switch(saltStyle) {
            case NO_SALT:
                password = getPasswordForUser(conn, username)[0];
                break;
            case CRYPT:
                // TODO: separate password and hash from getPasswordForUser[0]
                throw new ConfigurationException("Not implemented yet");
            // break;
            case COLUMN:
                String[] queryResults = getPasswordForUser(conn, username);
                password = queryResults[0];
                salt = queryResults[1];
                break;
            case EXTERNAL:
                password = getPasswordForUser(conn, username)[0];
                salt = getSaltForUser(username);
        }
        if (password == null) {
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }
        info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
        if (salt != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(salt));
        }
    } catch (SQLException e) {
        final String message = "There was a SQL error while authenticating user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }
        // Rethrow any SQL errors as an authentication exception
        throw new AuthenticationException(message, e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }
    return info;
}
Also used : AccountException(org.apache.shiro.authc.AccountException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) ConfigurationException(org.apache.shiro.config.ConfigurationException) SQLException(java.sql.SQLException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) Connection(java.sql.Connection) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 24 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project shiro by apache.

the class DefaultSecurityManagerTest method testSubjectReuseAfterLogout.

/**
 * Test that validates functionality for issue
 * <a href="https://issues.apache.org/jira/browse/JSEC-22">JSEC-22</a>
 */
@Test
public void testSubjectReuseAfterLogout() {
    Subject subject = SecurityUtils.getSubject();
    AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
    subject.login(token);
    assertTrue(subject.isAuthenticated());
    assertTrue("guest".equals(subject.getPrincipal()));
    assertTrue(subject.hasRole("guest"));
    Session session = subject.getSession();
    Serializable firstSessionId = session.getId();
    session.setAttribute("key", "value");
    assertEquals(session.getAttribute("key"), "value");
    subject.logout();
    assertNull(subject.getSession(false));
    assertNull(subject.getPrincipal());
    assertNull(subject.getPrincipals());
    subject.login(new UsernamePasswordToken("lonestarr", "vespa"));
    assertTrue(subject.isAuthenticated());
    assertTrue("lonestarr".equals(subject.getPrincipal()));
    assertTrue(subject.hasRole("goodguy"));
    assertNotNull(subject.getSession());
    assertFalse(firstSessionId.equals(subject.getSession().getId()));
    subject.logout();
    assertNull(subject.getSession(false));
    assertNull(subject.getPrincipal());
    assertNull(subject.getPrincipals());
}
Also used : Serializable(java.io.Serializable) AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Session(org.apache.shiro.session.Session) Test(org.junit.Test)

Example 25 with UsernamePasswordToken

use of org.apache.shiro.authc.UsernamePasswordToken in project shiro by apache.

the class VMSingletonDefaultSecurityManagerTest method testVMSingleton.

@Test
public void testVMSingleton() {
    DefaultSecurityManager sm = new DefaultSecurityManager();
    Ini ini = new Ini();
    Ini.Section section = ini.addSection(IniRealm.USERS_SECTION_NAME);
    section.put("guest", "guest");
    sm.setRealm(new IniRealm(ini));
    SecurityUtils.setSecurityManager(sm);
    try {
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
        subject.login(token);
        subject.getSession().setAttribute("key", "value");
        assertTrue(subject.getSession().getAttribute("key").equals("value"));
        subject = SecurityUtils.getSubject();
        assertTrue(subject.isAuthenticated());
        assertTrue(subject.getSession().getAttribute("key").equals("value"));
    } finally {
        sm.destroy();
        // SHIRO-270:
        SecurityUtils.setSecurityManager(null);
    }
}
Also used : AuthenticationToken(org.apache.shiro.authc.AuthenticationToken) Ini(org.apache.shiro.config.Ini) IniRealm(org.apache.shiro.realm.text.IniRealm) Subject(org.apache.shiro.subject.Subject) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) Test(org.junit.Test)

Aggregations

UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)114 Subject (org.apache.shiro.subject.Subject)50 Test (org.junit.Test)30 AuthenticationException (org.apache.shiro.authc.AuthenticationException)28 AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)27 SimpleAuthenticationInfo (org.apache.shiro.authc.SimpleAuthenticationInfo)17 AuthenticationInfo (org.apache.shiro.authc.AuthenticationInfo)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)11 Test (org.testng.annotations.Test)11 LockedAccountException (org.apache.shiro.authc.LockedAccountException)10 IncorrectCredentialsException (org.apache.shiro.authc.IncorrectCredentialsException)9 HttpServletResponse (javax.servlet.http.HttpServletResponse)8 UnknownAccountException (org.apache.shiro.authc.UnknownAccountException)7 DelegatingSubject (org.apache.shiro.subject.support.DelegatingSubject)7 Session (org.apache.shiro.session.Session)6 SimplePrincipalCollection (org.apache.shiro.subject.SimplePrincipalCollection)6 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)6 AuthorizationInfo (org.apache.shiro.authz.AuthorizationInfo)4 AbstractQi4jTest (org.qi4j.test.AbstractQi4jTest)4