How fix error 500 Server Internal Error in post login? - iis

I'm making an application with asp core 2.1 and Vue. My problem is the login to the production server (Windows Server 2012 R2). When I want to do login throws the following error.
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Access to XMLHttpRequest at 'http://{ip...}/api/account/login' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Uncaught (in promise) TypeError: Cannot set property 'error' of undefined at eval (Login.vue?03db:289)
All other endpoints respond except the login.
However, when I test in the development backend pointing to the production DB, it logs without problems and all the endpoints also respond (get, post etc). As far as I can understand it can be a configuration issue, maybe on the server related to IIS. As I understand if it were a matter of CORS no endpoint would work
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("defaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequiredLength = 5;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
options.TokenValidationParameters = new TokenValidationParameters
{
...
});
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddCors();
//Autorizacion a recursos de la aplicaciĆ³n
services.AddMvc().AddJsonOptions(ConfigureJson);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
});
}
private void ConfigureJson(MvcJsonOptions obj) {
obj.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext context)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseMvc();
}
Program.cs
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}

Related

BLAZOR, ASPCORE 5 and AzureAPP: has been blocked by CORS policy

I have a problem and i dont know how to solve. I use blazor, with AzureAD and azure Service ( I can loggin) but the problem is to access the data of the database that is in azureBD. I dont know why the redirection. I try a lot of code :( maybe something that i missing??
ERROR:
Access to fetch at 'https://login.microsoftonline.com/12acee71-6c99-48a3-9ff7-02fc9a24288a/oauth2/v2.0/authorize?client_id=5153b62a-311b-4c00-a0d0-at-ver=6.7.1.0' (redirected from 'https://rims.rafint.com/api/TblTeamStdRoles') from origin 'https://rims.rafint.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Failed to load resource: net::ERR_FAILED
startup.cs:
services.AddDbContext<RIMS_Copy24apr21Context>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DbContext")));
services.AddTransient <Rafint_RIMSService> ();
services.AddHttpClient();
services.AddOptions();
string[] initialScopes = Configuration.GetValue<string>(
"Rafint-RIMS:ScopeForAccessToken")?.Split(' ');
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddInMemoryTokenCaches();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigins("https://rims.rafint.com" , "https://rims.rafint.com/api/TblTeamStdRoles",
"api://5153b62a-311b-4c00-a0d0-a896b0cdc908/TblTeamStdRoles.read")
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddControllersWithViews();
services.AddRazorPages().AddMvcOptions(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
Problem
Program.CS
I need to access to the DataBase!!
As far as I know, the issue lies in the below code snippet,
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigins("https://rims.rafint.com" , "[https://rims.rafint.com/api/TblTeamStdRoles"](https://rims.rafint.com/api/TblTeamStdRoles%22 "https://rims.rafint.com/api/tblteamstdroles%22"),
"api://5153b62a-311b-4c00-a0d0-a896b0cdc908/TblTeamStdRoles.read")
.AllowAnyMethod()
.AllowAnyHeader());
});
To resolve the issue, please try with the following workarounds,
Try adding https:// for "api://5153b62a-311b-4c00-a0d0-a896b0cdc908/TblTeamStdRoles.read"
Otherwise, try including only two links("https://rims.rafint.com" , "https://rims.rafint.com/api/TblTeamStdRoles") in builder.WithOrigins
If it still occurs, make use of AllowAnyOrigin as below,
Services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
Please find below references if they are helpful.
References:
Ref1 , Ref2 , Ref3

MSAL access token getting unauthorized with MicrosoftIdentityWebApi Authentication

