Can not find AddAuthentification method in Microsoft Extensions Package - authentication

I am trying to use Microsoft.Extensions.DependencyInjection's method AddAuthentification on a ASP .NET Core 2.1 project though it seems it does not exist in the package when trying to resolve it.Instead i have an extension AddAuthentificationCore which does not have the same signature.
According to the documentation it should be present for .NET Core 2.1.
P.S I want to use the AddAuthentification like :
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
options.LoginPath = "/login";
options.AccessDeniedPath = "/AccessDenied";
options.Events.OnRedirectToLogin = (context) => {
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});

That's not part of Microsoft.Extensions.DependencyInjection. It simply uses that namespace so no explicit additional using statement is required to have the extensions show up. It will actually live in one of the Microsoft.AspNetCore.Authentication NuGet packages.

Related

Migration to Minimal API - Test Settings Json not overriding Program

Thanks to this answer: Integration test and hosting ASP.NET Core 6.0 without Startup class
I have been able to perform integration tests with API.
WebApplicationFactory<Program>? app = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
});
});
HttpClient? client = app.CreateClient();
This has worked using the appsettings.json from the API project. Am now trying to use integrationtestsettings.json instead using:
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(ProjectDirectoryLocator.GetProjectDirectory())
.AddJsonFile("integrationtestsettings.json")
.Build();
WebApplicationFactory<Program>? app = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureAppConfiguration(cfg => cfg.AddConfiguration(configuration));
builder.ConfigureServices(services =>
{
});
});
_httpClient = app.CreateClient();
I have inspected the configuration variable and can see the properties loaded from my integrartiontestsettings.json file. However, the host is still running using the appsettings.json from the server project.
Previously, in .Net5, I was using WebHostBuilder and the settings were overridden by test settings.
WebHostBuilder webHostBuilder = new();
webHostBuilder.UseStartup<Startup>();
webHostBuilder.ConfigureAppConfiguration(cfg => cfg.AddConfiguration(_configuration));
But cannot get the test settings to apply using the WebApplicationFactory.
It seems the method has changed.
Changing:
builder.ConfigureAppConfiguration(cfg => cfg.AddConfiguration(configuration));
To:
builder.UseConfiguraton(configuration);
has done the trick.
builder.ConfigureAppConfiguration, now it's configuring the app (after your WebApplicationBuilder.Build() is called) and your WebApplication is created.
You need to "inject" your configurations before the .Build() is done. This is why you need to call UseConfiguraton instead of ConfigureAppConfiguration.

How to modify .Aspnetcore.Identity.Application Cookie name?

I wanna hide that i use ASP.NET Core.
The Cookie name show that i use ASP.NET Core and Identity.
So, I Would modify the Cookie name, I don't know way.
How to do this?
Somebody help me please.
I solved this.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "MyCustomCookieName";
});
}
}
This works since .NET Core 3.1.
When using AddMicrosoftIdentityWebAppAuthentication from Microsoft.Identity.Web in .Net 5+, the ConfigureApplicationCookie method didn't work for me. I was able to change the name of the .AspNetCore.Cookies cookie by using the following code placed directly after the AddMicrosoftIdentityWebAppAuthentication method call:
services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Name = "AuthCookieName";
});

Getting 'TypeError: Failed to fetch' error when trying to call AspNetCore Restful API from Blazor Wasm

