.Net Core 2 - How to add and use Authentication service (Jwt endpoint) - asp.net-web-api2

I am using .Net Core 2. I need to add a simple token endpoint. I was following this article but found that the below method is obsolete in .Net Core 2
app.UseJwtBearerAuthentication();
Quoting the second link:
Configure(): UseXyzAuthentication() has been replaced by ConfigureService(): AddXyz()
Therefore, in ConfigureService method, i am trying to use something like
services.AddAuthentication(new JwtBearerOptions());
which is not correct, i know but how to achieve this?
Unfortunately, i couldn't find any help on web.
Thanks

These are implemented some what in a more efficient manner in core 2.0
possible duplicate

It may also explain a lot easier and technical manner. Good solution

The migration guide contains a whole article dedicated to the changes in Authentication and Identity:
In Configure you have to call app.UseAuthentication();.
The code in ConfigureServices should be:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.Audience = "http://localhost:5001/";
options.Authority = "http://localhost:5000/";
});

Related

protobuf-net.grpc client and .NET Core's gRPC client factory integration

I am experimenting with a gRPC service and client using proto files. The advice is to use gRPC client factory integration in .NET Core (https://learn.microsoft.com/en-us/aspnet/core/grpc/clientfactory?view=aspnetcore-3.1). To do this you register the client derived from Grpc.Core.ClientBase that is generated by the Grpc.Tools package, like this:
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddGrpcClient<MyGrpcClientType>(o =>
{
o.Address = new Uri("https://localhost:5001");
});
})
My understanding is that MyGrpcClientType is registered with DI as a transient client, meaning a new one is created each time it is injected, but that the client is integrated with the HttpClientFactory, allowing the channel to be reused rather than be created each time.
Now, I would like to use protobuf-net.grpc to generate the client from an interface, which appears to be done like this:
GrpcClientFactory.AllowUnencryptedHttp2 = true;
using var http = GrpcChannel.ForAddress("http://localhost:10042");
var calculator = http.CreateGrpcService<ICalculator>();
If I am correct in thinking that channels are expensive to create, but clients are cheap, how do I achieve integration with the HttpClientFactory (and so reuse of the underlying channel) using protobuf-net.grpc? The above appears to create a GrpcChannel each time I want a client, so what is the correct approach to reusing channels?
Similarly, is it possible to register the protobuf-net.grpc generated service class with the below code in ASP.Net Core?
endpoints.MapGrpcService<MyGrpcServiceType>();
(Please correct any misunderstandings in the above)
Note that you don't need the AllowUnencryptedHttp2 - that's just if you aren't using https, but: you seem to be using https.
On the "similarly"; that should already work - the only bit you might be missing is the call to services.AddCodeFirstGrpc() (usually in Startup.cs, via ConfigureServices).
As for the AddGrpcClient; I would have to investigate. That isn't something that I've explored in the integrations so far. It might be a new piece is needed.
The Client Factory support not exists, and works exactly like documented here except you register with the method
services.AddCodeFirstGrpcClient<IMyService>(o =>
{
o.Address = new Uri("...etc...");
});

What is the difference between AddAuthentication and AddAuthenticationCore?

Looking at the code for AuthenticationServiceCollectionExtensions.AddAuthentication() vs AuthenticationCoreServiceCollectionExtensions.AddAuthenticationCore(), it looks like AddAuthentication implicitly calls AddAuthenticationCore, adds some other goodies, and then returns a new instance of AuthenticationBuilder instead of just returning IServiceCollection.
Am I understanding the code correctly? If so, are there generally any reasons to call AddAuthenticationCore instead of AddAuthentication outside of writing your own extension?
It seems to be a typical pattern in ASP.NET Core: the Add[xxx]Core methods add the bare minimum to enable a feature, but without any bells and whistles. It's also probably used to make unit testing the core features easier.
You can make a parallel with the AddMvc vs AddMvcCore methods. There's a question that asks Should I use AddMvc or AddMvcCore for ASP.NET Core MVC development?, and the gist is that it allows for fine-grained control on what middleware you want to use.
To answer your question: for a typical user, there's probably no reason to use AddAuthenticationCore.
Actually there is a reason. Currently AddAuthentication() also adds data protection services, which you may not need - for example if you are writing your own Authentication Scheme. So instead you can do this:
services.AddAuthenticationCore(o => {
o.DefaultScheme = "My Custom Scheme";
});
services.AddWebEncoders();
services.AddSingleton<ISystemClock, SystemClock>();
var authBuilder = new AuthenticationBuilder(services);
however I fully expect this to break in future versions of asp.net core as it's undocumented and a bit of a hack.

Getting a token for Web API

