Token Based Authentication using ASP.NET Web API 2 and Owin throws 401 unauthorized

喜你入骨 提交于 2019-12-12 02:43:37

问题


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();

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/40440117/token-based-authentication-using-asp-net-web-api-2-and-owin-throws-401-unauthori

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!