Verify saml profile request if needed.

@param profileRequest the profile request
@param resolver       the resolver
@param request        the request
@param context        the context
@throws Exception the exception
344806
public void verifySamlProfileRequestIfNeeded(final RequestAbstractType profileRequest,
                                                 final MetadataResolver resolver,
                                                 final HttpServletRequest request,
                                                 final MessageContext context) throws Exception {

        val roleDescriptorResolver = getRoleDescriptorResolver(resolver, context, profileRequest);

        LOGGER.debug("Validating signature for [{}]", profileRequest.getClass().getName());

        val signature = profileRequest.getSignature();
        if (signature != null) {
            validateSignatureOnProfileRequest(profileRequest, signature, roleDescriptorResolver);
        } else {
            validateSignatureOnAuthenticationRequest(profileRequest, request, context, roleDescriptorResolver);
        }
    }
1247347
protected void initializeServices(ProfileRequestContext<?, ?> profileRequestContext) throws ExternalAutenticationErrorCodeException {
    this.authnContextService.initializeContext(profileRequestContext);
    this.signSupportService.initializeContext(profileRequestContext);
  }
1233526
protected String getRelayState(ProfileRequestContext<?, ?> context) {
    SAMLBindingContext samlBinding = this.samlBindingContextLookupStrategy.apply(context);
    return samlBinding != null ? samlBinding.getRelayState() : null;
  }
1180710
public static void setCurrentActionResolver( ActionResolver resolver, HttpServletRequest request,
                                                 ServletContext servletContext )
    {
        StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
        HttpServletRequest unwrappedRequest = PageFlowUtils.unwrapMultipart( request );
        RequestContext rc = new RequestContext( unwrappedRequest, null );
        String currentJpfAttrName =
            ScopedServletUtils.getScopedSessionAttrName( CURRENT_JPF_ATTR, unwrappedRequest );
        String currentLongLivedJpfAttrName =
                ScopedServletUtils.getScopedSessionAttrName( CURRENT_LONGLIVED_ATTR, unwrappedRequest );

        //
        // This case occurs when the previous page flow is no longer active and there is no new page flow
        //
        if ( resolver == null )
        {
            sh.removeAttribute( rc, currentJpfAttrName );
            sh.removeAttribute( rc, currentLongLivedJpfAttrName );
            return;
        }

        //
        // If this is a long-lived page flow, also store the instance in an attribute that never goes away.
        //
        if ( resolver.isPageFlow() && isLongLived( ( ( PageFlowController ) resolver ).theModuleConfig() ) )
        {
            String longLivedAttrName = getLongLivedFlowAttr( resolver.getModulePath() );
            longLivedAttrName = ScopedServletUtils.getScopedSessionAttrName( longLivedAttrName, unwrappedRequest );

            // Only set this attribute if it's not already there.  We want to avoid our onDestroy() callback that's
            // invoked when the page flow's session attribute is unbound.
            if ( sh.getAttribute( rc, longLivedAttrName ) != resolver )
            {
                sh.setAttribute( rc, longLivedAttrName, resolver );
            }

            sh.setAttribute( rc, currentLongLivedJpfAttrName, resolver.getModulePath() );
            sh.removeAttribute( rc, currentJpfAttrName );
        }
        //
        // Default case for removing a previous page flow in the presence of a new page flow.
        //
        else
        {
            sh.setAttribute( rc, currentJpfAttrName, resolver );
            sh.removeAttribute( rc, currentLongLivedJpfAttrName );
        }
    }
1261209
protected final void validateAssertionSignature(final Signature signature, final SAML2MessageContext context,
                                                    final SignatureTrustEngine engine) {

        final SAMLPeerEntityContext peerContext = context.getSAMLPeerEntityContext();

        if (signature != null) {
            final String entityId = peerContext.getEntityId();
            validateSignature(signature, entityId, engine);
        } else {
            if (wantsAssertionsSigned(context) && !peerContext.isAuthenticated()) {
                throw new SAMLSignatureRequiredException("Assertion or response must be signed");
            }
        }
    }
