.NET 5 API add Access-Control-Allow-Origin headers - with Ionic 5.5 - asp.net-core

Can you please assist, I have a .NET 5 Web API and Ionic 5.5 app. I have deployed the API and the Ionic app to Azure Web Services. The API is serving the Ionic app, so they are on the same domain - I can say same origin because the scheme, and domain are the same.
The issue is that, the Ionic app is failing to call the API because it seems like CORS is blocking it.
In my API, I have allowed any origin, any header and credentials but it's still not working. I have attached my Startup.cs file for the .NET 5 API.
Startup.cs code
using AutoMapper;
using EventManager.Business.Repositories;
using EventManager.Database;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Reflection;
namespace EventManager.Api
{
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.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
//options.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
services.AddControllers();
services.AddApiVersioning(x =>
{
x.DefaultApiVersion = new ApiVersion(2, 1);
x.AssumeDefaultVersionWhenUnspecified = true;
x.ReportApiVersions = true;
// Supporting multiple versioning scheme
x.ApiVersionReader = new UrlSegmentApiVersionReader();
});
services.AddVersionedApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = false;
});
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new Business.MappingProfile());
});
var mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Event Manager API Documentation",
Version = "v1",
Contact = new OpenApiContact
{
Email = "eric#xxxxx.com",
Name = "Eric Smith",
Url = new Uri("https://www.xxxxx.org/")
},
Description = #"Used for as a self-service for event attendees.
To capture attendee details and print out attendee badges",
License = new OpenApiLicense
{
Name = "Use under LICX",
Url = new Uri("https://www.xxxxx.org/api/license"),
}
});
//Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
services.AddDbContext<AppDbContext>(x => x.UseSqlServer(Configuration.GetConnectionString("MSSqlConnection"),
b => b.MigrationsAssembly("EventManager.Database")));
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<EventRepository>();
services.AddScoped<AttendeeRepository>();
services.AddScoped<DesignationRepository>();
services.AddScoped<EntryQuestionRepository>();
services.AddScoped<EntryQuestionSectionRepository>();
//Sart: To serve angular app
services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp"; });
//End: To serve angular app
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "EventManager.Api v1"));
}
app.UseRouting();
app.UseCors(builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
app.UseAuthorization();
//Start: To serve angular app
app.UseDefaultFiles();
app.UseSpaStaticFiles();
//End: To serve angular app
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//Start: To serve angular app
app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; });
//End: To serve angular app
}
}
}
My API call from the Ionic app
headers = new HttpHeaders({
"Authorization": "Bearer " + "XXXXXXX",
"Content-Type": "application/json"
});
//environment.api = 'https://myazureappname.azurewebsites.net/api/'
get(cellNumber?: string): Observable<AttendeeGetModel[]> {
return this._http.get<AttendeeGetModel[]>(`${environment.api}v1/attendees?cellNumber=${cellNumber}`, { headers: this.headers });
}
**Error message from Firefox browser attached**
[![enter image description here][1]][1]

The error ERR_NAME_NOT RESOLVED typically means: Chrome cannot resolve the domain name which in most cases means you're using the wrong domain name or have a typo.
In your case it looks like your're using the wrong top level domain in your app. Postman = ".net", Your app = ".com".

Related

swagger not working with gRPC .net core 7

I followed the steps this documentation https://learn.microsoft.com/en-us/aspnet/core/grpc/json-transcoding-openapi?view=aspnetcore-7.0 and integrated google protos.
I tried to open it locally and adding /swagger/index.html
and I am getting
An HTTP/1.x request was sent to an HTTP/2 only endpoint.
Program.cs:
using Extensions;
using Google.Api;
using gRPCserver.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.OpenApi.Models;
using Models.Models;
using Serilog;
using Serilog.Sinks.Kafka;
using sKashCallCenterAPI.Interface;
using sKashCallCenterAPI.Service;
var builder = WebApplication.CreateBuilder(args);
var ConnectionString = builder.Configuration["sqlconnection:ConnectionString"];
builder.Services.AddDbContext<sKashDbContext>(options =>
{
options.UseSqlServer(ConnectionString);
});
//builder.Services.AddGrpc();
builder.Services.AddGrpcSwagger();
builder.Services.AddGrpcHttpApi();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo { Title = "gRPC Server", Version = "v1" });
var filePath = Path.Combine(System.AppContext.BaseDirectory, "gRPCserver.xml");
c.IncludeXmlComments(filePath);
c.IncludeGrpcXmlComments(filePath, includeControllerXmlComments: true);
});
ConfigurationManager configuration = builder.Configuration;
var kafkaServer = configuration["KafkaConfig:ServerIP"] + ":" + configuration["KafkaConfig:Port"];
builder.Host.UseSerilog((ctx, lc) => lc
.WriteTo.Console()
.WriteTo.Kafka(topic: configuration["KafkaConfig:Topic"], bootstrapServers: kafkaServer)
.Enrich.WithProperty("Source", configuration["KafkaConfig:Source"])
.ReadFrom.Configuration(ctx.Configuration));
builder.Services.ConfigurJWTAuthentication();
builder.Services.ConfigureRepositoryWrapper();
builder.Services.ConfigureContractsServices();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IMemoryCache, MemoryCache>();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
// Configure the HTTP request pipeline.
//app.MapGrpcService<GreeterService>();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
});
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
app.Run();
The project is running but no swagger documentation is shown.
Assuming you're debugging using Kestrel, did you configure its protocol support for both HTTP1 and HTTP2 in appsettings or the startup pipeline?
{
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http1AndHttp2"
}
}
}
Yes, you are right. The swagger documentation will not show up as default. You will have to use a plugin as grpc-gateway. This is a reverse-proxy server which translates a RESTful HTTP API into gRPC, by reading protobuf service definitions.

