Skip to content

Instantly share code, notes, and snippets.

@fquintanilla
Last active May 20, 2020 15:48
Show Gist options
  • Select an option

  • Save fquintanilla/d20aa178ba98256347cb7ce18c48d40f to your computer and use it in GitHub Desktop.

Select an option

Save fquintanilla/d20aa178ba98256347cb7ce18c48d40f to your computer and use it in GitHub Desktop.
public class CustomAuthorizationProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var credentialsAreValid = System.Web.Security.Membership.ValidateUser(context.UserName, context.Password);
if (!credentialsAreValid)
{
context.SetError("invalid_grant", "Incorrect credentials, unable to grant a token");
return;
}
var username = context.UserName;
var roles = System.Web.Security.Roles.GetRolesForUser(username);
if (!roles.Any() || !roles.Contains("WebAdmins"))
{
context.SetError("invalid_grant", "Invalid user or missing required permissions.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, username));
identity.AddClaim(new Claim(ClaimTypes.Role, "WebAdmins"));
context.Validated(identity);
}
}
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void Configuration(IAppBuilder app)
{
var OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = ConfigurationHelper.Instance.GetAppSetting("TokenAllowInsecureHttp", false)
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
}
<add key="owin:AutomaticAppStartup" value="true" />
@fquintanilla
Copy link
Copy Markdown
Author

image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment