0

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();
Community
  • 1
  • 1
cpiock
  • 1,275
  • 2
  • 17
  • 44

2 Answers2

0

FOA, You do not seem to be using the SimpleAuthorizationServerProvider class in your ConfigureOAuth() method.

So, please change the code to be like :

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() {

            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider(),
        };

And then please comment what happens.

Jose Francis
  • 950
  • 13
  • 28
  • I use Autofac to resolve the interface IOAuthAuthorizationServerProvider and create a instance of SimpleAuthorizationServerProvider. – cpiock Nov 08 '16 at 13:09
  • @cpiock I'm using the same OWIN version in the repo, can you try to disable AutoFac and try to run the application without any DI, then if it is good you need troubleshoot what is going with the AutoFac. – Taiseer Joudeh Nov 11 '16 at 21:37
  • @TaiseerJoudeh hmm. removing all Autofac things is a pain. But the user creation ecc. looks like working. Should not some of the methods in the SimpleAuthorizationServerProvider hit if I call a endpoint after calling my token endpoint? – cpiock Nov 17 '16 at 21:24
  • @TaiseerJoudeh now i added a custom autorization attribute and I see that the actionContext.RequestContext.Principal is always null. In the context I see that the heade with the bearer token arrives in the post. Di you think that is always a problem of autofac? – cpiock Nov 29 '16 at 20:04
0

This answer solves my problem https://stackoverflow.com/a/36769653/5441093

Change in the GrantResourceOwnerCredentials method this to resolve my userbl class:

var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
var userBl = autofacLifetimeScope.Resolve<IUserBl>();

instead of using the injection of autofac Thanks to @taiseer joudeh for the hint to look at Autofac

Community
  • 1
  • 1
cpiock
  • 1,275
  • 2
  • 17
  • 44