cors error in authentication type windows - visual studio 2019

I started a .NET CORE 5 project
And I chose windows type authentication
type authentication image
And this type of project gives me a CORS error on the client side (react)
But if instead of windows I choose none, I won't get an error
This is the call from the client side:
const res = await fetch(`https://localhost:44373/weatherforecast`)
I need this type of project because I want to use AD authentication
I tried adding it to the fetch call:
const res = await fetch(`https://localhost:44300/weatherforecast`,{credentials: 'include'})
and change the STARTUP:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication3
{
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.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("MyMyAllowCredentialsPolicy",
policy =>
{
policy.WithOrigins("https://localhost:44300")
.AllowCredentials();
});
});
}
// This method gets called by the runtime. Use this method to
configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseCors();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I also created a new .net 6 web api project with windows authentication. I also had a front end project.
This is my code and it worked for me. In my Program.cs, I added Cors policy and others are generated by default.
using Microsoft.AspNetCore.Authentication.Negotiate;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("mypolicy",
policy =>
{
policy.WithOrigins("http://localhost:8848").AllowCredentials();
//.AllowCredentials();
});
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors("mypolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
And I used ajax to send the request, missing withCredentials will lead to 401 error:
$("#btn2").click(function(event) {
$.ajax({
url: "https://localhost:7272/WeatherForecast",
type: "get",
xhrFields: {
withCredentials: true
},
success: function(data) {
alert(data);
console.info(data);
}
})
});
Another point which needs to notice is that, when opening the client website in the private mode, it will still meet 401 while everything worked well when open the website in the normal window. That is because private mode doesn't contain auth information I think.
For Post request, still worked.
Post with parameters??

.NET Core 6 Web Api Authentication/ Authorization not working

I have written a small .NET 6 minimal web api, which is heavily based on / copied from a tutorial I did. The tutorial worked as expected, but I have two problems in my version.
The first problem is with swagger. When I uncomment the line c.OperationFilter<SecurityRequirementsOperationFilter>(); in AddSwaggerGen() I get a swagger error in the browser "Failed to load API definition. Fetch error. response status is 500 https://localhost:7123/swagger/v1/swagger.json"
The second problem is (when the swagger line is commented out to get it to run) nothing is secured. Either from swagger or from the browser I can access all endpoints.
Here is my program.cs. It certainly looks like I have everything in the right place. Even so, I would have expected that if it was misconfigured, it would prevent me from accessing the endpoints.
using DataAccess.DbAccess;
using MyAuthAPI;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(
c => {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyAPI", Version = "v1" });
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme {
Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
// When this line is uncommented I get a swagger error- Failed to load api
// c.OperationFilter<SecurityRequirementsOperationFilter>();
});
builder.Services.AddSingleton<ISqlDataAccess, SqlDataAccess>();
builder.Services.AddSingleton<IPersonAuthData, PersonAuthData>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
// app.UseStatusCodePages();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.ConfigureRoutes();
app.Run();
The routes and db access etc all works fine, but here is the routes.cs file just in case.
using DataAccess.DTOs;
using Microsoft.AspNetCore.Authorization;
namespace MyAuthAPI;
[Authorize]
public static class Routes
{
public static void ConfigureRoutes(this WebApplication app)
{
app.MapGet("PersonAuths", GetPersonAuths);
app.MapGet("PersonAuths/{id}", GetPersonAuth);
app.MapPost("Login", Login);
}
private static async Task<IResult>GetPersonAuths(IPersonAuthData data)
{
try
{
return Results.Ok(await data.GetPersonAuths());
} catch(Exception ex)
{
return Results.Problem(ex.Message);
}
}
private static async Task<IResult> GetPersonAuth(int id, IPersonAuthData data)
{
try
{
var results = await data.GetPersonAuth(id);
if (results == null) return Results.NotFound();
return Results.Ok(results);
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
}
[AllowAnonymous]
private static async Task<IResult> Login(LoginDTO loginDetails, IPersonAuthData data)
{
try
{
string jwt = await data.Login(loginDetails);
if (jwt != "")
{
return Results.Ok(jwt);
} else
{
return Results.Unauthorized();
}
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
}
}
Thanks
Edit
The swagger issue looks like it may be due to Swashbuckle.AspNetCore.Filters not supporting minimal apis.
Swashbuckle.AspNetCore.Filters

Why is /signin-oidc returning 404 after using Azure AD sign-in?

I'm implementing Azure AD authentication in an ASP.NET Core MVC 3.0 app. I have followed the instructions in this tutorial, the option 2; the only difference is I used an existing app instead of the downloadable example (I made sure of installing all NuGet packages and adding configuration data as provided by the tutorial and the example). I'm testing this app in my local machine.
App is properly registered in Azure so I have a client ID and a tenant ID. Data as follows:
Redirect URIs: Web, https://localhost:5002/signin-oidc; Web, https://localhost:5002 (in that order)
Logout URL: https://localhost:5002/signout-oidc
Implicit grant: ID tokens
Trying to access an action marked with [Authorize] triggers the sign in process, but when it's complete, it redirects to https://localhost:5002/signin-oidc and then the site returns 404.
appsettings.json config:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "[OMITTED]",
"TenantId": "[OMITTED]",
"ClientId": "[OMITTED]",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"AllowedHosts": "*"
}
Startup class:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace TestApp.WebSite
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services
.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.Authority += "/v2.0/";
options.TokenValidationParameters.ValidateIssuer = false;
});
services.AddLocalization(options => options.ResourcesPath = "Resources");
services
.AddControllersWithViews(options => options.Filters.Add(GetAuthorizeFilter()))
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRequestLocalization(GetLocalizationOptions());
app.UseStaticFiles(GetStaticFileOptions());
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
private RequestLocalizationOptions GetLocalizationOptions()
{
var cookie_request_culture_provider = new CookieRequestCultureProvider
{
CookieName = "UserCulture"
};
var providers = new List<IRequestCultureProvider>()
{
cookie_request_culture_provider,
new AcceptLanguageHeaderRequestCultureProvider()
};
var supported_cultures = new CultureInfo[]
{
new CultureInfo("en"),
new CultureInfo("es")
};
var result = new RequestLocalizationOptions
{
RequestCultureProviders = providers,
SupportedCultures = supported_cultures,
SupportedUICultures = supported_cultures,
DefaultRequestCulture = new RequestCulture("en")
};
return result;
}
private StaticFileOptions GetStaticFileOptions()
{
var result = new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "text/plain"
};
return result;
}
private AuthorizeFilter GetAuthorizeFilter()
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
var result = new AuthorizeFilter(policy);
return result;
}
}
}
Any advice that can point me in the right direction will be greatly appreciated.
That is because you miss the app.UseAuthentication(); so that OIDC middleware can't handle the authentication process in your application :
app.UseAuthentication(); //add this line
app.UseAuthorization();