Once upon a time I used to install Thinktecture.IdentityModel, call it using basic auth to get a token and then pass this in the headers of ajax calls to Web API.
I just tried to do this, and it barfed.
Up periscope!
Method not found: no match for ctor signature (hurrah for Fiddler).
Comparison with a project in which it does work reveals that the required signature exists in version 2.0.0.0 of System.IdentityModel.Tokens.Jwt but is no longer present in version 4.0.20622.1351
Quick, Robin - to the Bingpole!
There's a github support query on this very topic and in the comments we find
leastprivilege commented on Jan 27
The AuthenticationHandler is not the recommended approach anymore for
Web API v2 since everything is now built-in - use middleware instead.
Unask the question, Grasshopper
This is a definitive opinion. He's one of the library's authors. It is also incredibly unhelpful to anyone who needs to ask the question.
Could someone could point me at appropriate introductory and tutorial links so I can join the ranks of those who nod sagely and marvel at the zen-like brevity of this comment?
I was using AuthenticationHandler to validate out of SQL Server table containing a username and password. Purists please don't lecture me, there are countless businesses that don't or won't use third party OAUTH. I need to convert a username/password pair into a session token that I can use on my Web API methods. That's all. I happen to agree about OAUTH but the people paying for this are not interested in grand unified authentication, they like silos.
Supplementary info
I found a publically accessible PluralSight course on the whole authentication thing. It's by the fellow who wrote the ThinkTecture.AuthenticationHandler and it's quite good as a backgrounder on recent change.
In the course of the material he refers to another PluralSight course on MVC, which has more information on OWIN (which is pure API ie an interface) and Katana (which is Microsoft's implementation of OWIN).
At this point it is clear to me that
There has been a fundamental architecture change for assorted good reasons.
A MessageHandler is not the place to do authentication.
There is a NuGet package called Thinktecture.IdentityModel.Owin.BasicAuthentication which is described as OWIN middleware for HTTP Basic Authentication in OWIN/Katana applications.
My still fuzzy understanding of the new landscape suggests that the middleware package is what I need. NuGet did its thing and now I have to provide some code to insert the middleware into the OWIN middleware chain and more code to actually validate the credentials. As near as I can tell I need to do this in Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseBasicAuthentication("some_realm", (id, secret) =>
{
if (id == secret) //should check database, but never mind right now
{
var claims = new List<Claim> {
new Claim(ClaimTypes.NameIdentifier, id),
new Claim(ClaimTypes.Role, "Foo") //this can come from db also
};
return Task.FromResult<IEnumerable<Claim>>(claims);
}
return Task.FromResult<IEnumerable<Claim>>(null);
});
Assuming I've got this right so far, how do I use it? Do I continue to decorate Web API methods with [Authorize]?
Success! Nearly.
At the moment a request from my test client causes a hit on the breakpoint I've set on the line if (id == secret) and the condition is satisfied because id and secret contain the values sent by my test code. Claims objects are created as per the code above and duly returned, but the test client receives 401 Unauthorized.
This is almost certainly due to a failure to create a principal object. There's some business with a UserManager and an IdentityModel, and it may be possible to customise that to use our own schema.

Custom ClaimsPrincipal in Asp.Net 5 (Mvc 6)

How can I override the default Context.User of type System.Security.Claims.ClaimsPrincipal in Asp.Net 5 (MVC-6)?
I would like to use my customized User-type, so that it's accessible in Controllers (HttpContext.User), as well as in the Razor views (#User.)
Any help is much appreciated. Thanks!:)
The basic answer is don't - it's generally a bad idea to try to implement your own security code; there's lots of options out there that will save you a lot of time up front, and save you a lot of headaches on the back side, too.
The other answer is that you can't - it's built in to the new framework from the beginning.
This is what a User POCO model is for. The Identity framework has operated this way (I think since the beginning), and it mirrors OAuth and most other authentication/authorization systems. It's an incredibly flexible and efficient model.
Instead what I would recommend doing is build your own ClaimTypes and use those in addition to the ones built in to the framework. Depending on how you're authenticating the user, you should be able to add them when you would create the IPrincipal, anyway.
Short answer - assign custom .User to HttpContext in middleware.
Long answer: Where to set custom ClaimsPrincipal for all HttpRequests

WCF Data Service 5.6 + EF 6 Code First + Alpha Provider with Stream Provide

I need some help please. I've tried to implement a stream provider along with EntityFrameworkDataService Provider. I, then, implemented IServiceProvider on my Data Service as it's recommended in this series of article about StreamProvider.
But I'm not able to set up the CSDL file (HasStream Attribute) in code first to suit the needs for having a Service Type StreamProvider enabled.
Is There something I messed up or a way to register properly my StreamProvider with EF6 Code First ? Does I have to implement a MetadaServiceProvider ?
Thanks for helping me.
For information,
I tried to use HasTreamAttribute on my entity and this did not work because IDataServiceProvider was not enumerated into GetService Method implementation of IServiceProvider.
Then, I resolve it by applying [NamedStream("StreamLink")] on my entity, and I was able to intercept IDataServiceStreamProvider2 into GetService Implementation of IServiceProvider.
Hope it helps !