How to use basic-auth - 10 common examples

To help you get started, we’ve selected a few basic-auth examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github the-control-group / authx / src / strategies / secret.js View on Github external
var request;


		// HTTP POST (json)
		if (ctx.method === 'POST' && ctx.is('application/json'))
			request = await json(ctx.req);


		// HTTP POST (form)
		else if (ctx.method === 'POST' && ctx.is('application/x-www-form-urlencoded'))
			request = await form(ctx.req);


		// HTTP Basic Authentication
		else {
			let basic = auth(ctx.req);
			if (basic)
				request = {
					user_id: basic.name,
					secret: basic.pass
				};
		}


		// send authenticate headers
		if (!request) {
			ctx.set('WWW-Authenticate', 'Basic realm="' + ctx[x].authx.config.realm + '"');
			ctx.throw(401, 'HTTP Basic credentials are required.');
		}


		// get the user ID
github coralproject / talk / src / core / server / app / middleware / basicAuth.ts View on Github external
return (req, res, next) => {
    // Pull the credentials out of the request.
    const credentials = auth(req);

    // Check credentials
    if (credentials && check(credentials.name, credentials.pass)) {
      return next();
    }

    res.setHeader("WWW-Authenticate", `Basic realm="${req.originalUrl}"`);
    res.status(401).send("Access denied");
  };
};
github shesek / spark-wallet / src / auth.js View on Github external
if (req.url == '/redir') return res.type('text/html').end('')

    // Authenticate using the access key token, via the X-Access header or using access-key on the body/query.
    // This also marks the request as csrfSafe. Used for RPC API calls and for SSE requests.
    if ((req.get('X-Access') || req.query['access-key'] || req.body['access-key']) === accessKey) {
      req.csrfSafe = true
      return next()
    }

    // Authenticate with HMAC-signed cookies
    if (req.signedCookies.user) {
      return next()
    }

    // HTTP basic authentication (username/password)
    const cred = basicAuth(req)
    if (cred && cred.name === username && cred.pass === password) {
      // Once the user authenticates with basic auth, set a signed cookie to authenticate future requests.
      // HTTP basic auth is quirky, this makes for a smoother experience.
      res.cookie('user', username, cookieOpt)
      return next()
    }

    res.set('WWW-Authenticate', 'Basic realm="Private Area"')
       .sendStatus(401)
  }
}
github chriswiggins / rtsp-streaming-server / src / lib / ClientServer.ts View on Github external
// Ask for authentication
    if (this.hooks.authentication) {
      if (!req.headers.authorization) {
        debug('%s:%s - No authentication information (required), sending 401', req.socket.remoteAddress, req.socket.remotePort);
        res.setHeader('WWW-Authenticate', 'Basic realm="rtsp"');
        res.statusCode = 401;
        return false;
      } else {
        if (req.headers.session && this.clients[req.headers.session] && this.clients[req.headers.session].authorizationHeader !== req.headers.authorization) {
          debug('%s:%s - session header doesn\'t match the cached value, sending 401', req.socket.remoteAddress, req.socket.remotePort);
          res.setHeader('WWW-Authenticate', 'Basic realm="rtsp"');
          res.statusCode = 401;
          return false;
        }

        const result = parse(req.headers.authorization);
        if (!result) {
          debug('%s:%s - No authentication information (required), sending 401', req.socket.remoteAddress, req.socket.remotePort);
          res.setHeader('WWW-Authenticate', 'Basic realm="rtsp"');
          res.statusCode = 401;
          return false;
        }

        const allowed = await this.hooks.authentication(result.name, result.pass, req, res);
        if (!allowed) {
          debug('%s:%s - No authentication information (hook returned false), sending 401', req.socket.remoteAddress, req.socket.remotePort);
          res.setHeader('WWW-Authenticate', 'Basic realm="rtsp"');
          res.statusCode = 401;
          return false;
        }
      }
    }
