List of usage examples for org.springframework.security.core Authentication getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.cloudfoundry.identity.uaa.authentication.manager.ExternalLoginAuthenticationManager.java
protected UaaUser getUser(Authentication request, ExternalAuthenticationDetails authDetails) { UserDetails userDetails;//from w w w. j a v a2s. co m if (request.getPrincipal() instanceof UserDetails) { userDetails = (UserDetails) request.getPrincipal(); } else if (request instanceof UsernamePasswordAuthenticationToken) { String username = request.getPrincipal().toString(); String password = request.getCredentials() != null ? request.getCredentials().toString() : ""; userDetails = new User(username, password, true, true, true, true, UaaAuthority.USER_AUTHORITIES); } else if (request.getPrincipal() == null) { logger.debug(this.getClass().getName() + "[" + name + "] cannot process null principal"); return null; } else { logger.debug(this.getClass().getName() + "[" + name + "] cannot process request of type: " + request.getClass().getName()); return null; } String name = userDetails.getUsername(); String email = null; if (userDetails instanceof Mailable) { email = ((Mailable) userDetails).getEmailAddress(); if (name == null) { name = email; } } if (email == null) { email = generateEmailIfNull(name); } String givenName = null; String familyName = null; if (userDetails instanceof Named) { Named names = (Named) userDetails; givenName = names.getGivenName(); familyName = names.getFamilyName(); } String phoneNumber = (userDetails instanceof DialableByPhone) ? ((DialableByPhone) userDetails).getPhoneNumber() : null; String externalId = (userDetails instanceof ExternallyIdentifiable) ? ((ExternallyIdentifiable) userDetails).getExternalId() : name; UaaUserPrototype userPrototype = new UaaUserPrototype().withUsername(name).withPassword("").withEmail(email) .withAuthorities(UaaAuthority.USER_AUTHORITIES).withGivenName(givenName).withFamilyName(familyName) .withCreated(new Date()).withModified(new Date()).withOrigin(origin).withExternalId(externalId) .withZoneId(IdentityZoneHolder.get().getId()).withPhoneNumber(phoneNumber); return new UaaUser(userPrototype); }
From source file:org.cloudfoundry.identity.uaa.authentication.manager.LoginAuthenticationManager.java
@Override public Authentication authenticate(Authentication request) throws AuthenticationException { if (!(request instanceof AuthzAuthenticationRequest)) { logger.debug("Cannot process request of type: " + request.getClass().getName()); return null; }/*from www . j a v a 2s. c o m*/ AuthzAuthenticationRequest req = (AuthzAuthenticationRequest) request; Map<String, String> info = req.getInfo(); logger.debug("Processing authentication request for " + req.getName()); SecurityContext context = SecurityContextHolder.getContext(); if (context.getAuthentication() instanceof OAuth2Authentication) { OAuth2Authentication authentication = (OAuth2Authentication) context.getAuthentication(); if (authentication.isClientOnly()) { UaaUser user = getUser(req, info); UaaAuthenticationDetails authdetails = (UaaAuthenticationDetails) req.getDetails(); boolean addNewAccounts = authdetails != null && authdetails.isAddNew(); try { if (NotANumber.equals(user.getId())) { user = userDatabase.retrieveUserByName(user.getUsername(), user.getOrigin()); } else { //we should never add new accounts if we specify user_id addNewAccounts = false; user = userDatabase.retrieveUserById(user.getId()); } } catch (UsernameNotFoundException e) { // Not necessarily fatal if (addNewAccounts) { // Register new users automatically publish(new NewUserAuthenticatedEvent(user)); try { user = userDatabase.retrieveUserByName(user.getUsername(), user.getOrigin()); } catch (UsernameNotFoundException ex) { throw new BadCredentialsException("Bad credentials"); } } else { //if add_new=false then this is a bad user ID throw new BadCredentialsException("Bad Credentials"); } } Authentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(), authdetails); publish(new UserAuthenticationSuccessEvent(user, success)); return success; } } logger.debug("Did not locate login credentials"); return null; }
From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { throw new IllegalArgumentException( "Only SAMLAuthenticationToken is supported, " + authentication.getClass() + " was attempted"); }/*from w w w .j a v a2 s . c o m*/ IdentityZone zone = IdentityZoneHolder.get(); SAMLAuthenticationToken token = (SAMLAuthenticationToken) authentication; SAMLMessageContext context = token.getCredentials(); String alias = context.getPeerExtendedMetadata().getAlias(); boolean addNew = true; IdentityProvider<SamlIdentityProviderDefinition> idp; SamlIdentityProviderDefinition samlConfig; try { idp = identityProviderProvisioning.retrieveByOrigin(alias, IdentityZoneHolder.get().getId()); samlConfig = idp.getConfig(); addNew = samlConfig.isAddShadowUserOnLogin(); if (!idp.isActive()) { throw new ProviderNotFoundException("Identity Provider has been disabled by administrator."); } } catch (EmptyResultDataAccessException x) { throw new ProviderNotFoundException("Not identity provider found in zone."); } ExpiringUsernameAuthenticationToken result = getExpiringUsernameAuthenticationToken(authentication); UaaPrincipal samlPrincipal = new UaaPrincipal(Origin.NotANumber, result.getName(), result.getName(), alias, result.getName(), zone.getId()); Collection<? extends GrantedAuthority> samlAuthorities = retrieveSamlAuthorities(samlConfig, (SAMLCredential) result.getCredentials()); Collection<? extends GrantedAuthority> authorities = mapAuthorities(idp.getOriginKey(), samlAuthorities); Set<String> filteredExternalGroups = filterSamlAuthorities(samlConfig, samlAuthorities); MultiValueMap<String, String> userAttributes = retrieveUserAttributes(samlConfig, (SAMLCredential) result.getCredentials()); UaaUser user = createIfMissing(samlPrincipal, addNew, authorities, userAttributes); UaaPrincipal principal = new UaaPrincipal(user); return new LoginSamlAuthenticationToken(principal, result).getUaaAuthentication(user.getAuthorities(), filteredExternalGroups, userAttributes); }
From source file:org.cloudfoundry.identity.uaa.provider.saml.LoginSamlAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { throw new IllegalArgumentException( "Only SAMLAuthenticationToken is supported, " + authentication.getClass() + " was attempted"); }/* ww w .ja v a2 s .co m*/ IdentityZone zone = IdentityZoneHolder.get(); SAMLAuthenticationToken token = (SAMLAuthenticationToken) authentication; SAMLMessageContext context = token.getCredentials(); String alias = context.getPeerExtendedMetadata().getAlias(); boolean addNew; IdentityProvider<SamlIdentityProviderDefinition> idp; SamlIdentityProviderDefinition samlConfig; try { idp = identityProviderProvisioning.retrieveByOrigin(alias, IdentityZoneHolder.get().getId()); samlConfig = idp.getConfig(); addNew = samlConfig.isAddShadowUserOnLogin(); if (!idp.isActive()) { throw new ProviderNotFoundException( "Identity Provider has been disabled by administrator for alias:" + alias); } } catch (EmptyResultDataAccessException x) { throw new ProviderNotFoundException("No SAML identity provider found in zone for alias:" + alias); } ExpiringUsernameAuthenticationToken result = getExpiringUsernameAuthenticationToken(authentication); UaaPrincipal samlPrincipal = new UaaPrincipal(OriginKeys.NotANumber, result.getName(), result.getName(), alias, result.getName(), zone.getId()); Collection<? extends GrantedAuthority> samlAuthorities = retrieveSamlAuthorities(samlConfig, (SAMLCredential) result.getCredentials()); Collection<? extends GrantedAuthority> authorities = null; SamlIdentityProviderDefinition.ExternalGroupMappingMode groupMappingMode = idp.getConfig() .getGroupMappingMode(); switch (groupMappingMode) { case EXPLICITLY_MAPPED: authorities = mapAuthorities(idp.getOriginKey(), samlAuthorities); break; case AS_SCOPES: authorities = new LinkedList<>(samlAuthorities); break; } Set<String> filteredExternalGroups = filterSamlAuthorities(samlConfig, samlAuthorities); MultiValueMap<String, String> userAttributes = retrieveUserAttributes(samlConfig, (SAMLCredential) result.getCredentials()); UaaUser user = createIfMissing(samlPrincipal, addNew, authorities, userAttributes); UaaPrincipal principal = new UaaPrincipal(user); UaaAuthentication resultUaaAuthentication = new LoginSamlAuthenticationToken(principal, result) .getUaaAuthentication(user.getAuthorities(), filteredExternalGroups, userAttributes); if (samlConfig.isStoreCustomAttributes()) { userDatabase.storeUserInfo(user.getId(), new UserInfo().setUserAttributes(resultUaaAuthentication.getUserAttributes()) .setRoles(new LinkedList(resultUaaAuthentication.getExternalGroups()))); } return resultUaaAuthentication; }
From source file:org.fao.geonet.kernel.security.ecas.ECasAuthenticationProvider.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }//from w w w. java2s.c o m if (authentication instanceof UsernamePasswordAuthenticationToken && (!CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER .equals(authentication.getPrincipal().toString()) && !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER .equals(authentication.getPrincipal().toString()))) { // UsernamePasswordAuthenticationToken not CAS related return null; } // If an existing CasAuthenticationToken, just check we created it if (authentication instanceof CasAuthenticationToken) { if (this.key.hashCode() == ((CasAuthenticationToken) authentication).getKeyHash()) { return authentication; } else { throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.incorrectKey", "The presented CasAuthenticationToken does not contain the expected key")); } } // Ensure credentials are presented if ((authentication.getCredentials() == null) || "".equals(authentication.getCredentials())) { throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.noServiceTicket", "Failed to provide a CAS service ticket to validate")); } boolean stateless = false; if (authentication instanceof UsernamePasswordAuthenticationToken && CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER.equals(authentication.getPrincipal())) { stateless = true; } CasAuthenticationToken result = null; if (stateless) { // Try to obtain from cache result = statelessTicketCache.getByTicketId(authentication.getCredentials().toString()); } if (result == null) { result = this.authenticateNow(authentication); result.setDetails(authentication.getDetails()); } if (stateless) { // Add to cache statelessTicketCache.putTicketInCache(result); } return result; }
From source file:org.opendatakit.common.security.spring.Oauth2AuthenticationProvider.java
public Authentication authenticate(final Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }//from w w w . j a v a2 s . c o m if (authentication instanceof Oauth2AuthenticationToken) { Oauth2AuthenticationToken response = (Oauth2AuthenticationToken) authentication; // Lookup user details UserDetails userDetails = new User(response.getName(), UUID.randomUUID().toString(), true, true, true, true, new ArrayList<GrantedAuthority>()); return createSuccessfulAuthentication(userDetails, response); } return null; }
From source file:org.opendatakit.common.security.spring.OutOfBandAuthenticationProvider.java
public Authentication authenticate(final Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }/*ww w . j a va 2 s . c o m*/ if (authentication instanceof OutOfBandAuthenticationToken) { OutOfBandAuthenticationToken response = (OutOfBandAuthenticationToken) authentication; // Lookup user details UserDetails userDetails = new User(response.getName(), UUID.randomUUID().toString(), true, true, true, true, new ArrayList<GrantedAuthority>()); return createSuccessfulAuthentication(userDetails, response); } return null; }
From source file:org.orcid.api.t2.server.delegator.impl.T2OrcidApiServiceDelegatorImpl.java
/** * Add new external identifiers to the profile. As with all calls, if the * message contains any other elements, a 400 Bad Request will be returned. * /*from w ww . j a v a2s . c o m*/ * @param orcidMessage * the message congtaining the external ids * @return If successful, returns a 200 OK with the updated content. */ @Override @AccessControl(requiredScope = ScopePathType.ORCID_BIO_EXTERNAL_IDENTIFIERS_CREATE) public Response addExternalIdentifiers(UriInfo uriInfo, String orcid, OrcidMessage orcidMessage) { OrcidProfile orcidProfile = orcidMessage.getOrcidProfile(); try { ExternalIdentifiers updatedExternalIdentifiers = orcidProfile.getOrcidBio().getExternalIdentifiers(); // Get the client profile information Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String clientId = null; if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) { OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request(); clientId = authorizationRequest.getClientId(); } for (ExternalIdentifier ei : updatedExternalIdentifiers.getExternalIdentifier()) { // Set the client profile to each external identifier if (ei.getSource() == null) { Source source = new Source(); source.setSourceClientId(new SourceClientId(clientId)); ei.setSource(source); } else { // Check if the provided external orcid exists Source source = ei.getSource(); String sourceOrcid = source.retrieveSourcePath(); if (sourceOrcid != null) { if (StringUtils.isBlank(sourceOrcid) || (!profileEntityManager.orcidExists(sourceOrcid) && !clientDetailsManager.exists(sourceOrcid))) { Map<String, String> params = new HashMap<String, String>(); params.put("orcid", sourceOrcid); throw new OrcidNotFoundException(params); } } } } orcidProfile = orcidProfileManager.addExternalIdentifiers(orcidProfile); return getOrcidMessageResponse(orcidProfile, orcid); } catch (DataAccessException e) { throw new OrcidBadRequestException( localeManager.resolveMessage("apiError.badrequest_createorcid.exception")); } }
From source file:org.orcid.api.t2.server.delegator.impl.T2OrcidApiServiceDelegatorImpl.java
public void setSponsorFromAuthentication(OrcidProfile profile) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (profile.getOrcidHistory() == null) { OrcidHistory orcidHistory = new OrcidHistory(); orcidHistory.setCreationMethod(CreationMethod.API); profile.setOrcidHistory(orcidHistory); }//from w w w . j a va2 s . com profile.getOrcidHistory() .setSubmissionDate(new SubmissionDate(DateUtils.convertToXMLGregorianCalendar(new Date()))); if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) { OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request(); Source sponsor = new Source(); String sponsorId = authorizationRequest.getClientId(); ClientDetailsEntity clientDetails = clientDetailsManager.findByClientId(sponsorId); if (clientDetails != null) { sponsor.setSourceName(new SourceName(clientDetails.getClientName())); if (OrcidStringUtils.isClientId(sponsorId)) { sponsor.setSourceClientId(new SourceClientId(sponsorId)); } else { sponsor.setSourceOrcid(new SourceOrcid(sponsorId)); } } profile.getOrcidHistory().setSource(sponsor); } }
From source file:org.orcid.api.t2.server.delegator.impl.T2OrcidApiServiceDelegatorImpl.java
/** * Register a new webhook to the profile. As with all calls, if the message * contains any other elements, a 400 Bad Request will be returned. * /*w w w . jav a2 s . c o m*/ * @param orcid * the identifier of the profile to add the webhook * @param uriInfo * an uri object containing the webhook * @return If successful, returns a 2xx. * */ @Override @AccessControl(requiredScope = ScopePathType.WEBHOOK) public Response registerWebhook(UriInfo uriInfo, String orcid, String webhookUri) { @SuppressWarnings("unused") URI validatedWebhookUri = null; try { validatedWebhookUri = new URI(webhookUri); } catch (URISyntaxException e) { Object params[] = { webhookUri }; throw new OrcidBadRequestException( localeManager.resolveMessage("apiError.badrequest_incorrect_webhook.exception", params)); } ProfileEntity profile = profileEntityCacheManager.retrieve(orcid); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ClientDetailsEntity clientDetails = null; String clientId = null; if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) { OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request(); clientId = authorizationRequest.getClientId(); clientDetails = clientDetailsManager.findByClientId(clientId); } if (profile != null && clientDetails != null) { WebhookEntityPk webhookPk = new WebhookEntityPk(profile, webhookUri); WebhookEntity webhook = webhookDao.find(webhookPk); boolean isNew = webhook == null; if (isNew) { webhook = new WebhookEntity(); webhook.setProfile(profile); webhook.setDateCreated(new Date()); webhook.setEnabled(true); webhook.setUri(webhookUri); webhook.setClientDetails(clientDetails); } webhookDao.merge(webhook); webhookDao.flush(); return isNew ? Response.created(uriInfo.getAbsolutePath()).build() : Response.noContent().build(); } else if (profile == null) { Map<String, String> params = new HashMap<String, String>(); params.put("orcid", orcid); throw new OrcidNotFoundException(params); } else { Map<String, String> params = new HashMap<String, String>(); params.put("client", clientId); throw new OrcidClientNotFoundException(params); } }