c# - Web API Basic authentication always unauthorized -


i have web api 1 user, i'm trying use basic authentication protect returns code 401 unauthorized.

this code:

class basicauthenticationattribute

using system; using system.threading; using system.security.principal; using system.text; using system.web.http.controllers; using system.web.http.filters; using system.net; using system.net.http;  public class basicauthenticationattribute: authorizationfilterattribute {    public override void onauthorization(httpactioncontext actioncontext) {     if (actioncontext.request.headers.authorization == null)     {         actioncontext.response = actioncontext.request.createresponse(httpstatuscode.unauthorized);     }     else     {         // gets header parameters           string authenticationstring = actioncontext.request.headers.authorization.parameter;         string originalstring = encoding.utf8.getstring(convert.frombase64string(authenticationstring));          // gets username , password           string usrename = originalstring.split(':')[0];         string password = originalstring.split(':')[1];          // validate username , password           if (!checkuser.login(usrename, password))         {             // returns unauthorized error               actioncontext.response = actioncontext.request.createresponse(httpstatuscode.unauthorized);         }     }      base.onauthorization(actioncontext); } } 

class checkuser

using system;  public class checkuser { public static bool login(string username, string password) {     if (username == "user" && password == "mypassword")         return true;     else         return false; } } 

the api controller

public class addusercontroller : apicontroller {     [httpget, basicauthentication]     [route("api/user/{email}")]     public string adduser(string email)     {         string country_code = "";          string username = system.threading.thread.currentprincipal.identity.name;          return "welcome"; } 

this jquery function:

var token = ''; var headers = {}; if (token) { headers.authorization = 'basic ywhdzwqer5whtzwramjaxnw=='; }  $.ajax({ type: 'get', url: 'http://mywebapi.com', headers: headers }).done(function (data) { self.result(data); }) 

i don't know wrong code!! please help

thank in advance

you create empty token, set headers if token not empty, never set headers...

var token = ''; var headers = {}; if (token) {     headers.authorization = 'basic ywhdzwqer5whtzwramjaxnw=='; } 

try

if (!token) { 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -