Signs a request.

@param {AuthInterface} auth
@param {Request} request
@param {AuthHandlerInterface~authSignHookCallback} done
14944
function (auth, request, done) {
        var params = auth.get([
                'consumerKey',
                'consumerSecret',
                'token',
                'tokenSecret',
                'signatureMethod',
                'timestamp',
                'nonce',
                'version',
                'realm',
                'addParamsToHeader',
                'addEmptyParamsToSign'
            ]),
            url = urlEncoder.toNodeUrl(request.url.toString(true)),
            signatureParams,
            header;

        if (!params.consumerKey || !params.consumerSecret) {
            return done(); // Nothing to do if required parameters are not present.
        }

        // Remove existing headers and params (if any)
        request.removeHeader('Authorization');
        request.removeQueryParams(_.values(OAUTH1_PARAMS));
        request.body && request.body.urlencoded && request.body.urlencoded.remove(function (param) {
            return _.includes(_.values(OAUTH1_PARAMS), param.key);
        });

        // Generate a new nonce and timestamp
        params.nonce = params.nonce || oAuth1.nonce(11).toString();
        params.timestamp = params.timestamp || oAuth1.timestamp().toString();

        // Ensure that empty parameters are not added to the signature
        if (!params.addEmptyParamsToSign) {
            params = _.reduce(params, function (accumulator, value, key) {
                if (_.isString(value) && (value.trim() === EMPTY)) {
                    return accumulator;
                }
                accumulator[key] = value;

                return accumulator;
            }, {});
        }

        // Generate a list of parameters associated with the signature.
        signatureParams = this.computeHeader({
            url: getOAuth1BaseUrl(url),
            method: request.method,
            queryParams: request.url.query && request.url.query.count() ? request.url.query.map(function (qParam) {
                return {
                    key: qParam.key,
                    value: qParam.value
                };
            }) : [],

            // todo: WTF! figure out a better way
            // Body params only need to be included if they are URL encoded.
            // http://oauth.net/core/1.0a/#anchor13
            bodyParams: (request.body &&
                request.body.mode === RequestBody.MODES.urlencoded &&
                request.body.urlencoded &&
                request.body.urlencoded.count &&
                request.body.urlencoded.count()) ? request.body.urlencoded.map(function (formParam) {
                    return {
                        key: formParam.key,
                        value: formParam.value
                    };
                }) : [],
            helperParams: params
        });

        // The OAuth specification says that we should add parameters in the following order of preference:
        // 1. Auth Header
        // 2. Body parameters
        // 3. Query parameters
        //
        // http://oauth.net/core/1.0/#consumer_req_param
        if (params.addParamsToHeader) {
            header = oAuth1.getAuthorizationHeader(params.realm, _.map(signatureParams, function (param) {
                return [param.key, param.value];
            }));
            request.addHeader({
                key: 'Authorization',
                value: header,
                system: true
            });
        }
        else if ((/PUT|POST/).test(request.method) &&
                (request.body && request.body.mode === RequestBody.MODES.urlencoded)) {
            _.forEach(signatureParams, function (param) {
                request.body.urlencoded.add(param);
            });
        }
        else {
            request.addQueryParams(signatureParams);
        }

        return done();
    }
869199
def process_request(self, req, resp):  # pylint: disable=unused-argument
        

        try:
            creds = self._get_creds(req)
            self.auth_creds(*creds)
        except (AuthRejected, AuthRequired, InvalidAuthSyntax) as exc:
            exc.headers = self._error_headers
            if not self.optional:
                abort(exc)
123201
function RequestSigner(request, credentials) {

  if (typeof request === 'string') request = url.parse(request)

  var headers = request.headers = (request.headers || {}),
      hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)

  this.request = request
  this.credentials = credentials || this.defaultCredentials()

  this.service = request.service || hostParts[0] || ''
  this.region = request.region || hostParts[1] || 'us-east-1'

  // SES uses a different domain from the service name
  if (this.service === 'email') this.service = 'ses'

  if (!request.method && request.body)
    request.method = 'POST'

  if (!headers.Host && !headers.host) {
    headers.Host = request.hostname || request.host || this.createHost()

    // If a port is specified explicitly, use it as is
    if (request.port)
      headers.Host += ':' + request.port
  }
  if (!request.hostname && !request.host)
    request.hostname = headers.Host || headers.host

  this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
}
480930
function cmd_auth(args, done) {
    var seneca = this
    var userent = seneca.make(user_canon)
    var loginent = seneca.make(login_canon)

    var q = { id: args.token }

    loginent.load$(q, function(err, login) {
      if (err) return done(err)

      if (!login) {
        return done(null, {
          ok: false,
          token: args.token,
          why: 'login-not-found'
        })
      }

      if (!login.active) {
        return done(null, {
          ok: false,
          token: args.token,
          why: 'login-inactive'
        })
      }

      userent.load$({ id: login.user }, function(err, user) {
        if (err) return done(err)

        if (!user) {
          return done(null, {
            ok: false,
            token: args.token,
            user: login.user,
            why: 'user-not-found'
          })
        }

        done(null, { user: user, login: login, ok: true })
      })
    })
  }
