MVC Web-API - token based authentication

M

Miss

I am writing to seek help, as to create a token based authentication. I am little unsure, how the token is created for each user? Is the token string generated when the user logs in or initially all the users should have a token value stored with them in the database.

Is it possible to pass the token using Delegating Handler?

-------------------------------------------------------------------------
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
AuthenticationHeaderValue authValue = request.Headers.Authorization;

if (authValue == null || authValue.Scheme != BasicAuthResponseHeaderValue)
{
return Unauthorized(request);
}

string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authValue.Parameter)).Split(new[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
{
//return Unauthorized(request);
var resp = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent(string.Format("access denied")),
};
}

api_login user = repository.Validate2(credentials[0], credentials[1]);
if (user == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent(string.Format("access denied")),
};
return Unauthorized(request);
}
else
{
var roles = repository.GetRolesForUser(user.username);
IPrincipal principal = new GenericPrincipal(new GenericIdentity(user.username, BasicAuthResponseHeaderValue), roles);
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
}

return base.SendAsync(request, cancellationToken);

}
 
A

Arne Vajhøj

I am writing to seek help, as to create a token based authentication. I am little unsure, how the token is created for each user? Is the token string generated when the user logs in or initially all the users should have a token value stored with them in the database.

Is it possible to pass the token using Delegating Handler?

-------------------------------------------------------------------------
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
AuthenticationHeaderValue authValue = request.Headers.Authorization;

if (authValue == null || authValue.Scheme != BasicAuthResponseHeaderValue)
{
return Unauthorized(request);
}

string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authValue.Parameter)).Split(new[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
{
//return Unauthorized(request);
var resp = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent(string.Format("access denied")),
};
}

api_login user = repository.Validate2(credentials[0], credentials[1]);
if (user == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent(string.Format("access denied")),
};
return Unauthorized(request);
}
else
{
var roles = repository.GetRolesForUser(user.username);
IPrincipal principal = new GenericPrincipal(new GenericIdentity(user.username, BasicAuthResponseHeaderValue), roles);
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
}

return base.SendAsync(request, cancellationToken);

}

What are you trying to accomplish?

The code seems to be using Basic HTTP authentication. Which is a very
old but still valid mechanism.

But then you talk about token. Token is not the same as Basic HTTP
authentication.

And there are no particular rules on how to generate tokens except that
they need to be hard to guess, so secure random number generator is
often used as part of the solution.

Arne
 
M

Miss

Thank you for your reply. Apology for the late response.
I would like to be able to create a token-based authentication for my web api.

I am ware of the token built-in function from the 'owin' packages. I created the following code in MVC4 (VS2012), using this site as reference (http://www.saifikram.com/2014/06/token-based-authentication-using-asp-net-web-api-2-with-owin).
When I call a GET request (api/values), I get a authorized error on the client.

here is my startup class:
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);

WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}


public void ConfigureOAuth(IAppBuilder app)
{
// Configure the application for OAuth based flow
var oAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"), //Path of the authorization server
Provider = new SimpleAuthorizationServerProvider(),

AuthorizeEndpointPath = new PathString("http://localhost:62635/api/values"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(5),
AllowInsecureHttp = false, //HTTPS is allowed only
ApplicationCanDisplayErrors = true,
};

// Token Generation
app.UseOAuthAuthorizationServer(oAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

}

This is my Values API controller:
[RoutePrefix("api/values")]
[Authorize]
public class ValuesController : ApiController
{
public IHttpActionResult Get()
{
ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
var userName = principal.Claims.Where(c => c.Type == "admin").Single().Value;
return Ok("You are allowed to request data");
}

The "OAuthAuthorizationServerProvider", on my web api application is the same as the reference link.

Do I need to setup a interface class to get the authenicaion window. Any further advice, as to where I may be going wrong would be most appreciated.

Thank you for your time and help.
 
Top