Blazor Server with Microsoft Identity in IIS with virtual application - c#

I've created a Blazor Server project using the standard Visual Studio 2022 template with authentication set to Microsoft Identity. It works locally without issue.
When I try to deploy it to the default website on an IIS server in a virtual application, it gives the following error:
Program.cs:
var builder = WebApplication.CreateBuilder(args);
var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ') ??
builder.Configuration["MicrosoftGraph:Scopes"]?.Split(' ');
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
builder.Services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
I think it is an issue with the return url, because the virtual application name is added to the address automatically. I have this url included in my app registration, but it still doesn't work.

I think after you see the error message page above, you may try to visit http://localhost or maybe you change the default home page url so http://localhost/the_word_you_covered and see if the user already signed in successfully.
I created a new Blazor server application with Microsoft Identity, then I fill the appsettings.json with tenant id, client id, and leave the CallbackPath as /signin-oidc by default. And in AAD, set redirect URL as https://localhost/signin-oidc. It worked well when test locally. After published to IIS, the sign in didn't work well so I comment the
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
and content in the so that I can see more error issue.
if (!app.Environment.IsDevelopment()) { }
But after doing these steps, everything worked well except the sign in redirect back to http://localhost/signin-oidc. Pls note here we need to set the redirect URL as http in Azure AD portal because IIS uses HTTP by default. But since there's no page routing to signin-oidc.
=========================================
If what I said above is not the issue, I'm afraid you can create a self-signed certificate and bind it to the default website, then visiting https instead. Just now I tried again and it keep showing 500 error like screenshot below. Then I create self-signed certificate to use https then solved the 500 error.

Related

Specify RedirectURI under openidconnect options - Azure AD, .NET6 C#

I have an azure Active Directory and have my app registered under it.
Under the RedirectURIs in the portal, i have specified this http://custom_domain/signin-oidc.
Under my startup.cs, i have these codes.
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.Authority = options.Authority + "/v2.0";
options.TokenValidationParameters.ValidateIssuer = false;
});
All the information specified under the app settings is correct (ClientID, TenantID, etc)
When deployed to my Azure App Service, the redirect URI changes to the app service original url name instead of the custom domain.
Inspected the login page when my app was executed:
https://login.microsoftonline.com/5910deee------/oauth2/v2.0/authorize?client_id=2782------&redirect_uri=https%3A%2F%2F**WRONG REDIRECT URI WHICH WAS NOT SPECIFIED UNDER THE AZURE PORTAL AD REDIRECT URI**%3A44345%2Fsignin-oidc&response_type=id_token&scope=openid%20profile&response_mode=form_post&nonce=6379148910548699......
How can I specify the redirect uri in my codes, or have the MS login page redirect to my custom domain uri? Specifying under the PORTAL -> AD -> Authentication -> Redirect URIs does not work.
Below are the workaround you can follow to resolve the above issue;
Make sure that you have provided the redirect uri same as on our Azure AD application(Authentication >..Redirect Uri) in your appsettings.json file.
As stated by #Tinywang, If you have multiple redirect uri in your application please remove those and keep the same which you want to redirect after log-in.
i m getting the error "The path in 'value' must start with '/'. " when
i follow as per the image you shared. The value is /signin-oidc
initially
So if you have done with all the above steps , Please make sure that your redirect uri must be begin with https and not http as you have mentioned in the question it is http://custom_domain/signin-oidc which is not valid.
For example you can set something like:- https://contoso.com/abc/response-oidc.
Program.cs should look like this:-
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages()
.AddMicrosoftIdentityUI();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.Run();
And in appsettings.json
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "[ e.g. contoso.onmicrosoft.com]",
"TenantId": "00000-00000-0000000",
"ClientId": "11111111-222222-333",
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath ": "/signout-callback-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
NOTE:- Make sure that you have enabled SSL value to true in Visual studio .
For complete setup and more information please refer the below Links:-
MICROSOFT DOCUMENTATION|Supported redirect uri and Configuration file.
Blog| Create an ASP.NET Web Application (.NET Framework – Web Forms or MVC) using Azure AD Authentication .
SO THREAD suggested by #diegosasw

Azure AD Exception: Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler<TOptions>.HandleRequestAsync()

I try add Azure AD auth. I alredy have a default auth with AccountController
When I try call https://localhost:44304/signin-oidc I get error
I try connect like:
services.AddMicrosoftIdentityWebAppAuthentication(Configuration);
or
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
AzureAd implemented in appsettings, for test project it works.
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
When I try call https://localhost:44304/signin-oidc I get error
When you call above url by broswer directly, it should be Http GET request. This is the reason you are experiencing the phenomenon.
Step 1
Open F12 to monitor the Http request in the Network.
1. Under normal operation steps, the captured Http Request is of the post method.
call https://localhost:44304/signin-oidc by browser.
Related issue
Microsoft Account Authentication not working
#1012
CallbackPath is used for the middleware to receive the results of the remote auth. You do not need a route/controller/action for this path. Once it has processed the results and generated the sign-in identity/cookie, then it will redirect back to your app code, either to where it started or where you told it to return to in the initial challenge.
Recommendation: keep the default CallbackPath value /signin-microsoft and register https://localhost:50001/signin-microsoft in the MSA portal.

Azure AD SSO: .Net Core 2.1 Single Sign On Based On Organization's Office 365 Username&Password

I have created an ASP.NET Core 2.1 MVC web application and I have used a simple login form to authenticate the users. Now We have decided to remove the login form and use a single sign-on option with my Organization's Office 365 user credentials or my office’s outlook username & password and followed the following Microsoft website but I could not choose the right SSO one.
This web app is a MVP (minimum viable product) project so we just don't want to use our own authentication & authorization process and only my organization people going to use this app so we have decided to use the Organization's Azure AD SSO. I am not using SAML or WS-Federation protocols in my web app but I just wanted to implement the SSO for my project.
I searched many sites on the internet, a few websites explained "No code is required to configure SSO but only Azure AD configurations" and some other websites explained with some piece of code also. So now I am totally confused that how should I achieve the SSO for my simple web application.
Hosted environment: Azure App Service
Application users: only organization users (internal web app)
My Startup.cs code:
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.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.AddSession(options =>
{
options.Cookie.IsEssential = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//Fetching Connection string from APPSETTINGS.JSON
var ConnectionString = Configuration.GetConnectionString("MbkDbConstr");
//Entity Framework
services.AddDbContext<ShardingDbContext>(options => options.UseSqlServer(ConnectionString));
//Automapper Configuration
AutoMapperConfiguration.Configure();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller:required}/{action}/{id?}",
defaults: new { controller = "UserAccount", action = "UserLogin" });
});
}
}
Note: I have configured the app.UseAuthentication() & other functions but authentication part not used inside my projects.
If you want to Authenticate your users with App Services, refer the document to see how to enable AAD Authentication in app services.
Generally for any web application, you can configure App Registration in Azure AD. You can configure claim attribute as well in order to use SSO feature. Refer the document for how to configure app registration in Azure AD.

AspNetCore Web Api Microsoft Account Authentication

My basic requirement is a Web Api that exposes some REST resources. Authentication is required to access any resource, and I want that to happen via Microsoft Accounts. This is to be a web api for programmatic access.
I started along this path: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins?view=aspnetcore-2.2
And have got to the end. It probably works fine except I get this:
InvalidOperationException: The default Identity UI layout requires a partial view '_LoginPartial' usually located at '/Pages/_LoginPartial' or at '/Views/Shared/_LoginPartial' to work.
But I don't want a UI with a sign in experience. I want apps (and users from clients such as browsers) to authenticate via Microsoft and then access my REST resources.
My configure services looks like this:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultTokenProviders()
//.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<IdentityDbContext>();
services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = _config["Authentication:Microsoft:ApplicationId"];
microsoftOptions.ClientSecret = _config["Authentication:Microsoft:Password"];
});
And then:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseAuthentication();
Program just does:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:5000", "https://localhost:5001");
You have implemented the Microsoft Authentication AND the login process in the same application, this kind of solution produce a cookie for the ASP.NET.
You probably want clients to authenticate, via OAuth, passing a Bearer Token.
In this case you must use a JwtBearer token authentication.
In this scenario your application DO NOT provide a UI for the authentication (like the example), instead ONLY validate/authenticate the token received.
Here some references
jwt auth in asp.net core
jwt validation
token authenticationin Asp.NET
Authentication in ASP.NET Core JWT

Azure AD /signin-oidc 404 - NGINX reverse proxy with .NET Core 2.0

I have a .NET Core 2.0 application running in a Kubernetes cluster with Linux containers. In front of the application I have an Nginx reverse proxy that is set up with LetsEncrypt, SSL termination, and forwarding http to the app.
My app successfully authenticates and redirects locally (without reverse proxy) and is based on the sample form here:
https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect-aspnetcore
When deployed, this setup initially caused issues with the app attempting to authenticate users by switching from https://my.domain.cloudapp.azure.com to http://my.domain.cloudapp.azure.com. As a result my reply URL (https://my.domain.cloudapp.azure.com/signin-oidc) was not being used and I received an error.
I was able to fix this with information from here and here and specifically I added:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.Use(async (context, next) =>
{
if (context.Request.Host.Host.ToLower() != "localhost")
context.Request.Scheme = "https";
await next.Invoke();
});
Now when I go to https://my.domain.cloudapp.azure.com I'm redirected properly to https://login.microsoftonline.com/. After authenticating I'm redirected back to my app at https://my.domain.cloudapp.azure.com but the OpenID Connect authentication middleware does not seem to be handling the /signin-oidc route. I instead receive a 404 error.
Does anyone know what I'm doing wrong?
I ended up having two problems that were causing this issue. First, I had multiple pods serving my app in Kubernetes and so I needed to persist the encryption/decryption keys for the cookies to a central location.
The second issue was that the reverse proxy was rewriting the reply url. My project changed a little since my original post and I switched to OAuth2 Proxy so I'm not sure the exact scenario for Nginx in my original post. However, for Oauth2 Proxy I had to add "https://my.domain.cloudapp.azure.com/oauth2/callback" as a reply url in my app registration.

Categories