Example usage for org.springframework.security.core Authentication getClass

List of usage examples for org.springframework.security.core Authentication getClass

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.orcid.api.t2.server.delegator.impl.T2OrcidApiServiceDelegatorImpl.java

/**
 * Unregister a webhook from a profile. As with all calls, if the message
 * contains any other elements, a 400 Bad Request will be returned.
 * // www .j a v a2 s. com
 * @param orcid
 *            the identifier of the profile to unregister the webhook
 * @param uriInfo
 *            an uri object containing the webhook that will be unregistred
 * @return If successful, returns a 204 No content.
 * */
@Override
@AccessControl(requiredScope = ScopePathType.WEBHOOK)
public Response unregisterWebhook(UriInfo uriInfo, String orcid, String webhookUri) {
    ProfileEntity profile = profileEntityCacheManager.retrieve(orcid);
    if (profile != null) {
        WebhookEntityPk webhookPk = new WebhookEntityPk(profile, webhookUri);
        WebhookEntity webhook = webhookDao.find(webhookPk);
        if (webhook == null) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("orcid", orcid);
            params.put("uri", webhookUri);
            throw new OrcidWebhookNotFoundException(params);
        } else {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String clientId = null;
            if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
                OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
                clientId = authorizationRequest.getClientId();
            }
            // Check if user can unregister this webhook
            if (webhook.getClientDetails().getId().equals(clientId)) {
                webhookDao.remove(webhookPk);
                webhookDao.flush();
                return Response.noContent().build();
            } else {
                // Throw 403 exception: user is not allowed to unregister
                // that webhook
                throw new OrcidForbiddenException(
                        localeManager.resolveMessage("apiError.forbidden_unregister_webhook.exception"));
            }
        }
    } else {
        Map<String, String> params = new HashMap<String, String>();
        params.put("orcid", orcid);
        throw new OrcidNotFoundException(params);
    }
}

From source file:org.orcid.core.security.DefaultPermissionChecker.java

/**
 * Obtain the current users' permission and return the
 * {@link org.orcid.jaxb.model.message.Visibility} array containing those
 * /* w w  w.  j  a  va2  s  .c  o m*/
 * @param authentication
 *            the object containing the user's security information
 * @return the {@alink Visibility} array of the current user
 */
@Override
public Set<Visibility> obtainVisibilitiesForAuthentication(Authentication authentication,
        ScopePathType requiredScope, OrcidMessage orcidMessage) {
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    if (authoritiesHasRole(authorities, "ROLE_SYSTEM")) {
        return new HashSet<Visibility>(Arrays.asList(Visibility.SYSTEM));
    } else if (OrcidOAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
        OrcidOAuth2Authentication auth2Authentication = (OrcidOAuth2Authentication) authentication;
        Set<Visibility> visibilities = getVisibilitiesForOauth2Authentication(auth2Authentication, orcidMessage,
                requiredScope);
        return visibilities;
    } else {
        throw new IllegalArgumentException("Cannot obtain authentication details from " + authentication);
    }
}

From source file:org.orcid.core.security.DefaultPermissionChecker.java

private void performPermissionChecks(Authentication authentication, ScopePathType requiredScope, String orcid,
        OrcidMessage orcidMessage) {/*from ww  w.jav a  2 s .c om*/
    // We can trust that this will return a not-null Authentication object
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    if (authoritiesHasRole(authorities, "ROLE_SYSTEM")) {
        return;
    } else if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
        checkScopes(oAuth2Authentication, requiredScope);
        performSecurityChecks(oAuth2Authentication, requiredScope, orcidMessage, orcid);
    } else {
        throw new AccessControlException(
                "Cannot access method with authentication type " + authentication != null
                        ? authentication.toString()
                        : ", as it's null!");
    }
}

From source file:org.springframework.security.authentication.ProviderManager.java