asp core 2.1 angular 6 iis 8 unable to find css js files

I have an asp.net core Angular 6 application that works fine locally in visual studio or if i run this command on the iis server: dotnet .\CTI_Admin.dll
When I try to connect via the IIS webserver all of my css and js files receive this error on an IIS 8 server.
Failed to load resource: the server responded with a status of 404 (Not Found).
Statup.cs
using AspNet.Security.OpenIdConnect.Primitives;
using AutoMapper;
using CTI_Admin.Authorization;
using CTI_Admin.Helpers;
using CTI_Admin.ViewModels;
using DAL;
using DAL.Core;
using DAL.Core.Interfaces;
using DAL.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using OpenIddict.Abstractions;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.IO;
using AppPermissions = DAL.Core.ApplicationPermissions;
namespace CTI_Admin
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"], b => b.MigrationsAssembly("CTI_Admin"));
options.UseOpenIddict();
});
// add identity
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Configure Identity options and password complexity here
services.Configure<IdentityOptions>(options =>
{
// User settings
options.User.RequireUniqueEmail = true;
// //// Password settings
// //options.Password.RequireDigit = true;
// //options.Password.RequiredLength = 8;
// //options.Password.RequireNonAlphanumeric = false;
// //options.Password.RequireUppercase = true;
// //options.Password.RequireLowercase = false;
// //// Lockout settings
// //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
// //options.Lockout.MaxFailedAccessAttempts = 10;
options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});
// Register the OpenIddict services.
services.AddOpenIddict()
.AddCore(options =>
{
options.UseEntityFrameworkCore().UseDbContext<ApplicationDbContext>();
})
.AddServer(options =>
{
options.UseMvc();
options.EnableTokenEndpoint("/connect/token");
options.AllowPasswordFlow();
options.AllowRefreshTokenFlow();
options.AcceptAnonymousClients();
options.DisableHttpsRequirement(); // Note: Comment this out in production
options.RegisterScopes(
OpenIdConnectConstants.Scopes.OpenId,
OpenIdConnectConstants.Scopes.Email,
OpenIdConnectConstants.Scopes.Phone,
OpenIdConnectConstants.Scopes.Profile,
OpenIdConnectConstants.Scopes.OfflineAccess,
OpenIddictConstants.Scopes.Roles);
// options.UseRollingTokens(); //Uncomment to renew refresh tokens on every refreshToken request
// Note: to use JWT access tokens instead of the default encrypted format, the following lines are required:
// options.UseJsonWebTokens();
})
.AddValidation(); //Only compatible with the default token format. For JWT tokens, use the Microsoft JWT bearer handler.
// Add cors
services.AddCors();
// Add framework services.
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
//Todo: ***Using DataAnnotations for validation until Swashbuckle supports FluentValidation***
//services.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
//.AddJsonOptions(opts =>
//{
// opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "CTI_Admin API", Version = "v1" });
c.OperationFilter<AuthorizeCheckOperationFilter>();
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "password",
TokenUrl = "/connect/token",
Description = "Note: Leave client_id and client_secret blank"
});
});
services.AddAuthorization(options =>
{
options.AddPolicy(Authorization.Policies.ViewAllUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewUsers));
options.AddPolicy(Authorization.Policies.ManageAllUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageUsers));
options.AddPolicy(Authorization.Policies.ViewAllRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewRoles));
options.AddPolicy(Authorization.Policies.ViewRoleByRoleNamePolicy, policy => policy.Requirements.Add(new ViewRoleAuthorizationRequirement()));
options.AddPolicy(Authorization.Policies.ManageAllRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageRoles));
options.AddPolicy(Authorization.Policies.AssignAllowedRolesPolicy, policy => policy.Requirements.Add(new AssignRolesAuthorizationRequirement()));
});
Mapper.Initialize(cfg =>
{
cfg.AddProfile<AutoMapperProfile>();
});
// Configurations
services.Configure<SmtpConfig>(Configuration.GetSection("SmtpConfig"));
// Business Services
services.AddScoped<IEmailSender, EmailSender>();
// Repositories
services.AddScoped<IUnitOfWork, HttpUnitOfWork>();
services.AddScoped<IAccountManager, AccountManager>();
// Auth Handlers
services.AddSingleton<IAuthorizationHandler, ViewUserAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, ManageUserAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, ViewRoleAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, AssignRolesAuthorizationHandler>();
// DB Creation and Seeding
services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();
}
// 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(LogLevel.Warning);
loggerFactory.AddFile(Configuration.GetSection("Logging"));
Utilities.ConfigureLogger(loggerFactory);
EmailTemplates.Initialize(env);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
//Configure Cors
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseAuthentication();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.DocumentTitle = "Swagger UI - Quick Application";
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CTI_Admin API V1");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
spa.Options.StartupTimeout = TimeSpan.FromSeconds(60); // Increase the timeout if angular app is taking longer to startup
//spa.UseProxyToSpaDevelopmentServer("http://localhost:4200"); // Use this instead to use the angular cli server
}
});
}
}
}
You need to follow the steps:
Bundle your Angular application using ng build --prod
Ensure your IIS Hosting bundle is installed https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-2.1
Finally publish the website in a folder and the deploy to hosting server
For detailed instructions: https://code-maze.com/net-core-web-development-part16/#windowsserver
The way i resolved this was by adding --base-href to
ng build --extract-css --base-href /CTI_Admin/ClientApp/dist
However, my JS files are not loading even though i get a status code 200. The new error I receive is
scripts.c070f8cfd43553c493e4.js:1 Uncaught SyntaxError: Unexpected token <
Its basically returning the index.html code.
UPDATE:
This is the proper build script when you application is setup under site in IIS
ng build --prod --extract-css --base-href /CTI_Admin/