Example usage for org.apache.shiro.authc AuthenticationInfo getPrincipals

List of usage examples for org.apache.shiro.authc AuthenticationInfo getPrincipals

Introduction

In this page you can find the example usage for org.apache.shiro.authc AuthenticationInfo getPrincipals.

Prototype

PrincipalCollection getPrincipals();

Source Link

Document

Returns all principals associated with the corresponding Subject.

Usage

From source file:cn.usually.common.shiro.authc.pam.AnySuccessfulStrategy.java

License:Apache License

/**
 * Returns the specified {@code aggregate} instance if is non null and valid
 * (that is, has principals and they are not empty) immediately, or, if it
 * is null or not valid, the {@code info} argument is returned instead.
 * <p/>//  www .j  a  v  a  2s. c  o m
 * This logic ensures that the first valid info encountered is the one
 * retained and all subsequent ones are ignored, since this strategy
 * mandates that only the info from the first successfully authenticated
 * realm be used.
 */
protected AuthenticationInfo merge(AuthenticationInfo info, AuthenticationInfo aggregate) {
    if (aggregate != null && !CollectionUtils.isEmpty(aggregate.getPrincipals())) {
        return aggregate;
    }
    return info != null ? info : aggregate;
}

From source file:com.authlete.sample.server.security.Authenticator.java

License:Apache License

/**
 * Authenticate the resource owner./*from w w w  . jav a 2  s.c o m*/
 *
 * @param username
 *         The resource owner's user name.
 *
 * @param password
 *         The resource owner's password.
 *
 * @return
 *         The subject (unique identifier) of the user when he/she
 *         was authenticated successfully. {@code null} when the
 *         user was not authenticated.
 */
public static String authenticate(String username, String password) {
    // Pack the username and password into AuthenticationToken
    // which Apache Shiro's SecurityManager can accept.
    AuthenticationToken credentials = new UsernamePasswordToken(username, password);

    try {
        // Authenticate the resource owner using Apache Shiro.
        AuthenticationInfo info = SecurityUtils.getSecurityManager().authenticate(credentials);

        // Get the subject of the authenticated user.
        String subject = info.getPrincipals().getPrimaryPrincipal().toString();

        // Successfully authenticated.
        return subject;
    } catch (AuthenticationException e) {
        // Authentication failed.
        String message = String.format("Authentication failed: username=%s, error=%s (%s)", username,
                e.getMessage(), e.getClass().getSimpleName());

        // Emit a debug log message.
        Logger.getLogger(Authenticator.class.getName()).fine(message);

        // Not authenticated.
        return null;
    }
}

From source file:com.enioka.jqm.webui.shiro.JpaRealm.java

License:Open Source License

@Override
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info)
        throws AuthenticationException {
    if (token instanceof CertificateToken) {
        if (!((CertificateToken) token).getUserName().equals(info.getPrincipals().getPrimaryPrincipal())) {
            throw new IncorrectCredentialsException("certificate presented did not match the awaited username");
        }//  w w w  .j av  a 2  s  .c  om
        return;
    }
    super.assertCredentialsMatch(token, info);
}

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 {/*w  w w  . j  ava  2  s. 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.josue.kingdom.security.application.ApplicationlRealmTest.java

@Test
public void testDoGetAuthenticationInfoNoManagerToken() {
    String appKey = "appKey";
    char[] appSecret = "app-secret".toCharArray();
    ApplicationToken appToken = new ApplicationToken(appKey, appSecret);

    ApplicationToken spyAppToken = Mockito.spy(appToken);
    Application app = Mockito.mock(Application.class);

    when(persistence.getApplication((String) spyAppToken.getPrincipal(), new String(appSecret)))
            .thenReturn(app);/*from   w  ww  . j  a v a2  s. c  o  m*/

    AuthenticationInfo info = realm.doGetAuthenticationInfo(appToken);

    PrincipalCollection principals = info.getPrincipals();
    assertTrue(principals.getPrimaryPrincipal() instanceof KingdomSecurity);
    KingdomSecurity security = (KingdomSecurity) principals.getPrimaryPrincipal();
    assertEquals(app, security.getCurrentApplication());

    try {
        security.getCurrentManager();
        fail();
    } catch (RestException ex) {
        assertTrue(ex instanceof HeaderRequiredException);
    }
}

From source file:com.josue.kingdom.security.application.ApplicationlRealmTest.java

@Test
public void testDoGetAuthenticationInfoUnauthenticated() {

    String manEmail = "man@email.com";
    char[] manPassword = "man-pass123".toCharArray();
    ManagerToken manToken = new ManagerToken(manEmail, manPassword);

    String appKey = "appKey";
    char[] appSecret = "app-secret".toCharArray();
    ApplicationToken appToken = new ApplicationToken(appKey, appSecret, manToken);

    ApplicationToken spyAppToken = Mockito.spy(appToken);
    Application app = Mockito.mock(Application.class);

    when(persistence.getApplication((String) spyAppToken.getPrincipal(), new String(appSecret)))
            .thenReturn(app);/*from w  w w  .  ja  v  a  2  s .c  o  m*/
    when(persistence.getManagerByEmail(appKey, manEmail, new String(manPassword))).thenReturn(null);

    AuthenticationInfo info = realm.doGetAuthenticationInfo(appToken);

    PrincipalCollection principals = info.getPrincipals();
    assertTrue(principals.getPrimaryPrincipal() instanceof KingdomSecurity);
    KingdomSecurity security = (KingdomSecurity) principals.getPrimaryPrincipal();
    assertEquals(app, security.getCurrentApplication());
    assertEquals(KingdomSecurity.ManagerStatus.UNAUTHENTICATED, security.getManagerStatus());

    try {
        security.getCurrentManager();
        fail();
    } catch (RestException ex) {
    }

}