136620
@Override
  public void processRequest(ProfileRequestContext<?, ?> context) throws ExternalAutenticationErrorCodeException {
    final String logId = this.getLogString(context);
    boolean isSignatureService = this.isSignatureServicePeer(context);    

    SignMessageContext signMessageContext = this.getSignMessageContext(context);
    if (signMessageContext == null) {

      // If the peer is a signature service and has only requested a sigmessage LoA we report an error.
      //
      if (isSignatureService) {
        AuthnContextClassContext authnContextClassContext = this.authnContextService.getAuthnContextClassContext(context);
        for (String loa : authnContextClassContext.getAuthnContextClassRefs()) {
          if (this.isSignMessageURI(loa)) {
            log.info("SP has requested '{}' but did not include SignMessage, removing ... [{}]", loa, logId);
            authnContextClassContext.deleteAuthnContextClassRef(loa);
          }
        }
        if (authnContextClassContext.isEmpty()) {
          final String msg = "No valid AuthnContext URI:s were specified in AuthnRequest";
          log.info("{} - can not proceed [{}]", msg, logId);
          throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
        }
      }
    }
    else {
      // If an ordinary SP included a SignMessage in the request, we simply ignore it.
      //
      if (!isSignatureService) {
        log.warn("Requesting SP is not a signature service, but included SignMessage extension, ignoring ... [{}]", logId);
        AuthenticationContext authnContext = this.getAuthenticationContext(context);
        authnContext.removeSubcontext(SignMessageContext.class);
      }
      // Else, make additional checks and decrypt.
      //
      else {

        // Decrypt the message
        //
        if (signMessageContext.getSignMessage().getEncryptedMessage() != null) {
          try {
            Message cleartextMessage = this.signatureSupportKeyService.decrypt(signMessageContext.getSignMessage());
            log.debug("SignMessage was successfully decrypted [{}]", logId);
            signMessageContext.setClearTextMessage(cleartextMessage);
          }
          catch (DecryptionException e) {
            final String msg = String.format("Failed to decrypt SignMessage - %s", e.getMessage());
            log.error("{} [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SIGN_MESSAGE_DECRYPTION_ERROR, msg);
          }
        }
        else {
          log.debug("SignMessage was not encrypted [{}]", logId);
        }

        if (!this.supportsMimeType(signMessageContext.getMimeType())) {
          log.warn("IdP does not support display of SignMessage with type '{}' [{}]", signMessageContext.getMimeType(), logId);
          signMessageContext.setDoDisplayMessage(false);

          if (signMessageContext.mustShow()) {
            throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SIGN_MESSAGE_TYPE_NOT_SUPPORTED,
              "Unsupported SignMessage mime type");
          }
        }
        
        // Process (filter, validate, transform) the sign message.
        //
        if (this.signMessagePreProcessor != null && signMessageContext.getClearTextMessage() != null) {
          try {
            String messageToDisplay = this.signMessagePreProcessor.processSignMessage(signMessageContext.getClearTextMessage(), signMessageContext.getMimeType());
            signMessageContext.setMessageToDisplay(messageToDisplay);
          }
          catch (SignMessageContentException e) {
            log.error("Failed to process sign message: {} [{}]", e.getMessage(), logId);
            
            if (signMessageContext.mustShow()) {
              throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, e.getMessage());
            }
            else {
              signMessageContext.setDoDisplayMessage(false);
            }
          }
        }
        
        // Sanity check - If the clear text message is empty, we can not display anything.
        //
        if (signMessageContext.isDoDisplayMessage() && 
            (signMessageContext.getMessageToDisplay() == null || signMessageContext.getMessageToDisplay().matches("\\s*"))) {
          
          log.warn("Sign message is empty or contains only non-visible characters [{}]", logId);
          signMessageContext.setDoDisplayMessage(false);

          if (signMessageContext.mustShow()) {
            throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, "No sign message to show");
          }
        }
        
        // If the SignMessage element from the signature request includes a MustShow attribute with the value true, the
        // Signature Service MUST require that the provided sign message is displayed by the Identity Provider, by
        // including a sigmessage authentication context URI.
        //
        if (signMessageContext.mustShow()) {
          AuthnContextClassContext authnContextClassContext = this.authnContextService.getAuthnContextClassContext(context);
          for (String loa : authnContextClassContext.getAuthnContextClassRefs()) {
            if (!this.isSignMessageURI(loa)) {
              log.info("SP has requested the SignMessage must be displayed, removing '{}' ... [{}]", loa, logId);
              authnContextClassContext.deleteAuthnContextClassRef(loa);
            }
          }
          if (authnContextClassContext.isEmpty()) {
            final String msg = "No valid sigmessage AuthnContext URI:s were specified in AuthnRequest";
            log.info("{} - can not proceed [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
          }
        }

        // Finally, check that the DisplayEntity matches our IdP entityID.
        //
        if (signMessageContext.getSignMessage().getDisplayEntity() != null) {
          if (!this.entityID.equals(signMessageContext.getSignMessage().getDisplayEntity())) {
            final String msg = String.format("DisplayEntity (%s) of SignMessage does not match IdP entityID (%s)",
              signMessageContext.getSignMessage().getDisplayEntity(), this.entityID);
            log.info("{} - can not proceed [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
          }
        }

        signMessageContext.setDoDisplayMessage(true);
      }
    }

    // Time to check SADRequest ...
    //
    SignatureActivationDataContext sadContext = this.getSadContext(context);
    if (sadContext != null) {

      if (isSignatureService) {
        // If a SADRequest is passed, a SignMessage must also be present.
        //
        if (signMessageContext == null) {
          final String msg = "Request contained SADRequest but no SignMessage was received - not allowed";
          log.info("{} - can not proceed [{}]", msg, logId);
          throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SWEID_BAD_REQUEST, msg);
        }
        else if (!signMessageContext.isDoDisplayMessage()) {
          // If we cannot display the SignMessage we can not issue a SAD ...
          final String msg = "SignMessage can not be displayed and SAD is requested";
          log.info("{} - can not proceed [{}]", msg, logId);
          throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SWEID_BAD_REQUEST, msg);
        }
        else {
          // Verify the SAD request ...
          //
          this.verifySadRequest(sadContext, context);
        }
      }
      else {
        log.warn("Requesting SP is not a signature service, but included SAPRequest extension in request, ignoring ... [{}]", logId);
        AuthenticationContext authnContext = this.getAuthenticationContext(context);
        authnContext.removeSubcontext(SignatureActivationDataContext.class);
      }
    }

  }
