Windows Authentication with asp.net core - asp.net-core

Please provide guidance on how to implement Windows Authentication on ASP.NET Core RC2+.
I see other SO questions that describe bearer authentication like Bearer Authentication with ASP.NET Core RC2 404 instead of 403
But that is not what I am looking for.

You can do this using WebListener, like so:
Open your project.json and add WebListener to dependencies:
"dependencies" : {
...
"Microsoft.AspNetCore.Server.WebListener": "0.1.0-rc2-final"
...
}
Add WebListener to commands (again in Project.json)
"commands": {
"weblistener": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener"
},
In Startup.cs, specify the WebHostBuilder to use WebListener with NTLM
var host = new WebHostBuilder()
// Some configuration
.UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM)
// Also UseUrls() is mandatory if no configuration is used
.Build();
That's it!

This doesn't appear to work any longer in the .Net Core 1.0.0 (RTM). I do the WebHostBuilder exactly as above in Ivan Prodanov's answer; it runs, don't get an error there, but the HttpContext.User is not marked with a WindowsIdentity. Following code used to work in ASP.Net 5 beta6:
in project.json:
"version": "1.0.0"
"dependencies": {
"Microsoft.AspNetCore.Owin": "1.0.0",
"Microsoft.AspNetCore.Server.WebListener": "0.1.0",
in middleware class:
public async Task Invoke(HttpContext context)
{
try
{
ClaimsPrincipal principal = context.User;
// <-- get invalidcastexception here:
WindowsIdentity winIdentity = (WindowsIdentity)principal.Identity;
....
....

Check your launchSettings.json file - change anonymousAuthentication to false
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
For deployment to iis check this Asp.Net core MVC application Windows Authentication in IIS

Related

Blazor and OIDC iframes Content Security Policy error

I had implemented OIDC authentication in my Blazor WebAssembly app (v6.0.6, non-hosted with ASP.NET), which worked fine. I had used Microsoft's template for new Blazor WebAssembly app with Authentication Type "Individual Accounts". My extra code :
Program.cs
...
builder.Services.AddScoped(sp => new HttpClient
{
BaseAddress = new Uri(builder.Configuration["httpClientBaseAddress"])
});
builder.Services.AddOidcAuthentication(options =>
{
builder.Configuration.Bind("oidc", options.ProviderOptions);
});
...
appsetting.json
{
"oidc": {
"Authority": "https://xxx.xxx.xx",
"ClientId": "clientIdxxx",
"DefaultScopes": [ "openid", "profile", "email", "xxapi" ],
"PostLogoutRedirectUri": "authentication/logout-callback",
"ResponseType": "code"
}
}
The Identity Server 4 we are using for central authentication is set for accepting my app.
All worked fine! However, after updating in version v6.0.7, I get the following error and my app never redirects to 'https://xxx.xxx.xx' for providing my credentials:
Refused to frame 'https://xxx.xxx.xx' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'none'".
No changes have made in Identity server, so I assume it is fault of the update.
So, having in mind that I'm using a Blazor WASM standalone app, how can I add the right headers for the 'Content Security Policy'?
Thanks in advance for your help!

How to inject the GraphServiceClient in Asp.net 6 (with application permissions NOT delegation permissions)

I have managed to get the GraphServiceClient to work on its own in daemon code, but would like to be able to inject it into my razor pages' constructor as well.
var queryOptions = new List<QueryOption>()
{
new QueryOption("startDateTime", "2022-08-02T16:22:00"),
new QueryOption("endDateTime", "2022-08-02T23:59:00")
};
var res = await _graphServiceClient.Users["smtp>"]
.CalendarView
.Request(queryOptions)
.Select("start,end,subject")
.GetAsync();
What code should be add to the builder?
The Id's and Secrets being read are valid and correct.
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "client.onmicrosoft.com",
"TenantId": "tenantid",
"ClientId": "clientid",
"ClientSecret": "clientsecret"
},
"Graph": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "https://graph.microsoft.com/.default"
},
I have tried the following and received: MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call even though it exposes an injectable GraphServiceClient to my page.
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(builder.Configuration.GetSection("Graph"))
.AddInMemoryTokenCaches();
I had the same error when I was trying to call GetAccessTokenForUserAsync (on ITokenAcquisition) at the Api Controller (Asp.net core 6.0).
"Microsoft.Identity.Client.MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call."
I was able to resolve it by using AuthorizeForScopes attribute on controller action. Example -
[AuthorizeForScopes(Scopes = new[] { AppConstants.ApiAppScope })]
Where AppConstants.ApiAppScope is the scope of my own WebApi.
If you are calling Graph api, it would be - https://graph.microsoft.com/.default
if you are calling your own Azure AD Web api, it would be something like api://app-id-of-web-api-as-registered-in-Azure-Ad/scope-defined-under-expose-as-api (i.e. api://ff1acf30-8c34-45ce-9bf6-7a47fa42d6be/access_as_user)
I couldn't figure out how to use built-in InMemory cache and I ended up creating my own caching. Caching is needed because call to GetAccessTokenForUserAsync will prompt the user to login again (if the scope is new).
This is my own application (self-disclaimer) that I am using for research (working sample)- https://securityresearchlab.aspnet4you.com/

asp.net 6 Get Windows User

I am having a devil of a time getting a simple Windows Domain User in my view in a apsnet core MVC project. Looking in google, i see a lot of people having the same question but very few suggestions past a full auth system. I was just hoping to turn on windows auth and get a username, no need for any other functions then to just display a name in the view.
In the past I have used:
#User.Identity.Name
in my launchSettings.json:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
I did also added to Program.cs:
app.UseAuthentication();
app.UseAuthorization();
Is there no way to just grab the windows user for a display value in asp.net core 6
In my opinion,you should have authentication to get UserName,you need to Enable Windows Authentication.
Program.cs:
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;
});
builder.Services.AddHttpContextAccessor();
app.UseAuthentication();
app.UseAuthorization();
launchSettings.json:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
}
Controller:
string UserName = HttpContext.User.Identity.Name;
Test Result:
For more details,please check this link.
If you do not need to automaticaly login the user with Windows Authentication, and you have already a custom login Controller to do that,you can refer to this.