From source file:com.josue.kingdom.security.application.ApplicationlRealmTest.java

@Test
public void testDoGetAuthenticationInfoAuthenticated() {

    String manEmail = "man@email.com";
    char[] manPassword = "man-pass123".toCharArray();
    String manUsername = "man-username";
    ManagerToken manToken = new ManagerToken(manEmail, manPassword);
    Manager foundManager = Mockito.mock(Manager.class);

    String appKey = "appKey";
    char[] appSecret = "app-secret".toCharArray();
    ApplicationToken appToken = new ApplicationToken(appKey, appSecret, manToken);

    ApplicationToken spyAppToken = Mockito.spy(appToken);
    Application app = Mockito.mock(Application.class);

    when(persistence.getApplication((String) spyAppToken.getPrincipal(), new String(appSecret)))
            .thenReturn(app);/*from w ww.  j  a v  a 2s .  c o  m*/

    when(persistence.getManagerByEmail(app.getUuid(), manEmail, new String(manPassword)))
            .thenReturn(foundManager);

    AuthenticationInfo info = realm.doGetAuthenticationInfo(appToken);

    PrincipalCollection principals = info.getPrincipals();
    assertTrue(principals.getPrimaryPrincipal() instanceof KingdomSecurity);
    KingdomSecurity security = (KingdomSecurity) principals.getPrimaryPrincipal();
    assertEquals(app, security.getCurrentApplication());
    assertEquals(KingdomSecurity.ManagerStatus.AUTHENTICATED, security.getManagerStatus());

    try {
        assertEquals(foundManager, security.getCurrentManager());
    } catch (RestException ex) {
        fail();
    }

}

From source file:com.josue.kingdom.security.application.ApplicationlRealmTest.java

@Test
public void testDoGetAuthenticationInfoByUsername() {

    char[] manPassword = "man-pass123".toCharArray();
    String manUsername = "man-username";
    ManagerToken manToken = new ManagerToken(manUsername, manPassword);
    Manager foundManager = Mockito.mock(Manager.class);

    String appKey = "appKey";
    char[] appSecret = "app-secret".toCharArray();
    ApplicationToken appToken = new ApplicationToken(appKey, appSecret, manToken);

    ApplicationToken spyAppToken = Mockito.spy(appToken);
    Application app = Mockito.mock(Application.class);

    when(persistence.getApplication((String) spyAppToken.getPrincipal(), new String(appSecret)))
            .thenReturn(app);//ww  w .  j  a  v  a2s  .co  m

    when(persistence.getManagerByUsername(app.getUuid(), manUsername, new String(manPassword)))
            .thenReturn(foundManager);

    AuthenticationInfo info = realm.doGetAuthenticationInfo(appToken);

    PrincipalCollection principals = info.getPrincipals();
    assertTrue(principals.getPrimaryPrincipal() instanceof KingdomSecurity);
    KingdomSecurity security = (KingdomSecurity) principals.getPrimaryPrincipal();
    assertEquals(app, security.getCurrentApplication());
    assertEquals(KingdomSecurity.ManagerStatus.AUTHENTICATED, security.getManagerStatus());

    try {
        assertEquals(foundManager, security.getCurrentManager());
    } catch (RestException ex) {
        fail();
    }

}

From source file:com.tensorwrench.shiro.realm.MongoUserPasswordRealmAuthenticationTest.java

License:Apache License

@Test
@MongoData("/principals.json")
public void credentialsRoundTrip() {
    BasicDBObject principal = new BasicDBObject();
    principal.put(MongoUserPasswordRealm.DEFAULT_AUTH_FIELD,
            realm.createUserCredentials("generatedUser", "password"));
    principal.put("_id", "generated-user-id");
    getMongoDB().getCollection("principals").insert(principal);
    System.out.println("Principal is " + principal);

    // now make sure we can find it
    AuthenticationInfo info = realm
            .getAuthenticationInfo(new UsernamePasswordToken("generatedUser", "password"));

    assertEquals(info.getPrincipals().getPrimaryPrincipal(), "generated-user-id");
}

From source file:com.thjug.bgile.servlet.AuthenticationListenerImpl.java

License:Creative Commons License

@Override
public void onSuccess(final AuthenticationToken token, final AuthenticationInfo info) {
    final Account account = (Account) info.getPrincipals().getPrimaryPrincipal();
    if (account != null) {
        LOG.info("Account {} id {} login success.", account.getId(), account.getUsername());
    }//w w  w. j  a  v a2 s  .c  o  m
}