basic-authentication.c (1900B)
1 /* examples/basic-authentication.c */ 2 3 #include <microhttpd2.h> 4 #include <assert.h> 5 6 7 static struct MHD_Action * 8 handle_request (void *cls, 9 struct MHD_Request *request, 10 const struct MHD_String *path, 11 enum MHD_HTTP_Method method, 12 uint_fast64_t upload_size) 13 { 14 union MHD_RequestInfoDynamicData dd; 15 16 if (MHD_SC_OK != 17 MHD_request_get_info_dynamic (request, 18 MHD_REQUEST_INFO_DYNAMIC_AUTH_BASIC_CREDS, 19 &dd)) 20 { 21 struct MHD_Response *r; 22 23 r = MHD_response_from_empty (MHD_HTTP_STATUS_UNAUTHORIZED); 24 if (MHD_SC_OK != 25 MHD_response_add_auth_basic_challenge (r, 26 "test", 27 MHD_YES)) 28 { 29 MHD_response_destroy (r); 30 return MHD_action_abort_request (request); 31 } 32 return MHD_action_from_response (request, 33 r); 34 } 35 fprintf (stderr, 36 "User `%s' has password `%s' (do not log this in real code)\n", 37 dd.v_auth_basic_creds.username.cstr, 38 dd.v_auth_basic_creds.password.cstr); 39 /* You may want to check that username/password are 40 actually OK here, and if not fail similar to 41 the MHD_HTTP_STATUS_UNAUTHORIZED returned above. */ 42 43 /* Success! */ 44 return MHD_action_from_response ( 45 request, 46 MHD_response_from_empty (MHD_HTTP_NO_CONTENT)); 47 } 48 49 50 int 51 main () 52 { 53 struct MHD_Daemon *d; 54 55 /* Create an HTTP server and use "handle_request()" to 56 handle all requests. */ 57 d = MHD_daemon_create (&handle_request, 58 NULL); 59 /* We run with everything on default, so port 80, no TLS */ 60 MHD_daemon_start (d); 61 /* Wait for input on stdin */ 62 (void) getchar (); 63 /* Then just shut everything down */ 64 MHD_daemon_stop (d); 65 return 0; 66 }