Skip to content

Instantly share code, notes, and snippets.

@danbarua
Created February 18, 2015 11:59
Show Gist options
  • Save danbarua/e8facf23002802eeec64 to your computer and use it in GitHub Desktop.
Save danbarua/e8facf23002802eeec64 to your computer and use it in GitHub Desktop.
Use TeamCity credentials to auth with NuGet.Server
public class Global : System.Web.HttpApplication
{
private readonly string connectionString = ConfigurationManager.ConnectionStrings["teamCity"].ConnectionString;
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
//check if requesting the web service - this is the only page
//that should accept Basic Authentication
HttpApplication app = (HttpApplication)sender;
if (app.Context.Request.Headers.Get("X-NUGET-APIKEY") != null)
{
return;
}
if (app.Context.Request.Path.StartsWith("/nuget"))
{
if (HttpContext.Current.User == null)
{
Console.WriteLine("Null user - use basic auth");
var ctx = HttpContext.Current;
var authenticated = false;
// look for authorization header
var authHeader = ctx.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic"))
{
// extract credentials from header
var credentials = this.extractCredentials(authHeader);
if (this.ValidateUser(credentials[0], credentials[1]))
{
var id = new GenericIdentity(credentials[0], "CustomBasic");
var p = new GenericPrincipal(id, null);
ctx.User = p;
authenticated = true;
}
}
// emit the authenticate header to trigger client authentication
if (authenticated == false)
{
ctx.Response.StatusCode = 401;
ctx.Response.AddHeader(
"WWW-Authenticate", string.Format("Basic realm=\"{0}\"", app.Context.Request.Url.Host));
ctx.Response.Flush();
ctx.Response.Close();
}
}
}
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
private bool ValidateUser(string username, string password)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = @"
SELECT COUNT(*) FROM users AS u
WHERE LOWER(u.username) = LOWER(@userName)
AND u.password = LOWER(SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('md5',@password)),3,32))";
cmd.Parameters.AddWithValue("@userName", username);
cmd.Parameters.Add(new SqlParameter("@password", SqlDbType.VarChar) { Value = password });
return (int)cmd.ExecuteScalar() > 0;
}
}
}
private string[] extractCredentials(string authHeader)
{
// strip out the "basic"
string encodedUserPass = authHeader.Substring(6).Trim();
// that's the right encoding
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass));
int separator = userPass.IndexOf(':');
string[] credentials = new string[2];
credentials[0] = userPass.Substring(0, separator);
credentials[1] = userPass.Substring(separator + 1);
return credentials;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment