2017-04-04 159 views
0

我有一個帶.net CORE的web API的角度APP,其中第一個請求是針對/ token服務的,但是我得到這個關於CORS的錯誤,但顯然我已經啓用它,我錯過了什麼?XMLHttpRequest無法加載沒有「訪問控制 - 允許來源」>標題出現在所請求的資源上

:8088 /#/ home:1 XMLHttpRequest無法加載 http://example.com:90/api/token。沒有'Access-Control-Allow-Origin' 標題出現在請求的資源上。原因 'http://example.com:8088'因此不允許訪問。

 public partial class Startup 
    { 
     public Startup(IHostingEnvironment env) 
     { 
      var builder = new ConfigurationBuilder() 
       .SetBasePath(env.ContentRootPath) 
       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
       .AddEnvironmentVariables(); 
      Configuration = builder.Build(); 

     } 

     public IConfigurationRoot Configuration { get; } 

     // This method gets called by the runtime. Use this method to add services to the container. 
     public void ConfigureServices(IServiceCollection services) 
     { 
      var corsBuilder = new CorsPolicyBuilder(); 
      corsBuilder.AllowAnyHeader(); 
      corsBuilder.AllowAnyMethod(); 
      corsBuilder.AllowAnyOrigin(); // For anyone access. 
      //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end! 
      corsBuilder.AllowCredentials(); 

      services.AddCors(options => 
      { 
       options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); 
      }); 
      // Add framework services. 
      services.AddMvc() 
        .AddJsonOptions(a => a.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); ; 



      //using Dependency Injection 
      services.AddSingleton<IEcommerceRepository, EcommerceRepository>(); 
      //services.AddSingleton<ITodoTerrenoRepository, TodoTerrenoRepository>(); 

      services.AddDbContext<EcommerContext>(options => 
      options.UseSqlServer(Configuration.GetConnectionString("AuthentConnection"))); 
      services.AddDbContext<TODOTERRENOContext>(options => 
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 


      services.Configure<IISOptions>(options => 
      { 

       options.AutomaticAuthentication = true; 
       options.ForwardClientCertificate = true; 
       options.ForwardWindowsAuthentication = true; 


      }); 


     } 

     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
     { 
      loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
      loggerFactory.AddDebug(); 
      if (env.IsDevelopment()) 
      { 
       app.UseDeveloperExceptionPage(); 
      } 
      else 
      { 
       app.UseExceptionHandler("/Home/Error"); 
      } 

      ConfigureAuth(app); 

      app.UseCors("SiteCorsPolicy"); 
      app.UseMvc(); 


     } 
    } 
} 

在我的角度APP,我有這個:

LoggingService.js

angular 
     .module('common.services') 
     .factory('loginservice', ['$http', 'appSettings', loginservice]); 

     function loginservice($http, appSettings) { 

      this.login = function() { 
       var resp = $http({ 
        url: appSettings.serverPath + 'token', 
        method: 'POST', 
        data: $.param({grant_type: 'password', username: appSettings.username, password: appSettings.password }), 

        headers: { 
         'Content-Type': 'application/x-www-form-urlencoded' } 
       }); 
       return resp; 
      }; 
      return { login: this.login } 
     } 

LoginController.js 

app.controller('logincontroller', ['$scope', 'loginservice', 'userProfile', '$rootScope', logincontroller]); 

function logincontroller($scope, loginservice, userProfile, $rootScope) { 
     $scope.title = 'logincontroller'; 

     $scope.IniciarLogin = function() { 

      var loginResult = loginservice.login(); 

      loginResult.then(function (resp) { 

       userProfile.setProfile(resp.data.userName, resp.data.access_token, resp.data.refresh_token); 
      }, function (response) { 

       alert("error"); 
      }); 

     } 


     $scope.logout = function() { 
      sessionStorage.removeItem('accessToken'); 
      if (sessionStorage.getItem('userSessionName') != null){ 
       sessionStorage.removeItem('userSessionName'); 
      } 
     } 
    } 

的網絡API令牌認證始建如下圖所示的鏈接,我不會自己貼整個代碼:

https://stormpath.com/blog/token-authentication-asp-net-core

回答

1

在這部分代碼中,您嘗試在將應用變量放入ConfigureAuth參數後添加configure cors,然後, CORS然後傳遞變量的應用打造成爲ConfigureAuth

您可以在下面的代碼中看到:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 
     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 
     else 
     { 
      app.UseExceptionHandler("/Home/Error"); 
     } 
     app.UseCors("SiteCorsPolicy"); 
     app.UseMvc(); 

     ConfigureAuth(app);   


    } 
+0

你真棒 –

1

你指定app.UseCors(「AllowAllHeader」);但是您的策略名稱爲「AllowAllHeaders」

如果您刪除該行,則調用app.UseCors(「AllowAllOrigins」);應該處理所有事情(因爲您在「AllowAllOrigins」策略中指定了AllowAnyHeader()

+0

我很抱歉,我抄錯startup.cs,請參閱編輯,我認爲它是正確的,但它可能有不同的錯誤 –

+0

我看不出新版本有什麼問題......如果你嘗試改變你的在ConfigureServices()中調用services.AddCors();然後在Configure()中調用app.UseCors(builder => builder.AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin() ); –

相關問題