I set up my Startup Class below:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
}
// 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.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
My AzureAd appsettings.json is below:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "2f0d9252-e207-4d7f-b4da-*******",
"TenantId": "de1ef02c-7cfa-46b8-a02b-*******",
"Audience": "2f0d9252-e207-4d7f-b4da-*******"
}
Now my controller below:
[HttpGet]
public async Task<string> Get()
{
//To be put on appsettings.json
string clientId = "2f0d9252-e207-4d7f-b4da-0cc618e77c93";
string tenantId = "de1ef02c-7cfa-46b8-a02b-61ab78bc602b";
var app = PublicClientApplicationBuilder.Create(clientId)
.WithRedirectUri("http://localhost:5000")
.WithTenantId(tenantId)
.Build();
string[] scopes = new string[] { };
//Azure Login Success here
var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
//Azure service graph get success.
string graphResult = await "https://graph.microsoft.com/beta/me"
.WithOAuthBearerToken(result.AccessToken)
.GetStringAsync();
//I pass the AccessToken from the result. But I'm getting UnAuthorized.
string authorizeResult = await "https://localhost:44328/weatherforecast/AuthorizeGet"
.WithOAuthBearerToken(result.AccessToken)
.GetStringAsync();
return graphResult;
}
[Authorize]
[HttpGet]
public async Task<string> AuthorizeGet()
{
return "Authorize";
}
The Azure Login will success here. But after I get the token and request to AuthorizeGet Api. It will give me Unauthorized 401.
Anything I missed out for the configuration?
Below is my Directory Authentication config.

How to authenticate/authorize in Azure AD Auth using MSAL in .NET

What I'm trying to do is after I login my azure credentials in MSAL login pop up, I will use the token to access authorize API.
I set up my Startup.cs below:
I use Microsoft.Identity.Web nuget package.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
My apsettings.json AzureAd is configured below:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "2f0d9252-e207-4d7f-b4da-********",
"TenantId": "de1ef02c-7cfa-46b8-a02b-********",
"Audience": "2f0d9252-e207-4d7f-b4da-********"
}
In my controller I have 2 API.
[HttpGet]
public async Task<string> LoginAzure()
{
//To be put on appsettings.json
string clientId = "2f0d9252-e207-4d7f-b4da-********";
string tenantId = "de1ef02c-7cfa-46b8-a02b-********";
var app = PublicClientApplicationBuilder.Create(clientId)
.WithRedirectUri("http://localhost:5000")
.WithTenantId(tenantId)
.Build();
string[] scopes = new string[] { };
//Azure Login Success here
var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
//I pass the AccessToken from the result. But I'm getting UnAuthorized.
string authorizeResult = await "https://localhost:44328/weatherforecast/AuthorizeGet"
.WithOAuthBearerToken(result.AccessToken)
.GetStringAsync();
return authorizeResult;
}
[Authorize]
[HttpGet]
public async Task<string> AuthorizeGet()
{
return "Authorize";
}
The LoginAzure is for calling the MSAL.
And the AuthorizeToken is an authorize api.
I can successfully get the access token after login in azure using MSAL. But if I use the access token to the Bearer Token and access the authorize API, I'm getting 401 Unauthorize.
Anything I missed out on my configuration? Or how do I set up properly my MSAL?
If I try to access the microsoft graph api with the access token, I can successfuly access it.

Authenticate to Azure Active Directory by .NET Core web api from Front-End from different domain

