Example usage for org.apache.shiro.authc SimpleAuthenticationInfo SimpleAuthenticationInfo

List of usage examples for org.apache.shiro.authc SimpleAuthenticationInfo SimpleAuthenticationInfo

Introduction

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

Prototype

public SimpleAuthenticationInfo(PrincipalCollection principals, Object credentials) 

Source Link

Document

Constructor that takes in an account's identifying principal(s) and its corresponding credentials that verify the principals.

Usage

From source file:com.ceecloud.shiro.CasRealm.java

License:Apache License

/**
 * Authenticates a user and retrieves its information.
 * /*from w  w w .ja va  2s .c  o  m*/
 * @param token the authentication token
 * @throws AuthenticationException if there is an error during authentication.
 */
@Override
@SuppressWarnings("unchecked")
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    CasToken casToken = (CasToken) token;
    if (token == null) {
        return null;
    }

    String ticket = (String) casToken.getCredentials();
    if (!StringUtils.hasText(ticket)) {
        return null;
    }

    TicketValidator ticketValidator = ensureTicketValidator();

    try {
        // contact CAS server to validate service ticket
        Assertion casAssertion = ticketValidator.validate(ticket, getCasService());
        // get principal, user id and attributes
        AttributePrincipal casPrincipal = casAssertion.getPrincipal();
        String userId = casPrincipal.getName();
        log.debug("Validate ticket : {} in CAS server : {} to retrieve user : {}",
                new Object[] { ticket, getCasServerUrlPrefix(), userId });

        Map<String, Object> attributes = casPrincipal.getAttributes();
        // refresh authentication token (user id + remember me)
        casToken.setUserId(userId);
        String rememberMeAttributeName = getRememberMeAttributeName();
        String rememberMeStringValue = (String) attributes.get(rememberMeAttributeName);
        boolean isRemembered = rememberMeStringValue != null && Boolean.parseBoolean(rememberMeStringValue);
        if (isRemembered) {
            casToken.setRememberMe(true);
        }
        // create simple authentication info
        List<Object> principals = CollectionUtils.asList(userId, attributes);
        PrincipalCollection principalCollection = new SimplePrincipalCollection(principals, getName());
        return new SimpleAuthenticationInfo(principalCollection, ticket);
    } catch (TicketValidationException e) {
        throw new CasAuthenticationException("Unable to validate ticket [" + ticket + "]", e);
    }
}

From source file:com.dylan.shiro.infrastructure.shiro.CasRealm.java

License:Apache License

/**
 * Authenticates a user and retrieves its information.
 * /*from  w w w  .j a  va 2 s  . c o m*/
 * @param token the authentication token
 * @throws AuthenticationException if there is an error during authentication.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    CasToken casToken = (CasToken) token;
    if (token == null) {
        return null;
    }

    String ticket = (String) casToken.getCredentials();
    if (!StringUtils.hasText(ticket)) {
        return null;
    }

    TicketValidator ticketValidator = ensureTicketValidator();

    try {
        // contact CAS server to validate service ticket
        Assertion casAssertion = ticketValidator.validate(ticket, getCasService());
        // get principal, user id and attributes
        AttributePrincipal casPrincipal = casAssertion.getPrincipal();
        String userId = casPrincipal.getName();
        log.debug("Validate ticket : {} in CAS server : {} to retrieve user : {}",
                new Object[] { ticket, getCasServerUrlPrefix(), userId });

        Map<String, Object> attributes = casPrincipal.getAttributes();
        // refresh authentication token (user id + remember me)
        casToken.setUserId(userId);
        String rememberMeAttributeName = getRememberMeAttributeName();
        String rememberMeStringValue = (String) attributes.get(rememberMeAttributeName);
        boolean isRemembered = rememberMeStringValue != null && Boolean.parseBoolean(rememberMeStringValue);
        if (isRemembered) {
            casToken.setRememberMe(true);
        }
        // create simple authentication info
        List<Object> principals = CollectionUtils.asList(userId, attributes);
        PrincipalCollection principalCollection = new SimplePrincipalCollection(principals, getName());
        return new SimpleAuthenticationInfo(principalCollection, ticket);
    } catch (TicketValidationException e) {
        throw new CasAuthenticationException("Unable to validate ticket [" + ticket + "]", e);
    }
}

