Tom
Tom

Reputation: 139

Getting urname / password from http url

Is it possible to get the username / password in asp.net (mvc3) from a http url where it is formated like this?

http://user:[email protected]/path

or is it only possible with the ftp protocol?

Upvotes: 0

Views: 718

Answers (1)

doublesharp
doublesharp

Reputation: 27637

The username and password in your example are using HTTP Basic Authentication - they aren't part of the URL but rather included in the header information. You can access this info in ASP.NET, see this article: Basic Authentication with Asp.Net WebAPI

public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute {
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) {
        if (actionContext.Request.Headers.Authorization == null){
            // No Header Auth Info
            actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        } else {
            // Get the auth token
            string authToken = actionContext.Request.Headers.Authorization.Parameter;
            // Decode the token from BASE64
            string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));

            // Extract username and password from decoded token
            string username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
            string password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);
        }
    }
}

Upvotes: 2

Related Questions