我有一個帶.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
你真棒 –