Owin身份令牌认证令牌端点以404响应

时间:2017-05-27 15:35:37

标签: c# asp.net authentication asp.net-identity restful-authentication

我一直在尝试使用OWIN和asp.net身份和实体框架向我的应用程序添加基于令牌的授权。但是,当我尝试通过令牌端点路径获取令牌时,我得到404响应。我的OWIN启动课程:

[assembly: OwinStartup(typeof(Web.Startup))]

namespace Web
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureOAuth(app);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            Console.WriteLine("owin");
            app.CreatePerOwinContext<OwinAuthDbContext>(() => new OwinAuthDbContext());
            app.CreatePerOwinContext<UserManager<IdentityUser>>(CreateManager);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var provider = new MyAuthorizationServerProvider();
            OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = false, //have also tried with true here
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = provider
            };
            app.UseOAuthAuthorizationServer(option);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }

        private static UserManager<IdentityUser> CreateManager(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context)
        {
            var userStore = new UserStore<IdentityUser>(context.Get<OwinAuthDbContext>());
            var owinManager = new UserManager<IdentityUser>(userStore);
            return owinManager;
        }
    }
}

正如您所看到的,令牌应该在&#34; / token&#34;下可用,但是当我拨打https://localhost:44373/token时,无论是否为用户名,密码和token_type添加标头,我都会得到404。我的OAuthAuthorizationServerProvider类:

public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        string clientId;
        string clientSecret;

        if (context.TryGetBasicCredentials(out clientId, out clientSecret))
        {
            // validate the client Id and secret against database or from configuration file.  
            context.Validated();
        }
        else
        {
            context.SetError("invalid_client", "Client credentials could not be retrieved from the Authorization header");
            context.Rejected();
        }
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        UserManager<IdentityUser> userManager = context.OwinContext.GetUserManager<UserManager<IdentityUser>>();
        IdentityUser user;
        try
        {
            user = await userManager.FindAsync(context.UserName, context.Password);
        }
        catch
        {
            // Could not retrieve the user due to error.  
            context.SetError("server_error");
            context.Rejected();
            return;
        }
        if (user != null)
        {
            ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                                                    user,
                                                    DefaultAuthenticationTypes.ExternalBearer);
            context.Validated(identity);
        }
        else
        {
            context.SetError("invalid_grant", "Invalid User Id or password'");
            context.Rejected();
        }
    }
}

我希望你能提供帮助。

修改

web.config依赖程序集:

<dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="4.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>

3 个答案:

答案 0 :(得分:0)

请确保您身体中也传递 grant_type:密码并使用POST发送至http://localhost:XXXXX/token

  • 用户名:userXX
  • 密码:XXXX
  • grant_type:密码

ps:我发现你错过了配置功能中的app.UseWebApi(config);?请确保在ConfigureOAuth(app);

之后调用它

示例:

public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();   
            ConfigureOAuth(app);    
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }

答案 1 :(得分:0)

请尝试这种方式:

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();
    ConfigureOAuth(app);

    WebApiConfig.Register(config);
    app.UseWebApi(config);
}

private void ConfigureOAuth(IAppBuilder app)
{
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/oauth/Token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
        Provider = new AuthorizationServerProvider()
    };

    //Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

AuthorizationServerProvider.cs

public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();

        return base.ValidateClientAuthentication(context);
    }

    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        //Add parameters to token
        ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
        oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

        context.Validated(oAuthIdentity);

        return base.GrantResourceOwnerCredentials(context);
    }
}

答案 2 :(得分:0)

您的启动类无法访问,请尝试将Web.config中的AutomaticAppStartup的值更改为true,如下所示:

<configuration>
  <appSettings>
.
.
    <add key="owin:AutomaticAppStartup" value="true" />
  <appSettings>
.
.
<configuration>