I have a .NET Core 3.1 Web API that is able to authenticate to Azure AD. If a user tries to execute an endpoint he is redirected to https://login.microsoftonline.com/ and then he is able to use the API.
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.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins(Configuration["CorsDomains"].Split(';', tringSplitOptions.RemoveEmptyEntries));
});
});
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddSingleton<IOAuthTokenClient, OAuthTokenClient>();
services.AddSingleton<IAuthenticationProvider, AppAuthenticationProvider>();
}
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseCors(MyAllowSpecificOrigins);
app.UseMvc(routes =>
{
routes.MapRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
});
}
}
Now we are trying to connect to this API by JS from a DIFFERENT DOMAIN. I have problems in understanding how this JS should authenticate with this API (as a user in Azure AD). When JS calls the endpoint it gets redirect but Chrom blocks it as CORS request...
VM55:5 Access to XMLHttpRequest at
'https://login.microsoftonline.com/3912a795-6h78-446d-8548-a49ffd73f550/oauth2/v2.0/authorize?client_id=9f58a774-a9dc-4e6b-83cd-8967d3aeb0ec&redirect_uri=https%3A%2F%2Fourapi.azurewebsites.net%2Fsignin-oidc&response_type=id_token&scope=openid%20profile&response_mode=form_post&nonce=637203035634363596.YmIzYTgxNjctMjNhYy00OWE4LWFmYmEtMWRhZTM5MDAzZWQwYjA5MTdiZGMtZGI4OS00YTYwLTliN2EtNThiMWE5MmQ0Njcy&state=CfDJ8JU16Qc5LiRIl-KmHX3n1UK07_IvDsK1bEHExzX3MFzbLibzoctAms4RnZEV9W1G4g45SiKBQFGLiOWjDBUSerYBOPZ2fYloPvNbi2iDwwMdVTlGnTyD6wQpujGOxZx3VmpSlDaxokrmxLnQfomPapUFm6YFRBBM8G9zBu-Nd8_No2rjK1hhThHGcYWNKudJhzaWLqv23fcrn1JdZA1YmUl1Sj2Q6ZTq_gtzJjWmzHDmqzitqTKg0hqsXXZJ6LpyDMto89A0Qhg7akGix-xgXPKGXmTBZ_nmp3DceHTK94YDqBCe9AlDVUjp1OW0WfNiLN1ILve7K1mvPN1w2zPThgurMRzMkQ4TkC0Yzfi5QodGjWFN6FBeeF6YMpbn9YM-WjMgWRZyjAGQ9syW22bbvv5sEEMuNcW2AB6iMn4jV9hZ2u7tiAKM9lN6-MlZDrPdoGeexgR7uAmvJMcBhlam7LP_RbgJLp2FaPLNmKioYDjxV65fSX3ApZDLeB-dZfx34Q&x-client-SKU=ID_NETSTANDARD2_0&x-client-ver=5.5.0.0'
(redirected from
'https://ourapi.azurewebsites.net/api/Users/jan.kowalski#ourdomain.com/Calendar/Events?startDate=2020-03-20T00:00:00Z&endDate=2020-03-21T00:00:00Z')
from origin 'http://localhost:8181' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
We can enable issuing access tokens in Authentication section in the Azure Portal and thanks to that, JS would be able to get access token on its own but I do not know if this is a correct way to do this. Maybe it is possible to somehow authenticate to Azure AD by calling our API?

How to re-route Azure Active Directory , authentication which ends up in Loop?

I have set up an authentication using AAd, I have set up the client id, application id and domain and added the services. But once I give in the credentials ,it loops into this page.
This is the configuration setting :
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAd(options => Configuration.Bind("AzureAd", options))
.AddCookie();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<DbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.Cookie.Name = ".TreeView.Session";
options.IdleTimeout = TimeSpan.FromSeconds(3600);
});
services.AddTransient<IObjectRepositary, ObjectRepositary>();
services.AddSingleton<IConfiguration>(Configuration);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddMvc();
services.AddHostedService<TicketingService>();
}
I am passing in the app id, tentant id , call back url , domain information in app setting
To authenticate your webapp with Azure AD, you can use the easy auth under App Service app. You do not need to make any changes to your code, just configure with express settings. If you want to log the user out, call [your-domain]/.auth/logout
If you don't want to use the authentication under App Service app, remember not to enable the authentication under App Service app. You can follow this sample to integrate Azure AD to your webapp.
The SignOut method also works fine:
[HttpGet]
public IActionResult SignOut()
{
var callbackUrl = Url.Action(nameof(SignedOut), "Account", values: null, protocol: Request.Scheme);
return SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
[HttpGet]
public IActionResult SignedOut()
{
if (User.Identity.IsAuthenticated)
{
// Redirect to home page if the user is authenticated.
return RedirectToAction(nameof(HomeController.Index), "Home");
}
return View();
}

Resources