Reputation: 33998
I have an angular APP with .net CORE web API, where the first request is against a /token service, however I get this error about CORS, but apparently I already have it enabled, what am I missing?
:8088/#/home:1 XMLHttpRequest cannot load http://example.com:90/api/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com:8088' is therefore not allowed access.
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();
}
}
}
In my angular APP, i have this:
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');
}
}
}
The web API token authentication was built as shown in the link below, I wont paste their entire code:
https://stormpath.com/blog/token-authentication-asp-net-core
Upvotes: 0
Views: 839
Reputation: 146
In this part of code, you are trying add the configure cors after put the app variable into ConfigureAuth like parameter. Then, you should configure first the CORS and then pass the variable app into ConfigureAuth.
You can see in the code below:
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);
}
Upvotes: 1
Reputation: 612
you specify app.UseCors("AllowAllHeader"); but your policy name is "AllowAllHeaders"
if you remove that line, your call to app.UseCors("AllowAllOrigins"); should handle everything (since you specify AllowAnyHeader() in the "AllowAllOrigins" policy
Upvotes: 1