Example usage for org.springframework.security.web.authentication.preauth PreAuthenticatedAuthenticationToken setAuthenticated

List of usage examples for org.springframework.security.web.authentication.preauth PreAuthenticatedAuthenticationToken setAuthenticated

Introduction

In this page you can find the example usage for org.springframework.security.web.authentication.preauth PreAuthenticatedAuthenticationToken setAuthenticated.

Prototype

public void setAuthenticated(boolean authenticated) 

Source Link

Usage

From source file:org.slc.sli.api.security.OauthMongoSessionManager.java

/**
 * Loads session referenced by the headers
 *
 * If there's a problem with the token, we embed a relevant {@link OAuth2Exception} in the
 * auth's details field/*  w  ww  .j  a v  a2s .co  m*/
 *
 * Per Oauth spec:
 *
 * If the protected resource request included an access token and failed authentication, the
 * resource server SHOULD
 * include the "error" attribute to provide the client with the reason why the access request
 * was declined.
 *
 * In addition, the resource server MAY include the "error_description" attribute to provide
 * developers a
 * human-readable explanation that is not meant to be displayed to end-users.
 *
 * If the request lacks any authentication information (e.g., the client was unaware that
 * authentication is
 * necessary or attempted using an unsupported authentication method), the resource server
 * SHOULD NOT include an
 * error code or other error information.
 *
 * @param headers
 * @return
 */
@Override
@SuppressWarnings("unchecked")
public OAuth2Authentication getAuthentication(String authz) {
    OAuth2Authentication auth = createAnonymousAuth();
    String accessToken = getTokenFromAuthHeader(authz);
    if (accessToken != null) {
        OAuth2Authentication cached = this.sessions.get(accessToken);

        if (cached != null) {
            auth = cached;
            SLIPrincipal prince = (SLIPrincipal) auth.getPrincipal();
            prince.clearObligations();
            prince.setStudentAccessFlag(true);
        } else {
            Entity sessionEntity = findEntityForAccessToken(accessToken);
            if (sessionEntity != null) {
                List<Map<String, Object>> sessions = (List<Map<String, Object>>) sessionEntity.getBody()
                        .get("appSession");
                for (Map<String, Object> session : sessions) {
                    if (session.get("token").equals(accessToken)) {

                        // Log that the long lived session is being used
                        Date createdOn;
                        if (sessionEntity.getMetaData().get("created").getClass() == String.class) {
                            String date = (String) sessionEntity.getMetaData().get("created");

                            if (date.contains("T")) {
                                date = date.substring(0, date.indexOf("T"));
                            }
                            createdOn = DateTimeUtil.parseDateTime(date).toDate();

                        } else {
                            createdOn = (Date) sessionEntity.getMetaData().get("created");
                        }
                        Long hl = (Long) sessionEntity.getBody().get("hardLogout");

                        if (isLongLived(hl - createdOn.getTime())) {
                            String displayToken = accessToken.substring(0, 6) + "......"
                                    + accessToken.substring(accessToken.length() - 4, accessToken.length());
                            LOG.info("Using long-lived session {} belonging to app {}", displayToken,
                                    session.get("clientId"));
                        }
                        // ****

                        ClientToken token = new ClientToken((String) session.get("clientId"), null, null);

                        try {
                            // Spring doesn't provide a setter for the approved field (used by
                            // isAuthorized), so we set it the hard way
                            Field approved = ClientToken.class.getDeclaredField("approved");
                            approved.setAccessible(true);
                            approved.set(token, true);
                        } catch (Exception e) {
                            LOG.error("Error processing authentication.  Anonymous context will be returned.",
                                    e);
                        }

                        SLIPrincipal principal = jsoner.convertValue(sessionEntity.getBody().get("principal"),
                                SLIPrincipal.class);
                        TenantContext.setTenantId(principal.getTenantId());

                        principal.setSessionId(sessionEntity.getEntityId());

                        // add logic here that checks principal.getUserType()
                        // -> if nil, set to staff
                        principal.setEntity(locator.locate(principal.getTenantId(), principal.getExternalId(),
                                principal.getUserType(), token.getClientId()).getEntity());

                        principal.populateChildren(repo);
                        Collection<GrantedAuthority> authorities = null;

                        if ((!principal.isAdminRealmAuthenticated())
                                && (principal.getUserType() == null || principal.getUserType().isEmpty()
                                        || principal.getUserType().equals(EntityNames.STAFF))) {
                            principal.setEdOrgRights(generateEdOrgRightsMap(principal, false));
                            principal.setEdOrgSelfRights(generateEdOrgRightsMap(principal, true));

                            // Generate EdOrg-Context-Rights map for principal.
                            principal.setEdOrgContextRights(generateEdOrgContextRightsCache(principal));
                        } else {
                            Collection<GrantedAuthority> selfAuthorities = resolveAuthorities(
                                    principal.getTenantId(), principal.getRealm(), principal.getRoles(),
                                    principal.isAdminRealmAuthenticated(), true);
                            principal.setSelfRights(selfAuthorities);
                            LOG.debug("Granted self rights - {}", selfAuthorities);

                            authorities = resolveAuthorities(principal.getTenantId(), principal.getRealm(),
                                    principal.getRoles(), principal.isAdminRealmAuthenticated(), false);
                            LOG.debug("Granted regular rights - {}", authorities);
                        }

                        if (!principal.isAdminRealmAuthenticated()) {
                            principal.setAuthorizingEdOrgs(
                                    appValidator.getAuthorizingEdOrgsForApp(token.getClientId()));
                        }
                        PreAuthenticatedAuthenticationToken userToken = new PreAuthenticatedAuthenticationToken(
                                principal, accessToken, authorities);
                        userToken.setAuthenticated(true);
                        auth = new OAuth2Authentication(token, userToken);
                        this.sessions.put(accessToken, auth);

                        // Extend the session
                        long previousExpire = (Long) sessionEntity.getBody().get("expiration");
                        // only update the expire time if it is within the next 5 minutes
                        // this explicitly does not update the expire time for long-lived
                        // session tokens
                        // they will last until their end, plus a 5 minutes session buffer
                        if (previousExpire < (System.currentTimeMillis() + 300000)) {
                            sessionEntity.getBody().put("expiration",
                                    System.currentTimeMillis() + this.sessionLength);
                            repo.update(SESSION_COLLECTION, sessionEntity, false);
                        }
                        // Purge expired sessions
                        purgeExpiredSessions();
                        break;
                    }
                }
            } else {
                // details is a convenient place to store an error message
                auth.setDetails(new OAuthAccessException(OAuthError.INVALID_TOKEN,
                        "The access token does not exist or is expired."));
            }
        }
    } else {
        // details is a convenient place to store an error message
        if (authz == null) {
            auth.setDetails(null); // oauth spec says not to give detailed error information if
                                   // token isn't included
        } else {
            auth.setDetails(new OAuthAccessException(OAuthError.INVALID_TOKEN,
                    "Authorization header must be of the form 'Bearer <token>'"));
        }
    }

    return auth;
}