ASP.NET Core 3.1 HttpClient to log only warnings and errors

I've noticed that my application(service) that supposed to run in a backgraund creates a log of garbage logging information because of HttpClient, like so:
info: System.Net.Http.HttpClient.Default.LogicalHandler[100]
Start processing HTTP request POST https://localhost:44317/programmatic/getcontent info:
System.Net.Http.HttpClient.Default.ClientHandler[100]
Sending HTTP request POST https://localhost:44317/programmatic/getcontent info:
System.Net.Http.HttpClient.Default.ClientHandler[101]
Received HTTP response after 3027.6345ms - OK info: System.Net.Http.HttpClient.Default.LogicalHandler[101]
End processing HTTP request after 3028.2987ms - OK info: System.Net.Http.HttpClient.Default.ClientHandler[101]
Received HTTP response after 3052.4709ms - OK info: System.Net.Http.HttpClient.Default.LogicalHandler[101]
End processing HTTP request after 3053.467ms - OK
Is there a way to configure it anywhere?
I inject client factory like this:
serviceCollection.AddHttpClient();
And then create a client like this:
HttpClient client = _clientFactory.CreateClient();
You can configure Logging in .NET Core through the Appsettings file. You should find a section in the appsettings.json file along the lines
{
"Logging": {
"Debug": {
"LogLevel": {
"Default": "Information"
}
}
}
}
You can add an additional Log Level filter to specify the minimum log level required to log.
{
"Logging": {
"Debug": {
"LogLevel": {
"Default": "Information",
"System.Net.Http.HttpClient": "Debug"
}
}
}
}
Documentation for Logging with filters in .NET Core can be found here.
Documemtation for Logging with filters in the IHttpClientFactory library can be found here. This documentation also includes examples of log filtering with a named HttpClient.
You can override log level in appsettings.json by adding, for example, a new row to the Logging object:
"Logging": {
"LogLevel": {
"System.Net.Http.HttpClient": "Warning"
}
},
This will log anything from Warning level and above.

asp .net core 3.1 identity server

I have a project that needs to be updated at .net core 3.1. The problem is that i don't know how to use this new feature from 3.1. I have my Identity Server Settings in appsettings.development.json, like this:
"IdentityServerSettings": {
"TokenUrl": "https://esample/token",
"ClientId": "xxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxx",
"ClientSecret": "yyyyy-yyyyy-yyyyy-yyyyy-yyyyyyyyy",
"GrantType": "credentials",
"Scope": "scope"
}
Here is the Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
var identityServerSettingsSection = this.Configuration.GetSection("IdentityServerSettings");
services.AddIdentityServer()
// here i need to app those properties from json
}
Here is how i read them from json file
identityServerSettingsSection.GetValue<string>("ClientId")
Thanks in advance!
If you want to read the different attributes of the section IdentityServerSettings you can do it like this, suppose you want to read ClientId.
this.Configuration.GetSection("IdentityServerSettings").GetSection("ClientId");
Or if you want to read all the attributes you can use the option pattern.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1
you can add identityserver like this
services.AddIdentityServer(Configuration);
which Configuration is IConfiguration. and for appsetting.json follow this IdentityServer Options