github replicatedhq / kots / kotsadm / api / src / controllers / kots / RestoreAPI.ts View on Github external
async putUndeployResult(
    @Req() request: Express.Request,
    @Res() response: Express.Response,
    @HeaderParams("Authorization") auth: string,
    @BodyParams("") body: any,
  ): Promise {
    const credentials: BasicAuth.Credentials = BasicAuth.parse(auth);

    let cluster;
    try {
      cluster = await (request.app.locals.stores.clusterStore as ClusterStore).getFromDeployToken(credentials.pass);
    } catch (err) {
      // TODO error type
      response.status(401);
      return {};
    }

    const status = body.is_error ? UndeployStatus.Failed : UndeployStatus.Completed;
    logger.info(`Restore API set RestoreUndeployStatus = ${status} for app ${body.app_id}`);
    const kotsAppStore = request.app.locals.stores.kotsAppStore as KotsAppStore;
    const app = await kotsAppStore.getApp(body.app_id);
    if (app.restoreInProgressName) {
      // Add a delay until we have logic to wait for all pods to be deleted.
github chriswiggins / rtsp-streaming-server / src / lib / PublishServer.ts View on Github external
async announceRequest (req: RtspRequest, res: RtspResponse) {
    debug('%s:%s - Announce request with headers %o', req.socket.remoteAddress, req.socket.remotePort, req.headers);
    // Ask for authentication
    if (this.hooks.authentication) {
      if (!req.headers.authorization) {
        debug('%s:%s - No authentication information (required), sending 401', req.socket.remoteAddress, req.socket.remotePort);
        res.setHeader('WWW-Authenticate', 'Basic realm="rtsp"');
        res.statusCode = 401;
        return res.end();
      } else {
        const result = parse(req.headers.authorization);
        if (!result) {
          debug('%s:%s - Invalid authentication information (required), sending 401', req.socket.remoteAddress, req.socket.remotePort);
          res.setHeader('WWW-Authenticate', 'Basic realm="rtsp"');
          res.statusCode = 401;
          return res.end();
        }

        const allowed = await this.hooks.authentication(result.name, result.pass, req, res);
        if (!allowed) {
          debug('%s:%s - Invalid authentication information (Hook returned false), sending 401', req.socket.remoteAddress, req.socket.remotePort);
          res.setHeader('WWW-Authenticate', 'Basic realm="rtsp"');
          res.statusCode = 401;
          return res.end();
        }

        this.authenticatedHeader = req.headers.authorization;
github replicatedhq / kots / kotsadm / api / src / controllers / kots / DeployAPI.ts View on Github external
async putDeployResult(
    @Req() request: Express.Request,
    @Res() response: Express.Response,
    @HeaderParams("Authorization") auth: string,
    @BodyParams("") body: any,
  ): Promise {
    const credentials: BasicAuth.Credentials = BasicAuth.parse(auth);

    let cluster;
    try {
      cluster = await request.app.locals.stores.clusterStore.getFromDeployToken(credentials.pass);
    } catch (err) {
      // TODO error type
      response.status(401);
      return {};
    }

    const output = {
      dryRun: {
        stderr: body.dryrun_stderr,
        stdout: body.dryrun_stdout,
      },
      apply: {
github replicatedhq / kots / kotsadm / api / src / controllers / kots / AppStatusAPI.ts View on Github external
async putAppStatus(
    @Req() request: Express.Request,
    @Res() response: Express.Response,
    @HeaderParams("Authorization") auth: string,
    @BodyParams("") body: any,
  ): Promise {
    const credentials: BasicAuth.Credentials = BasicAuth.parse(auth);

    try {
      await request.app.locals.stores.clusterStore.getFromDeployToken(credentials.pass);
    } catch (err) {
      // TODO error type
      response.status(401);
      return;
    }

    const kotsAppStatusStore: KotsAppStatusStore = request.app.locals.stores.kotsAppStatusStore;
    await kotsAppStatusStore.setKotsAppStatus(body.app_id, body.resource_states, body.updated_at);
    response.status(204);
  }
}
github replicatedhq / kots / kotsadm / api / src / controllers / kots / DeployAPI.ts View on Github external
async getDesiredState(
    @Req() request: Express.Request,
    @Res() response: Express.Response,
    @HeaderParams("Authorization") auth: string,
  ): Promise {
    const credentials: BasicAuth.Credentials = BasicAuth.parse(auth);

    let cluster;
    try {
      cluster = await request.app.locals.stores.clusterStore.getFromDeployToken(credentials.pass);
    } catch (err) {
      // TODO error type
      response.status(401);
      return {};
    }

    try {
      const apps = await request.app.locals.stores.kotsAppStore.listAppsForCluster(cluster.id);

      const present: any[] = [];
      const missing = {};
      let preflight = [];
github node-red / node-red / test / nodes / core / io / 21-httprequest_spec.js View on Github external
testProxyServer.on('proxyRes', function (proxyRes, req, res, options) {
                if (req.url == getTestURL('/proxyAuthenticate')){
                    var user = auth.parse(req.headers['proxy-authorization']);
                    if (!(user.name == "foouser" && user.pass == "barpassword")){
                        proxyRes.headers['proxy-authenticate'] = 'BASIC realm="test"';
                        proxyRes.statusCode = 407;
                    }
                }
            });
            testProxyServer.listen(testProxyPort);

basic-auth

node.js basic auth parser

MIT
Latest version published 6 years ago

Package Health Score

74 / 100
Full package analysis