From source file:com.github.dactiv.fear.user.web.AccountController.java

License:Apache License

/**
 * ?/* www .  j a v a2s . com*/
 *
 * @param entity              Map
 * @param redirectAttributes spring mvc ??
 *
 * @return ? json
 *
 * @throws IOException
 */
@RequestMapping("update-profile")
public String updateProfile(@RequestParam Map<String, Object> entity, RedirectAttributes redirectAttributes)
        throws IOException {
    // ?? shiro subject ?
    Subject subject = SecurityUtils.getSubject();
    Map<String, Object> user = Casts.cast(subject.getPrincipal());
    // ???
    user.putAll(entity);
    // ??
    Apis.invoke("accountService", "saveUser", user, null);

    DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager();
    // ?????
    AbstractRememberMeManager rmm = (AbstractRememberMeManager) securityManager.getRememberMeManager();
    rmm.rememberIdentity(subject, null,
            new SimpleAuthenticationInfo(subject.getPrincipals(), user.get("password")));

    // ? subjectDao, ???
    securityManager.getSubjectDAO().save(subject);

    redirectAttributes.addFlashAttribute("message", "??.");

    return "redirect:/account/user-profile";
}

From source file:com.sonatype.nexus.repository.nuget.internal.security.NugetApiKeyRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
        throws AuthenticationException {
    final PrincipalCollection principals = keyStore.getPrincipals((char[]) token.getCredentials());
    if (null != principals) {
        try {//from   ww w. j  a  v a 2 s  .  com
            if (UserStatus.active.equals(principalsHelper.getUserStatus(principals))) {
                ((NexusApiKeyAuthenticationToken) token).setPrincipal(principals.getPrimaryPrincipal());
                return new SimpleAuthenticationInfo(principals, token.getCredentials());
            }
        } catch (final UserNotFoundException e) {
            keyStore.deleteApiKey(principals);
        }
    }
    return null;
}

From source file:com.stormpath.sample.security.SampleApplicationRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {

    if (authcToken instanceof UsernamePasswordToken) {
        return super.doGetAuthenticationInfo(authcToken);
    }//from   ww w  . ja v  a 2  s  .  c  om

    HttpRequestAuthenticationToken token = (HttpRequestAuthenticationToken) authcToken;

    Application application = ensureApplicationReference();

    AccountResult accountResult;

    try {
        accountResult = application.newIdSiteCallbackHandler(token.getHttpServletRequest()).getAccountResult();
    } catch (ResourceException | InvalidJwtException | IllegalArgumentException e) {
        String msg = StringUtils.clean(e.getMessage());
        if (msg == null) {
            msg = "Invalid SSO Request";
        }
        throw new AuthenticationException(msg, e);
    }

    PrincipalCollection principals;

    try {
        principals = createPrincipals(accountResult.getAccount());
    } catch (Exception e) {
        throw new AuthenticationException("Unable to obtain authenticated account properties.", e);
    }
    return new SimpleAuthenticationInfo(principals, null);
}

From source file:com.stormpath.shiro.realm.ApplicationRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {

    assertState();/*from w  w w . j a v a 2 s.  com*/

    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

    AuthenticationRequest request = createAuthenticationRequest(token);

    Application application = ensureApplicationReference();

    Account account;

    try {
        account = application.authenticateAccount(request).getAccount();
    } catch (ResourceException e) {
        //todo error code translation to throw more detailed exceptions
        String msg = StringUtils.clean(e.getMessage());
        if (msg == null) {
            msg = StringUtils.clean(e.getDeveloperMessage());
        }
        if (msg == null) {
            msg = "Invalid login or password.";
        }
        throw new AuthenticationException(msg, e);
    }

    PrincipalCollection principals;

    try {
        principals = createPrincipals(account);
    } catch (Exception e) {
        throw new AuthenticationException("Unable to obtain authenticated account properties.", e);
    }

    return new SimpleAuthenticationInfo(principals, null);
}

