WebApi未经授权(401)进行制作

时间:2017-01-07 16:28:32

标签: asp.net-mvc asp.net-web-api oauth

我已经看到了有关WebApi 401未授权问题的几个问题和一些答案。我仍然无法弄清楚为什么一切都在当地环境中运作良好;但是上述错误发生在生产上。

我发布了大部分代码逻辑,因此有人可以解释问题出在哪里以及解决方案是什么。而且,请尽量准确,清晰。所有答案 - 包括这一个:Owin Bearer Token Not Working for WebApi - 对我来说仍然不清楚。

正如您将在下面注意到的那样,我只使用提供的模板,没有太大的变化。

所以,这里是Global.asax.cs中的常用条目:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

以下是Startup.cs:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
}

这是Startup.Auth.cs文件:

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static string PublicClientId { get; private set; }

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"), 
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = bool.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Oauth_AllowInsecureHttp"))
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);

        //****************** GOOGLE AUTHENTICATION *******************************************************
        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Oauth_Google:ClientID"),
            ClientSecret = System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Oauth_Google:ClientSecret")

        });
    }
}

最后,WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Elmah logging...
        config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());

        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    }
}

如前所述,一切都在当地运作良好。 401(授权)问题仅在部署在远程服务器上时才会发生。我们已经与邮差测试过,但仍然没有运气。响应标头显示: - 服务器→Microsoft-IIS / 8.5; - WWW-Authenticate→Bearer,Negotiate,NTLM

所以,当然,“授权:Bearer SomeTokenBlablablab”应该可以工作....

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

最后,我在查看了我的CORS配置后解决了这个问题(代码未包含在上面的帖子中)!