OAuth Server
Creating an Authorization Server
The standard examples are facebook/ google etc, or you use an in-house authorization server (eg IdentityServer or ADFS 4). You can have a custom OAuth server within your project/solution using Microsoft.Owin.Security.OAuth. Based on asp.net overview
Nuget packages
- Microsoft.Owin.Host.SystemWeb (Katana)
- Microsoft.Owin.Security.OAuth (brings in Owin dependencies)
- Microsoft.AspNet.WebApi.Owin (to run WebApi in Owin)
Startup
public class Startup
{
public void Configuration(IAppBuilder app)
{
//serve tokens
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
#if DEBUG
AllowInsecureHttp = true, //NOT IN PROD
#endif
//redirect uri
AuthorizeEndpointPath = new PathString("/Authorize"),
//token uri
TokenEndpointPath = new PathString("/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(7),
//work with the events
Provider = new MyOAuthAuthorizationServerProvider()
});
//use tokens
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
//webapi
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config); //Microsoft.AspNet.WebApi.Owin
}
}
OAuthAuthorizationServerProvider
Or just supply delegates to OAuthAuthorizationServerProvider.
public class MyOAuthAuthorizationServerProvider
: OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
//validate the client is registered (from Basic Auth or form encoded)
string clientId;
string clientSecret;
if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
context.TryGetFormCredentials(out clientId, out clientSecret))
{
Console.WriteLine(clientId);
if (clientId == "1" && clientSecret == "secret")
{
context.Validated();
}
}
return Task.FromResult(0);
}
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
if (context.UserName != "alice" && context.Password != "secret")
{
context.Rejected();
return Task.FromResult(0);
}
//password grant
var identity = new ClaimsIdentity(
//username, "Bearer"
new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType),
context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
context.Validated(identity);
return Task.FromResult(0);