/**
 * Attempts to authenticate the passed {@link Authentication} object.
 * <p>// www  . j  ava  2 s . c  om
 * The list of {@link AuthenticationProvider}s will be successively tried until an
 * <code>AuthenticationProvider</code> indicates it is capable of authenticating the
 * type of <code>Authentication</code> object passed. Authentication will then be
 * attempted with that <code>AuthenticationProvider</code>.
 * <p>
 * If more than one <code>AuthenticationProvider</code> supports the passed
 * <code>Authentication</code> object, the first one able to successfully
 * authenticate the <code>Authentication</code> object determines the
 * <code>result</code>, overriding any possible <code>AuthenticationException</code>
 * thrown by earlier supporting <code>AuthenticationProvider</code>s.
 * On successful authentication, no subsequent <code>AuthenticationProvider</code>s
 * will be tried.
 * If authentication was not successful by any supporting
 * <code>AuthenticationProvider</code> the last thrown
 * <code>AuthenticationException</code> will be rethrown.
 *
 * @param authentication the authentication request object.
 *
 * @return a fully authenticated object including credentials.
 *
 * @throws AuthenticationException if authentication fails.
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Class<? extends Authentication> toTest = authentication.getClass();
    AuthenticationException lastException = null;
    AuthenticationException parentException = null;
    Authentication result = null;
    Authentication parentResult = null;
    boolean debug = logger.isDebugEnabled();

    for (AuthenticationProvider provider : getProviders()) {
        if (!provider.supports(toTest)) {
            continue;
        }

        if (debug) {
            logger.debug("Authentication attempt using " + provider.getClass().getName());
        }

        try {
            result = provider.authenticate(authentication);

            if (result != null) {
                copyDetails(authentication, result);
                break;
            }
        } catch (AccountStatusException e) {
            prepareException(e, authentication);
            // SEC-546: Avoid polling additional providers if auth failure is due to
            // invalid account status
            throw e;
        } catch (InternalAuthenticationServiceException e) {
            prepareException(e, authentication);
            throw e;
        } catch (AuthenticationException e) {
            lastException = e;
        }
    }

    if (result == null && parent != null) {
        // Allow the parent to try.
        try {
            result = parentResult = parent.authenticate(authentication);
        } catch (ProviderNotFoundException e) {
            // ignore as we will throw below if no other exception occurred prior to
            // calling parent and the parent
            // may throw ProviderNotFound even though a provider in the child already
            // handled the request
        } catch (AuthenticationException e) {
            lastException = parentException = e;
        }
    }

    if (result != null) {
        if (eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) {
            // Authentication is complete. Remove credentials and other secret data
            // from authentication
            ((CredentialsContainer) result).eraseCredentials();
        }

        // If the parent AuthenticationManager was attempted and successful than it will publish an AuthenticationSuccessEvent
        // This check prevents a duplicate AuthenticationSuccessEvent if the parent AuthenticationManager already published it
        if (parentResult == null) {
            eventPublisher.publishAuthenticationSuccess(result);
        }
        return result;
    }

    // Parent was null, or didn't authenticate (or throw an exception).

    if (lastException == null) {
        lastException = new ProviderNotFoundException(messages.getMessage("ProviderManager.providerNotFound",
                new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}"));
    }

    // If the parent AuthenticationManager was attempted and failed than it will publish an AbstractAuthenticationFailureEvent
    // This check prevents a duplicate AbstractAuthenticationFailureEvent if the parent AuthenticationManager already published it
    if (parentException == null) {
        prepareException(lastException, authentication);
    }

    throw lastException;
}

From source file:org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider.java

/**
 * Authenticate the given PreAuthenticatedAuthenticationToken.
 * <p>//  ww  w. j ava2  s .  c o m
 * If the principal contained in the authentication object is null, the request will
 * be ignored to allow other providers to authenticate it.
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("PreAuthenticated authentication request: " + authentication);
    }

    if (authentication.getPrincipal() == null) {
        logger.debug("No pre-authenticated principal found in request.");

        if (throwExceptionWhenTokenRejected) {
            throw new BadCredentialsException("No pre-authenticated principal found in request.");
        }
        return null;
    }

    if (authentication.getCredentials() == null) {
        logger.debug("No pre-authenticated credentials found in request.");

        if (throwExceptionWhenTokenRejected) {
            throw new BadCredentialsException("No pre-authenticated credentials found in request.");
        }
        return null;
    }

    UserDetails ud = preAuthenticatedUserDetailsService
            .loadUserDetails((PreAuthenticatedAuthenticationToken) authentication);

    userDetailsChecker.check(ud);

    PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken(ud,
            authentication.getCredentials(), ud.getAuthorities());
    result.setDetails(authentication.getDetails());

    return result;
}

From source file:org.springframework.security.web.context.HttpSessionSecurityContextRepository.java

private boolean isTransientAuthentication(Authentication authentication) {
    return AnnotationUtils.getAnnotation(authentication.getClass(), Transient.class) != null;
}

From source file:org.springframework.ws.soap.security.x509.X509AuthenticationProvider.java

/**
 * If the supplied authentication token contains a certificate then this will be passed to the configured
 * {@link X509AuthoritiesPopulator} to obtain the user details and authorities for the user identified by the
 * certificate.<p>If no certificate is present (for example, if the filter is applied to an HttpRequest for
 * which client authentication hasn't been configured in the container) then a BadCredentialsException will be
 * raised.</p>/*from   w  ww  .  j  av  a 2 s  .co m*/
 *
 * @param authentication the authentication request.
 *
 * @return an X509AuthenticationToken containing the authorities of the principal represented by the certificate.
 *
 * @throws AuthenticationException if the {@link X509AuthoritiesPopulator} rejects the certficate.
 * @throws BadCredentialsException if no certificate was presented in the authentication request.
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("X509 authentication request: " + authentication);
    }

    X509Certificate clientCertificate = (X509Certificate) authentication.getCredentials();

    if (clientCertificate == null) {
        throw new BadCredentialsException(
                messages.getMessage("X509AuthenticationProvider.certificateNull", "Certificate is null"));
    }

    UserDetails user = userCache.getUserFromCache(clientCertificate);

    if (user == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Authenticating with certificate " + clientCertificate);
        }
        user = x509AuthoritiesPopulator.getUserDetails(clientCertificate);
        userCache.putUserInCache(clientCertificate, user);
    }

    X509AuthenticationToken result = new X509AuthenticationToken(user, clientCertificate,
            user.getAuthorities());

    result.setDetails(authentication.getDetails());

    return result;
}

From source file:org.unitedinternet.cosmo.acegisecurity.providers.ticket.TicketAuthenticationProvider.java

/**
 * Authenticate./*from   w ww  .j  ava  2s.  c o m*/
 * @param authentication The authentication.
 * @return authentication.
 * @throws AuthenticationException - if something is wrong this exception is thrown.
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass()) || !(authentication instanceof TicketAuthenticationToken)) {
        return null;
    }

    TicketAuthenticationToken token = (TicketAuthenticationToken) authentication;
    for (String key : token.getKeys()) {
        Ticket ticket = findTicket(token.getPath(), key);
        if (ticket != null) {
            token.setTicket(ticket);
            token.setAuthenticated(true);
            return token;
        }
    }

    throw new TicketException("No valid tickets found for resource at " + token.getPath());
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.AbstractOwncloudRestServiceImpl.java

protected HttpHeaders prepareHeadersWithBasicAuthorization() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (OwncloudUtils.isAuthenticationClassNotSupported(authentication.getClass())) {
        throw new OwncloudInvalidAuthenticationObjectException(authentication,
                UsernamePasswordAuthenticationToken.class);
    }/*from www. j av a 2 s.c  o  m*/
    return OwncloudRestUtils.addAuthorizationHeader(authentication);
}