991713
@GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_POST_SIMPLE_SIGN)
    protected void handleSaml2ProfileSsoRedirectRequest(final HttpServletResponse response,
                                                        final HttpServletRequest request) throws Exception {
        val decoder = getSamlProfileHandlerConfigurationContext().getSamlMessageDecoders().getInstance(HttpMethod.GET);
        handleSsoPostProfileRequest(response, request, decoder);
    }
248135
protected Principal getAccessTokenAuthenticationPrincipal(final AccessToken accessToken, final J2EContext context, final RegisteredService registeredService) {
        val currentPrincipal = accessToken.getAuthentication().getPrincipal();
        LOGGER.debug("Preparing user profile response based on CAS principal [{}]", currentPrincipal);

        val principal = this.scopeToAttributesFilter.filter(accessToken.getService(), currentPrincipal, registeredService, context, accessToken);
        LOGGER.debug("Created CAS principal [{}] based on requested/authorized scopes", principal);

        return principal;
    }
25893
protected CommonProfile getAuthenticatedProfile(final HttpServletRequest request,
                                                    final HttpServletResponse response,
                                                    final String requiredPermission) {
        val context = new J2EContext(request, response, getUmaConfigurationContext().getSessionStore());
        val manager = new ProfileManager<>(context, context.getSessionStore());
        val profile = manager.get(true).orElse(null);
        if (profile == null) {
            throw new AuthenticationException("Unable to locate authenticated profile");
        }
        if (!profile.getPermissions().contains(requiredPermission)) {
            throw new AuthenticationException("Authenticated profile does not carry the UMA protection scope");
        }
        return profile;
    }
230157
@SneakyThrows
    public static SamlRegisteredService newSamlServiceProviderService(final AbstractSamlSPProperties sp,
                                                                      final SamlRegisteredServiceCachingMetadataResolver resolver) {
        if (StringUtils.isBlank(sp.getMetadata())) {
            LOGGER.debug("Skipped registration of [{}] since no metadata location is found", sp.getName());
            return null;
        }

        val service = new SamlRegisteredService();
        service.setName(sp.getName());
        service.setDescription(sp.getDescription());
        service.setEvaluationOrder(Ordered.HIGHEST_PRECEDENCE);
        service.setMetadataLocation(sp.getMetadata());
        val attributesToRelease = new ArrayList<String>(sp.getAttributes());
        if (StringUtils.isNotBlank(sp.getNameIdAttribute())) {
            attributesToRelease.add(sp.getNameIdAttribute());
            service.setUsernameAttributeProvider(new PrincipalAttributeRegisteredServiceUsernameProvider(sp.getNameIdAttribute()));
        }
        if (StringUtils.isNotBlank(sp.getNameIdFormat())) {
            service.setRequiredNameIdFormat(sp.getNameIdFormat());
        }

        val attributes = CoreAuthenticationUtils.transformPrincipalAttributesListIntoMultiMap(attributesToRelease);
        val policy = new ChainingAttributeReleasePolicy();
        policy.addPolicy(new ReturnMappedAttributeReleasePolicy(CollectionUtils.wrap(attributes)));
        service.setAttributeReleasePolicy(policy);

        service.setMetadataCriteriaRoles(SPSSODescriptor.DEFAULT_ELEMENT_NAME.getLocalPart());
        service.setMetadataCriteriaRemoveEmptyEntitiesDescriptors(true);
        service.setMetadataCriteriaRemoveRolelessEntityDescriptors(true);

        if (StringUtils.isNotBlank(sp.getSignatureLocation())) {
            service.setMetadataSignatureLocation(sp.getSignatureLocation());
        }

        val entityIDList = determineEntityIdList(sp, resolver, service);

        if (entityIDList.isEmpty()) {
            LOGGER.warn("Skipped registration of [{}] since no metadata entity ids could be found", sp.getName());
            return null;
        }
        val entityIds = org.springframework.util.StringUtils.collectionToDelimitedString(entityIDList, "|");
        service.setMetadataCriteriaDirection(PredicateFilter.Direction.INCLUDE.name());
        service.setMetadataCriteriaPattern(entityIds);

        LOGGER.debug("Registering saml service [{}] by entity id [{}]", sp.getName(), entityIds);
        service.setServiceId(entityIds);

        service.setSignAssertions(sp.isSignAssertions());
        service.setSignResponses(sp.isSignResponses());

        return service;
    }