1243496
@SneakyThrows
    protected Http signHttpUserPreAuthRequest(final Http request) {
        request.signRequest(
            duoProperties.getDuoIntegrationKey(),
            duoProperties.getDuoSecretKey());
        return request;
    }
511645
function done(req, next, err, obj) {
    if (err) {
        req.error = {error: err.error || err.message};
    } else {
        req.provider = obj;
    }
    next();
}
142884
def auth_request_handler(self, callback):
        
        warnings.warn("This handler is deprecated. The recommended approach to have control over "
                      "the authentication resource is to disable the built-in  resource by "
                      "setting JWT_AUTH_URL_RULE=None and registering your own authentication "
                      "resource directly on your application.", DeprecationWarning, stacklevel=2)
        self.auth_request_callback = callback
        return callback
571816
def _on_auth(self, sock, authenticated):  # pylint: disable=unused-argument
        """"""
        def ack(eventname, error, data):  # pylint: disable=unused-argument
            """Ack"""
            if error:
                self.log.error(f"""OnAuth: {error}""")
            else:
                self.connect_channels(self.channels)
                self.post_conn_cb()

        sock.emitack("auth", self.creds, ack)
595799
function authorised(request) {
	// JWT is usually passed via an HTTP header
    let token = request.headers.authorization;
    
    // For EventSource and WebSocket, JWT is passed as a URL parameter
    if (token === undefined) {
    	let url = URL.parse(request.url, true);
    	
    	if (url.query)
    		token = url.query.jwt;
    }
    
    // ask app to validate JWT authorisation token
    return (!token || config.validateJWT(token, request.url));
}
121448
def sign(uri, headers, credentials):
    
    consumer_key, token_key, token_secret = credentials
    auth = OAuthSigner(token_key, token_secret, consumer_key, "")
    auth.sign_request(uri, method="GET", body=None, headers=headers)
1022686
function createAuthDetails( request ) {
   var auth= { scopedUsers: {} };
   request._connect_auth= auth;
   if( request.session ) {
     request.session.auth= auth;
   }
 }
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);
      }
    }

  }
429111
function onSignUp() {
  var email = $('#signup-email').val();
  var password = $('#signup-password').val();
  auth.createUserWithEmailAndPassword(email, password)
      .then(onAuthUserCredentialSuccess, onAuthError);
}
1294839
function(request, username, password, callback) {
    const user = users[username];
    if (!user) {
        return callback(null, false);
    }
    const isValid = password === user.password;
    callback(null, isValid, { id: user.id, name: user.name });
}
878914
def onAuthenticate(self, signature, extra):
        
        log.msg("onAuthenticate: {} {}".format(signature, extra))

        ## if there is a pending auth, and the signature provided by client matches ..
        if self._pending_auth:

            if signature == self._pending_auth.signature:

                ## accept the client
                return types.Accept(authid = self._pending_auth.uid,
                    authrole = self._pending_auth.authrole,
                    authmethod = self._pending_auth.authmethod,
                    authprovider = self._pending_auth.authprovider)
            else:

                ## deny client
                return types.Deny(message = u"signature is invalid")
        else:

            ## deny client
            return types.Deny(message = u"no pending authentication")
1187510
function postAuthLogout(req, res) {
    if (authMaintenance.usingSessions) {
      req.logout();
    }
    res.status(200).send('Ok');
  }
1352988
function InvalidSignature(reason) {
  Error.captureStackTrace(this, this.constructor);
  this.type = 'unauthorized';
  this.statusCode = 401;
  this.message = 'Invalid request signature';
  this.reason = reason;
}