Example usage for org.springframework.security.oauth2.provider OAuth2Authentication setDetails

List of usage examples for org.springframework.security.oauth2.provider OAuth2Authentication setDetails

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider OAuth2Authentication setDetails.

Prototype

public void setDetails(Object details) 

Source Link

Usage

From source file:eu.trentorise.smartcampus.resourceprovider.filter.ResourceAuthenticationManager.java

/**
 * Check whether the access to the specific resource is granted. The The
 * resource is identified from the {@link ResourceCallAuthenticationToken}
 * fields {@link ResourceCallAuthenticationToken#getRequestPath()} and
 * {@link ResourceCallAuthenticationToken#getHttpMethod()}.
 * /*from ww  w .  j av a  2 s.c o  m*/
 * @param authentication
 *            the authentication token object as instance of
 *            {@link ResourceCallAuthenticationToken}.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    assert authentication instanceof ResourceCallAuthenticationToken;
    ResourceCallAuthenticationToken rcAuth = (ResourceCallAuthenticationToken) authentication;

    String token = (String) rcAuth.getPrincipal();
    OAuth2Authentication auth = loadAuthentication(token);

    if (auth == null) {
        throw new InvalidTokenException("Invalid token: " + token);
    }

    String resourceUri;
    try {
        resourceUri = getUriManager().getUriFromRequest(rcAuth.getRequestPath(), rcAuth.getHttpMethod(),
                auth.getAuthorities());
    } catch (IOException e) {
        throw new OAuth2Exception("Problem accessing resource descriptor");
    }

    String resourceID = resourceUri;// resourceStore.loadResourceByResourceUri(resourceUri);
    // test senza lettura db

    Collection<String> resourceIds = auth.getAuthorizationRequest().getScope();

    if (resourceID == null || resourceIds.isEmpty() || !resourceIds.contains(resourceID)) {
        throw new OAuth2AccessDeniedException(
                "Invalid token does not contain resource id (" + resourceUri + ")");
    }

    String authority = authServices.loadResourceAuthorityByResourceUri(resourceUri);
    if (ROLE_USER.equals(authority) && auth.isClientOnly()) {
        throw new OAuth2AccessDeniedException("Incorrect access method");
    }
    if (ROLE_CLIENT.equals(authority) && !auth.isClientOnly()) {
        throw new OAuth2AccessDeniedException("Incorrect access method");
    }

    auth.setDetails(authentication.getDetails());

    return auth;
}

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//from w w w  .  j  a  v  a  2 s .  c  o  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;
}