簡體   English   中英

ASP.NET Web Api 獲取令牌跨域問題

[英]ASP.NET Web Api trouble with getting token cross-origin

我在使用跨域內容從我的前端(Node.js 和 Ajax)登錄到我的 Web Api 時遇到了一些問題。 我收到以下錯誤:

XMLHttpRequest cannot load http://localhost:61102/Token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500.

只有在嘗試調用/Token登錄時才會出現這個問題,可以訪問其他路由,完美注冊。 這是我的代碼:

啟動.cs:

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

    WebApiConfig.Register(config);
    app.UseCors(CorsOptions.AllowAll);
    app.UseWebApi(config);
}

啟動.Auth.cs:

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(14),
        // In production mode set AllowInsecureHttp = false
        AllowInsecureHttp = true
    };

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

我已經把context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); 進入GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

我已經嘗試尋找答案很長時間了,並且偶然發現了很多不同的答案,這對我不起作用。 不知道出了什么問題。

更新- 添加了我的 ajax 腳本

import {URL} from '../constants/AuthConstants';
import request from 'reqwest';
import history from './HistoryService';

let router = null;

class AuthService {

    login(email, password) {
        console.log(URL.LOGIN);
        var grant_type = 'password';
        return request({
            url: URL.LOGIN,
            method: 'POST',
            crossOrigin: true,
            content-Type
            data: {
                grant_type, email, password
            },
            success: function(response) {
                console.log("Yay! Login", response);
            },
            error: function(response) {
                console.log("Error! Login", response);
            }
        });
    }
}

您使用的 CORS 與我過去使用的略有不同。 我已經多次完成以下操作並取得了相對成功。

在您的 WebApi 項目中添加一個對System.Web.Cors的引用,並將以下內容添加到您的WebApiConfig.cs文件中的Register方法中:

public static void Register(HttpConfiguration config)
{
    config.SetCorsPolicyProviderFactory(new CorsPolicyFactory());
    config.EnableCors();
    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );                     
}

更深入的教程可以在這里找到:

http://tostring.it/2014/03/04/how-to-use-CORS-with-ASPNET-WebAPI-2/

http://enable-cors.org/server_aspnet.html

天哪,我讓它工作了。 不確定它是否好或正確的方法(可能不是,但它有效)。 我所做的是刪除了app.UseCors(CorsOptions.AllowAll); 和所有其他在我的代碼中啟用 cors 的東西,並將其添加到<system.webServer> web.config 中:

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://localhost:8080"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
      </customHeaders>
    </httpProtocol>

我會將其標記為答案,因為它有效,但由於我不確定它是否是解決此問題的正確方法,請告訴我是否正確,我將更改“正確答案”。

編輯- 正確的方法

使用上面的方法我能夠注冊和登錄,但不能執行其他調用,例如“api/values/1”(因為它在發送“GET”或其他東西之前發送了一個“OPTIONS”,我沒有不想為它做一個處理程序)。 我所做的被改回了一些我嘗試過很多次但以前沒有工作過的舊代碼。

我從 Web.config 中刪除了 httpProtocol 東西。

我將 WebApiConfig 更新為:

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

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

在 ApplicationOAuthProvider.cs 的 GrantResourceOwnerCredentials() 中,我將這一行添加到函數的頂部:

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

這是我之前多次嘗試過的一些完全相同的代碼,但這次我不知道是什么讓它起作用。 我登錄了我的電腦,當我回來嘗試時,它突然起作用了。 這里有一些伏都教的東西,但這可能是正確的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM