HttpRequestBase request = actionContext.HttpContext.Request;
string userName = "";
string password = "";
bool authorized = false;
String basicAuthorizationHeaderEncoded = request.Headers.Get("Authorization");
if (!String.IsNullOrEmpty(basicAuthorizationHeaderEncoded))
{
basicAuthorizationHeaderEncoded = basicAuthorizationHeaderEncoded.Split(' ')[1];
String basicAuthorizationHeaderDecoded = String.Empty.FromBase64(basicAuthorizationHeaderEncoded);
String[] authorizationHeaderValues = basicAuthorizationHeaderDecoded.Split(new char[] { ':' });
if (authorizationHeaderValues.Count() == 2)
{
userName = authorizationHeaderValues.First();
password = authorizationHeaderValues.Last();
}
}
else
{
var userInfo = request.Url.UserInfo;
if (!String.IsNullOrWhiteSpace(userInfo))
{
var parts = userInfo.Split(':');
userName = parts[0] ?? "";
password = parts[1] ?? "";
}
}
if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password))
{
var webpartServiceUserName = Config.DynamicWebservice.GetSection().Settings["WebpartServiceUserName"].Value;
var webpartServicePassword = Config.DynamicWebservice.GetSection().Settings["WebpartServicePassword"].Value;
if (userName == webpartServiceUserName && password == webpartServicePassword)
{
authorized = true;
}
}
if (!authorized)
{
HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true;
HttpContext.Current.Response.StatusCode = 401;
HttpContext.Current.Response.Headers.Add("WWW-Authenticate", String.Empty);
HttpContext.Current.Response.Buffer = false; // Disable buffer and flush output to prevent forms authentication redirect
HttpContext.Current.Response.BufferOutput = false;
HttpContext.Current.Response.Write("Not authorized");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.OutputStream.Flush();
HttpContext.Current.Response.End();
throw new Exception("Not authorized");
}
68800cookie-checkC# Basic Authentication