I'm getting a 'TypeError: Failed to fetch' error when trying to call my AspNetCore Restful API from Blazor Wasm. I can call it from Postman, and it works fine.
My Environment:
Microsoft Visual Studio Community 2019 Preview Version 16.6.0 Preview 3.0
Client: Blazor Wasm Service (dotnetstandard 2.1)
AspNet.WebApi.Client 5.2.7
AspNetCore..WebAssembly 3.2 preview 4.2
System.Net.Http.Json 3.2 preview 5.2
Important Usings:
using Microsoft.AspNetCore.JsonPatch;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
Parent namespace and class omitted
_httpClient is injected into parent class
public async Task<MyDto> UpdatePartialAsync(Guid primaryId, ObjectForUpdateDto objectForUpdateDto)
{
MyDto dtoFromApi = null;
var patchDoc = new JsonPatchDocument<ObjectForUpdateDto>()
.Replace(o => o.Name, objectForUpdateDto.Name)
.Replace(o => o.Description, objectForUpdateDto.Description)
var uri = $"MyUri/myResources/{primaryId}";
try
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var serializedPatchDoc = JsonConvert.SerializeObject(patchDoc);
var json = new StringContent(serializedPatchDoc, Encoding.UTF8, "application/json-patch+json");
var response = await _httpClient.PatchAsync(uri, json);
return await response.Content.ReadAsAsync<MyDto>();
}
catch (Exception)
{
throw; //throws 'TypeError: Failed to fetch'
}
return dtoFromApi;
}
My API (.Net 5.0, also tried .Net Core 3.1):
[HttpPatch]
[Route("{primaryId}")]
public ActionResult UpsertPartial([FromRoute]Guid primaryId, [FromBody] JsonPatchDocument<ObjectForUpdateDto> objectForUpdateDto)
{
//client call never makes it here
return NoContent();
}
What a misleading error message. It was a CORS issue.
The fix was adding "PATCH" to my CORS policy in my API's startup.cs ConfigureServices method (which previously was "GET, DELETE, PUT, POST, OPTIONS").
services.AddCors(options =>
{
options.AddPolicy(CorsAllowAll,
builder =>
{
builder.WithOrigins(Constants.ApiClientCors).AllowAnyHeader().WithMethods("GET, PATCH, DELETE, PUT, POST, OPTIONS");
});
});
#inliner49er, I wish that I could add a comment to clarify what you responded, since your answer is correct, but I don't have enough reputation points. Therefore, I'll post my tweaks to your answer as a separate answer.
You nailed it, the CORS issue fixed my program also. The only part of your code that didn't make sense was the reference that you have to a class called Constants. I am in the process of trying to complete the PluralSight tutorial, and because I'm working entirely internally, I can safely replace your code with the following:
services.AddCors(options =>
{
options.AddPolicy("PolicyName", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
I am super new to all of this, literally hours into the process of learning about it, so there is a buttload that I don't understand. I just thought I'd post this to help anyone who might have similar questions to what I had.
You can also try adding these lines directly to the Configure method of the Startup class:
//ENABLE CORS
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials()); // allow credentials

Error 500 after upgrade .net core 1.1 prodution application to .net core 2

I have a relative complex project which is .net core 1.1 (.net framework).
The reason why choose .Net Framework was the database is Oracle and the Core Framework didn't support Oracle Entity Data Model. Anyway, the application has been working well in production about a year now.
I am trying to upgrade this project to .net core 2 now. According to the documentation here I modified the Authentication register in Startup, the project compiles.
old code:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "Administration",
LoginPath = new PathString("/Login/"),
AccessDeniedPath = new PathString("/Login/"),
AutomaticAuthenticate = true,
CookieSecure = CookieSecurePolicy.SameAsRequest,
AutomaticChallenge = true
});
updated code:
app.UseAuthentication();
services.AddAuthentication("Administration").AddCookie(options =>
{
options.LoginPath = new PathString("/Login/");
options.AccessDeniedPath = new PathString("/Login/");
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
});
I am getting an error page 500:
Can anyone please help?
After look at the stdout log, the problem was ConfigureServices can only take IServiceCollection. I was trying to inject another parameter in, but the project compiled.
I hope this can be found by intelligent sense or IDE run time

Swagger .Net Core

I am trying to configure swagger for my .Netcore App (1.1) and couldnt generate the docs.
Here is my configuration
public void ConfigureServices(IServiceCollection services) {
services.AddMvcCore().AddVersionedApiExplorer(o => o.GroupNameFormat = "1.0");
services.AddMvc();
services.AddApiVersioning(opt =>
{
opt.ApiVersionReader = new HeaderApiVersionReader("api-version");
opt.DefaultApiVersion = new ApiVersion(1, 0);
opt.ReportApiVersions = true;
opt.AssumeDefaultVersionWhenUnspecified = true;
});
services.AddSwaggerGen(
options =>
{
options.SwaggerDoc("1.0",new Info {Contact = new Contact() {Name="Admin" } });
// add a custom operation filter which sets default values
options.OperationFilter<SwaggerDefaultValues>();
});
}
In the Configure Method
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=User}/{action=Get}/{requestString?}");
});
app.UseSwagger(o=>
{
o.RouteTemplate = "docs/{documentName}/swagger.json";
});
app.UseSwaggerUI(
options =>
{
options.SwaggerEndpoint("/docs/1.0/swagger.json", "1.0");
});
When I run the application,
http://localhost:5000/docs/1.0/swagger.json
I am getting the below methods, None of my API's are discovered.
{"swagger":"2.0","info":{"contact":{"name":"Admin"}},"basePath":"/","paths":{},"definitions":{},"securityDefinitions":{}}
OK, I have reproduced your problem and found that the reason is the value in GroupNameFormat option.
If quickly, instead of const version string you should specify version format. As you want to have version in url as 1.0 you may use:
services.AddMvcCore().AddVersionedApiExplorer( o => o.GroupNameFormat = "VVVV" );
From Version Format section in Documentation:
Format Specifier: VVVV
Description: Major, minor version, and status
Examples: 1-RC -> 1.0-RC, 1.1 -> 1.1, 1 -> 1.0
Regarding AddMvcCore() vs AddMvc():
From the swagger docs at https://github.com/domaindrivendev/Swashbuckle.AspNetCore
Swashbuckle relies heavily on ApiExplorer, the API metadata layer that ships with ASP.NET Core. If you're using the AddMvc helper to bootstrap the MVC stack, then ApiExplorer will be automatically registered and SB will work without issue. However, if you're using AddMvcCore for a more paired-down MVC stack, you'll need to explicitly add the Api Explorer service:
services.AddMvcCore().AddApiExplorer();
If you also want AddVersionedApiExplorer(), chain that after AddApiExplorer()