649571
protected Set<Event> resolveMultifactorProviderViaPredicate(final Optional<RequestContext> context,
                                                                final RegisteredService service,
                                                                final Principal principal,
                                                                final Collection<MultifactorAuthenticationProvider> providers) {
        val attributeNames = commaDelimitedListToSet(casProperties.getAuthn().getMfa().getGlobalPrincipalAttributeNameTriggers());
        return multifactorAuthenticationProviderResolver.resolveEventViaPrincipalAttribute(principal, attributeNames, service, context, providers,
            input -> providers.stream().anyMatch(provider -> input != null && provider.matches(input)));
    }
852102
protected void addAuthnContextClassContext(ProfileRequestContext<?, ?> context, AuthnContextClassContext authnContextClassContext)
      throws ExternalAutenticationErrorCodeException {
    AuthenticationContext authnContext = authenticationContextLookupStrategy.apply(context);
    if (authnContext == null) {
      log.error("No AuthenticationContext available [{}]", this.getLogString(context));
      throw new ExternalAutenticationErrorCodeException(AuthnEventIds.INVALID_AUTHN_CTX, "Missing AuthenticationContext");
    }
    authnContext.addSubcontext(authnContextClassContext, true);
  }
630719
public void loadProfile(Object key)
    {
        if (!isEnablePerThreadChanges())
        {
            throw new MetadataException("Can not load profile with disabled per thread mode");
        }
        DescriptorRepository rep = (DescriptorRepository) metadataProfiles.get(key);
        if (rep == null)
        {
            throw new MetadataException("Can not find profile for key '" + key + "'");
        }
        currentProfileKey.set(key);
        setDescriptor(rep);
    }
1355616
protected CommonProfile getAuthenticatedProfile(final HttpServletRequest request, final HttpServletResponse response) {
        val context = new J2EContext(request, response, getConfigurationContext().getSessionStore());
        val manager = new ProfileManager<>(context, context.getSessionStore());
        val profile = manager.get(true);

        if (profile.isEmpty()) {
            throw new IllegalArgumentException("Unable to determine the user profile from the context");
        }
        return profile.get();
    }
965422
def profile(request):
    '''
        
    '''
    context = {}

    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            messages.info(request, 'Password Changed.')
    else:
        form = PasswordChangeForm(request.user)

    key = Key.objects.get(email=request.user.email)
    
    #analytics
    endpoint_q = key.reports.values('api__name', 'endpoint').annotate(calls=Sum('calls')).order_by('-calls')
    endpoints = [{'endpoint':'.'.join((d['api__name'], d['endpoint'])),
                  'calls': d['calls']} for d in endpoint_q]
    date_q = key.reports.values('date').annotate(calls=Sum('calls')).order_by('date')
    context['endpoints'], context['endpoint_calls'] = _dictlist_to_lists(endpoints, 'endpoint', 'calls')
    context['timeline'] = date_q

    context['form'] = form
    context['key'] = key
    context['password_is_key'] = request.user.check_password(key.key)
    return render_to_response('locksmith/profile.html', context,
                              context_instance=RequestContext(request))
405081
protected <T extends SAMLObject> void prepareSecurityParametersContext(final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                                                           final MessageContext<T> outboundContext,
                                                                           final SamlRegisteredService service) {
        val secParametersContext = outboundContext.getSubcontext(SecurityParametersContext.class, true);
        val roleDesc = adaptor.getSsoDescriptor();
        val signingParameters = buildSignatureSigningParameters(roleDesc, service);
        secParametersContext.setSignatureSigningParameters(signingParameters);
    }
327000
public static Optional<SamlRegisteredServiceServiceProviderMetadataFacade> get(final SamlRegisteredServiceCachingMetadataResolver resolver,
                                                                                   final SamlRegisteredService registeredService,
                                                                                   final String entityID) {
        return get(resolver, registeredService, entityID, new CriteriaSet());
    }