I have create a OAuth Authentication using the guide from Taiseer Joudeh. I have created an endpoint /token to make the authentication. It works and I receive a result like this.
{
"access_token": "dhBvPjsHUoIs6k8NDsXfROpTq63qlww_7Bifl0LOzIxhZnngld0QCU-x4q4Qa7xWhhIQeQbbK6gYu_hLIYfUbsFMsdXwqlOqAYabJHNNsnJPMMHNADb-KCQznPQy7-waaqKMCVH1HPqx4L30sXlX0L8MbjtrtkX9-jxHaWdPapqYA9lU4Ai2-Z5-zXxoriFDL-SvxrUnBTDQMnRxOH_oEyclUngzW-is543TtJ0bysQ",
"token_type": "bearer",
"expires_in": 86399
}
But if I use the access token in my header of the next call of a enpoint that has the AuthorizeAttribute I alwayse recive a Unauthorized error. Also if I take a look in what is in the CurrentPrincipal of the current Thread it's always a GenericPrincipal.
My Startup class looks like this (looks similar to that in the guide)
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
IContainer container = AutoFacConfig.Register(config, app);
ConfigureOAuth(app, container);
WebApiConfig.Register(config);
AutoMapperConfig.Register();
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app, IContainer container)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = container.Resolve<IOAuthAuthorizationServerProvider>()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
And the OauthServiceprovider is like this:
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
private readonly IUserBl userBl;
public SimpleAuthorizationServerProvider(IUserBl userBl)
{
this.userBl = userBl;
}
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[] { "*" });
UserDto user = Mapper.Map<UserDto>(userBl.Login(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("role", "user"));
context.Validated(identity);
}
}
The only difference is that I'm using the version 3 of owin and not 2 like the guide. Are there some breaking changes that broken my code?
EDIT 1:
I'am using Autofac to resolve the Interface IOAuthAuthorizationServerProvider:
builder.RegisterType<SimpleAuthorizationServerProvider>()
.As<IOAuthAuthorizationServerProvider>()
.PropertiesAutowired()
.SingleInstance();