Skip to content

Instantly share code, notes, and snippets.

@fisshy
Created February 21, 2015 19:49
Show Gist options
  • Save fisshy/996d1468201c3a7047a9 to your computer and use it in GitHub Desktop.
Save fisshy/996d1468201c3a7047a9 to your computer and use it in GitHub Desktop.
JWT Token ASP.NET
public partial class Startup
{
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
#if DEBUG
AllowInsecureHttp = true,
#else
AllowInsecureHttp = false,
#endif
TokenEndpointPath = new PathString("/api/auth"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider(),
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
//Logger.ReportInformation("Auth", string.Join(" | ", context.Request.Headers.Select(a => string.Format("{0} -> {1}", a.Key, a.Value))));
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var _repo = new AuthRepository();
var user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("user", user.UserId.ToString()));
context.Validated(identity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment