My Asp.Net Core mvc web application requires Anonymous Authentication.
below is the launchSettings.json code
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:61545/",
"sslPort": 0
}
}
But after deploying,IIS Authentication settings are not changing based on launchSettings.json and it is changing based on authentication tag on web.config, which will automatically generate on publish.I tried adding web.config manually in solution with proper authentication settings.But,i am not able to debug the solution.How can i debug the application without renaming/removing the web.config file?Or Please suggest any alternate solution for resolving this issue.
Related
I've created a new dotnet 6 blazor wasm app with the core hosted option. The Visual Studio 2022 (v17.3.1) template creates Client, Server and Shared projects for this.
I've updated the Server project's program.cs to make use of Azure ADB2C as follows:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C"));
Its appsettings.json contains the following:
"AzureAdB2C": {
"Instance": "https://mydomain.b2clogin.com/",
"ClientId": "serverprojclientidhere",
"Domain": "mydomain.onmicrosoft.com",
"Scopes": "access_as_user",
"SignUpSignInPolicyId": "B2C_1_SignUpIn"
}
In the client project, the program.cs contains the following:
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("https://mydomain.onmicrosoft.com/api/Api.ReadWrite");
});
Its appsettings.json contains the following:
"AzureAdB2C": {
"Authority": "https://mydomain.b2clogin.com/mydomain.onmicrosoft.com/B2C_1_SignUpIn",
"ClientId": "clientprojclientidhere",
"ValidateAuthority": false
}
When I run this locally it works fine. The website loads and presents the home screen, if I select a "secured" page then I'm redirected to the ADB2C.
I have a devops pipeline that's deployed the solution to an Azure App Service (linux). If I go to the site it presents the hope page ok but on navigating to a secured page I get the following error message:
There was an error trying to log you in: 'this._settings.loginMode is
undefined'
I don't see any errors in the browser's console window.
Any ideas?
I managed to find the answer from this blog post
Resolution was to add the following to the client project's csproj file:
<ItemGroup>
<TrimmerRootAssembly Include="Microsoft.Authentication.WebAssembly.Msal" />
</ItemGroup>
I'm working on a .Net 5.0 Razor pages website that is configured to use windows authentication. With the follow block being included in launchSettings.json
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
}
Currently when you visit the site you will need to log in before you can view any of the pages. However, I would like to add a page that can be viewed by anyone without logging in. How can I enable public access or anonymous authentication for a single page?
You can use [AllowAnonymous] attribute in action which return specific single page.
[AllowAnonymous]
public IActionResult Index()
{
return View();
}
Simple authorization in ASP.NET Core
I've got a small Blazor app that uses AzureAD for user authentication. When I run the app directly from visual studio, I am able to login without any issues, however when I deploy the app to IIS, I get the below error when I click 'Login'.
IOException: IDX20807: Unable to retrieve document from: 'System.String'. HttpResponseMessage:
'System.Net.Http.HttpResponseMessage', HttpResponseMessage.Content: 'System.String'.
Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string address,
CancellationToken cancel)
InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'.
Microsoft.IdentityModel.Protocols.ConfigurationManager<T>.GetConfigurationAsync(CancellationToken cancel)
My appsettings.json configuration is:
AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "qualified.domain.name",
"TenantId": "22222222-2222-2222-2222-222222222222",
"ClientId": "11111111-1111-1111-11111111111111111",
"CallbackPath": "/signin-oidc",
"ClientSecret": "NNNNNNN-~nnnnnnnn_NNNNNNNNNNN~nnnn"
},
With the Domain, TenantId, ClientId and ClientSecret being populated from the secrets.json file.
My ConfigureServices function in the Startup.cs is:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(options =>
{
Configuration.Bind("AzureAd", options);
}, GraphConstants.Scopes)
.AddInMemoryTokenCaches();
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
services.AddRazorPages();
services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
services.AddMudServices();
}
And the code for the Login button is:
<AuthorizeView>
<Authorized>
Hello, #context.User.Identity.Name!
Log out
</Authorized>
<NotAuthorized>
Log in
</NotAuthorized>
</AuthorizeView>
My IIS configuration was done following the steps in this tutorial - https://www.c-sharpcorner.com/article/deploying-a-blazor-application-on-iis/
I've tried playing around with different settings around the AddMicrosoftIdentityWebApp section, figuring it was something to do with the configuration there, but nothing I try seems to make any difference.
Any help would be appreciated,
Thanks
Turns out the issue was to do with me using secrets.json to store some of the configuration.
This thread - ASP.NET Core 2 web application isn't loading user secrets when debugging IIS website - helped me figure out the solution
I’m encountering an issue wherein Windows authenticated user roles appear to be cached and are not updated until I restart the application. While a user's roles will not change often they do change and can change before an application restart is performed.
I am hosting my ASP.NET Core 2 application on IIS via Kestrel and the ASP.NET Core Module. Via the AuthorizeFilter I have a global policy which requires authenticated users. Users are not prompted for credentials but are instead authenticated via integrated Windows Authentication. Below are snippets of my application configuration that pertain to server host configuration, authentication and authorization:
Snippets from Program.cs
private static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel(options =>
{
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(30);
})
.UseIISIntegration()
.Build();
Snippets from Startup.cs
Authentication Configuration
services.AddAuthentication(options =>
{
options.DefaultScheme = IISDefaults.AuthenticationScheme;
options.DefaultForbidScheme = IISDefaults.AuthenticationScheme;
});
Authorization Configuration
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAuthenticatedUser",
policyBuilder => policyBuilder.RequireAuthenticatedUser());
});
Addition of Global AuthorizeFilter:
services.AddMvc(mvcOptions =>
{
mvcOptions.Filters.Add(new AuthorizeFilter("RequireAuthenticatedUser"));
});
Snippet from launchSettings.json
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:4100",
"sslPort": 0
}
}
}
All of this works wonderfully and users are required to authenticate and I am able to retrieve their Active Directory roles. Sadly, when those roles change without an application restart I am unable to get an updated list of roles. Meaning that users who should have access do not and those that should no longer have access still do. All of my role checking is based on the ClaimsPrincipal.IsInRole("xyz"), which remains stagnant from when the user first authenticated. However, if I use System.DirectoryServices.AccountManagement to check the user's current roles within Active Directory they are clearly updated (for production want to use built in functionality and don't want to resort to this).
What configuration changes, cache invalidation or session reset do I need to perform to ensure that when a user's AD roles change my application will reflect their current roles?
Ive set up my AzureAD in the portal, and an appservice that uses the AD to authenticate following instructions from microsoft.
Ive made a .net core app that uses this authorisation. It works on my localhost. But when i publish it i get this error
AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application: '614f66a9-xxxx-483a-8bc7-xxxxxxx'
What should i change and how come it works in my local but not when published?
This is current configuration of app:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "lmyName.onmicrosoft.com",
"TenantId": "******-ebd5-40d8-829b-*********",
"ClientId": "*****-8eef-483a-8bc7-********",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
When i followed the online intructions i was directed to configure the appservice in the portal to use reply URL: /.auth/login/aad/callback
Could that be the same as callbackPath?
For your case, you can change your reply URL in AAD Application to be <YourApplicaitonURL>/signin-oidc.
NOTE The base address in the Sign-on URL and Logout URL settings is http://localhost:port.
This localhost address allows the sample app to run insecurely from your local system. Port is the default port for the Kestrel server. Update the reply URL in your AAD Application if you configure the app for production use(If you publish your App to Azure Web App service).
For example, https://yourapp.azurewebsites.net/signin-oidc or https://www.contoso.com/signout-oidc
You can also refer to this Sample to Integrate Azure AD into an ASP.NET Core web app.
Please let me know if it helps!