Basic authentication (ISAPI filter)

Here is a simple example using an ISAPI filter to perform basic authentication. It is written in C.

/*
 * Authenticate users
 *
 * This ISAPI filter performs basic authentication.
 * Before every HTTP request is served, it checks for username/password
 * information and sends a '401 Permission Denied' response if the
 * information provided is incorrect.
 *
 */

/* Include ISAPI definitions and constants */
#include <httpfilt.h>
#include <string.h>

#define USERNAME "fred"
#define PASSWORD "bloggs"
#define DOMAIN   "Members Area"

/* This function is called when the filter is loaded by the web server */
BOOL WINAPI
GetFilterVersion( HTTP_FILTER_VERSION *pVer )
{
  /*  Set the filter version */
  pVer->dwFilterVersion = HTTP_FILTER_REVISION;

  /*  Set a description string for this filter */
  strncpy(pVer->lpszFilterDesc, "Basic Authentication Filter", SF_MAX_FILTER_DESC_LEN);

  /*  Ask to be notified at the authentication stage of every HTTP request */
  pVer->dwFlags = SF_NOTIFY_SECURE_PORT |
    SF_NOTIFY_NONSECURE_PORT |
    SF_NOTIFY_AUTHENTICATION;

  return TRUE;
}

/*  Ask the client to authenticate by sending a 401 response */
static void
Denied( PHTTP_FILTER_CONTEXT pfc, char *msg )
{
  char domain[256];
  int l = strlen( msg );
  /*  Set up string to include name of domain */
  sprintf(domain, "WWW-Authenticate: Basic realm=\"%s\"\r\n", DOMAIN);
  /*  Send a 401 header */
  pfc->ServerSupportFunction( pfc, SF_REQ_SEND_RESPONSE_HEADER,
			      (PVOID)   "401 Permission Denied",
			      (LPDWORD) domain,
			      0 );
  /*  Explain why authentication failed */
  pfc->WriteClient( pfc, msg, &l, 0 );
}

/*  This function is called for every HTTP request */
DWORD WINAPI
HttpFilterProc( PHTTP_FILTER_CONTEXT pfc,
		DWORD notificationType,
		VOID *pvNotification )
{
  HTTP_FILTER_AUTHENT *auth = (HTTP_FILTER_AUTHENT *) pvNotification;

  if( auth->pszUser[0] == 0) {
    /*  No authentication information was given */
    Denied( pfc, "No user/password given" );
    /*  This is the end of this HTTP request */
    return SF_STATUS_REQ_FINISHED;
  }
        
  if( strcmp( auth->pszUser, USERNAME ) ) {
    /*  Username is wrong */
    Denied( pfc, "Unknown user" );
    return SF_STATUS_REQ_FINISHED;
  }
        
  if( strcmp( auth->pszPassword, PASSWORD ) ) {
    /*  Password is wrong */
    Denied( pfc, "Wrong password" );
    return SF_STATUS_REQ_FINISHED;
  }

  /*  Continue with this request */
  return SF_STATUS_REQ_NEXT_NOTIFICATION;
}
Content Manager [Administrator] 16 December 2005  Permalink  
Download Free Trial

Recent Articles

Other Resources



www.zeus.com