From source file:com.stormpath.shiro.realm.JWTApplicationRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {

    assertState();/*  w ww  .  j av  a2s.co m*/

    JwtAuthenticationToken token = (JwtAuthenticationToken) authcToken;

    OAuthBearerRequestAuthentication request = createAuthenticationRequest(token);

    Application application = ensureApplicationReference();

    Account account;

    try {
        OAuthBearerRequestAuthenticationResult res = Authenticators.OAUTH_BEARER_REQUEST_AUTHENTICATOR
                .forApplication(application).authenticate(request);
        //account = application.authenticateAccount(request).getAccount();
        account = res.getAccount();
    } catch (ResourceException e) {
        //todo error code translation to throw more detailed exceptions
        String msg = StringUtils.clean(e.getMessage());
        if (msg == null) {
            msg = StringUtils.clean(e.getDeveloperMessage());
        }
        if (msg == null) {
            msg = "Invalid login or password.";
        }
        throw new AuthenticationException(msg, e);
    }

    PrincipalCollection principals;

    try {
        principals = createPrincipals(account);
    } catch (Exception e) {
        throw new AuthenticationException("Unable to obtain authenticated account properties.", e);
    }

    return new SimpleAuthenticationInfo(principals, null);
}

From source file:com.stormpath.shiro.realm.PassthroughApplicationRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    AccountAuthenticationToken accessAuthToken = (AccountAuthenticationToken) token;

    PrincipalCollection principals;//ww  w. j  av a2s.com

    try {

        Account account = accessAuthToken.getAccount();
        // we should not reach this point if the account is not enabled, but, just in case.
        if (AccountStatus.ENABLED != account.getStatus()) {
            throw new AuthenticationException("Account for user [" + account.getHref() + "] is not enabled.");
        }

        principals = createPrincipals(account);
    } catch (Exception e) {
        throw new AuthenticationException("Unable to obtain authenticated account properties.", e);
    }

    return new SimpleAuthenticationInfo(principals, null);
}

From source file:com.thesett.util.security.realm.ShiroDBRealm.java

License:Apache License

/**
 * {@inheritDoc}/*  w  w  w  .j  a  v  a  2s .  c o m*/
 *
 * <p/>Looks up a user by username in the database, and supplies the user id and password for authentication.
 */
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authNToken)
        throws AuthenticationException {
    LOG.fine("protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authNToken): called");

    UsernamePasswordToken upToken = (UsernamePasswordToken) authNToken;

    String username = upToken.getUsername();

    if (StringUtils.nullOrEmpty(username)) {
        throw new AccountException("'username' is required by this realm.");
    }

    AuthUser user = userSecurityDAO.findUserByUsername(username);

    if (user != null) {
        String password = user.getPassword();

        PrincipalCollection principals = new SimplePrincipalCollection(user.getId(), getName());

        return new SimpleAuthenticationInfo(principals, password);
    }

    return null;
}

From source file:com.thesett.util.security.realm.ShiroJWTRealm.java

License:Apache License

/**
 * {@inheritDoc}/*  ww w. ja va2s  .c  o  m*/
 *
 * <p/>Verifies the JWT token.
 */
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken)
        throws AuthenticationException {
    JWTAuthenticationToken jwtAuthToken = (JWTAuthenticationToken) authToken;

    // Ensure that the token is validate and extract its claims.
    jwtAuthToken.setPublicKey(publicKey);
    jwtAuthToken.assertValid();
    jwtAuthToken.extractClaims();

    PrincipalCollection principals = new SimplePrincipalCollection(jwtAuthToken, getName());

    return new SimpleAuthenticationInfo(principals, jwtAuthToken.getToken());
}