Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

cors denied error in asp.net core

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Pomelo.EntityFrameworkCore.MySql;
using System.Threading.Tasks;
using ctsapi.Services;
using Jose;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using ctsapi.Models;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Http;
using System.Net;
 
namespace ctsapi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
 
        public IConfiguration Configuration { get; }
 
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins", builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyMethod();
                    builder.AllowAnyHeader();
                });
            });
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "ctsapi", Version = "v1" });
                //c.IncludeXmlComments(XmlCommentsPath.XmlCommentsFilePath);
            });
 
            var jwtSection = Configuration.GetSection("JWTSettings");
            services.Configure<JWTSettings>(jwtSection);
 
            //to validate the token which has been sent by clients
            var appSettings = jwtSection.Get<JWTSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);
 
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                .AddJwtBearer(x =>
                {
                    x.RequireHttpsMetadata = true;
                    x.SaveToken = true;
                    x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });
 
            services.AddAuthorization(options =>
            {
                options.AddPolicy(Policies.Admin, Policies.AdminPolicy());
                options.AddPolicy(Policies.ShopKeeper, Policies.ShopKeeperPolicy());
                options.AddPolicy(Policies.User, Policies.UserPolicy());
            });
        }
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles(); // dodanie wwwroot
            //if (env.IsDevelopment())
            //{
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ctsapi v1"));
            //}
 
            app.UseHttpsRedirection();
 
            app.UseRouting();
 
            app.Use(async (context, next) =>
            {
                await next();
 
                if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
                {
                    // "Token Validation Has Failed. Request Access Denied"
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(new ErrorDto()
                    {
                        StatusCode = 401,
                        Message = "Token Validation Has Failed. Request Access Denied"
                    }.ToString());
                }
            });
 
            app.UseCors("AllowAllOrigins");
 
            app.UseAuthorization();
 
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
Comment

cors denied error in asp.net core

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Pomelo.EntityFrameworkCore.MySql;
using System.Threading.Tasks;
using ctsapi.Services;
using Jose;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using ctsapi.Models;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Http;
using System.Net;
 


namespace ctsapi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
 
        public IConfiguration Configuration { get; }
 
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins", builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyMethod();
                    builder.AllowAnyHeader();
                });
            });
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "ctsapi", Version = "v1" });
                //c.IncludeXmlComments(XmlCommentsPath.XmlCommentsFilePath);
            });
 
            var jwtSection = Configuration.GetSection("JWTSettings");
            services.Configure<JWTSettings>(jwtSection);
 
            //to validate the token which has been sent by clients
            var appSettings = jwtSection.Get<JWTSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);
 
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                .AddJwtBearer(x =>
                {
                    x.RequireHttpsMetadata = true;
                    x.SaveToken = true;
                    x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });
 
            services.AddAuthorization(options =>
            {
                options.AddPolicy(Policies.Admin, Policies.AdminPolicy());
                options.AddPolicy(Policies.ShopKeeper, Policies.ShopKeeperPolicy());
                options.AddPolicy(Policies.User, Policies.UserPolicy());
            });
        }
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles(); // dodanie wwwroot
            //if (env.IsDevelopment())
            //{
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ctsapi v1"));
            //}
 
            app.UseHttpsRedirection();
 
            app.UseRouting();
 
            app.Use(async (context, next) =>
            {
                await next();
 
                if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
                {
                    // "Token Validation Has Failed. Request Access Denied"
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(new ErrorDto()
                    {
                        StatusCode = 401,
                        Message = "Token Validation Has Failed. Request Access Denied"
                    }.ToString());
                }
            });
 
            app.UseCors("AllowAllOrigins");
 
            app.UseAuthorization();
 
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: fluent api c# hasmany withmany 
Csharp :: c# registrykey is null 
Csharp :: use string[] args c# 
Csharp :: f# print array strings 
Csharp :: c# break file into words 
Csharp :: asserting exceptions c# 
Csharp :: c# print expression tree 
Csharp :: print all string in textbox in array c# 
Csharp :: datagridview mouse click event c# 
Csharp :: C# resize window without title bar 
Csharp :: gegenstände bewegen c# 
Csharp :: c# task call more web api in parallel 
Csharp :: c# read csv file save to database dynamically 
Csharp :: c# how to return 2 strings 
Csharp :: system.collections.generic.list 1 system.int32 c# 
Csharp :: Process.Start(osk.exe) 
Csharp :: closedxm Iworksheet excel formulal 
Csharp :: how to do multiplication with button c# 
Csharp :: single or default in c# 
Csharp :: c# order by descending on 2 values 
Csharp :: c# gridview summary item displayformat 
Csharp :: snakes and ladder single player c# 
Csharp :: c# cosmos db add items into container 
Csharp :: C# Fibonacci list 
Csharp :: Handling aggregation responses with NEST c# 
Csharp :: button commandfield commandargument pass textbox 
Csharp :: netmath hack console 
Csharp :: sqlsinifi.baglanti.open() 
Csharp :: c# async rethrow exception 
Csharp :: gridview column cell alignment form c# 
ADD CONTENT
Topic
Content
Source link
Name
2+9 =