Finally I have time to watch this series that was recommended to me quite some time ago. I'm really enjoying it so far, I love how much detail you are going into!
Man this is really helpful. a lot of stuff online, documentation and such is so abstracted that, as a beginner, I have absolutely no idea what is going on. Getting under the hood makes things more clear. Thank you.
i really like how you explain and remind everything you write, not just like other tutorials they literally just copy paste what they see on the second monitor
This is a really really really good video. It is always good to show the manual stuff then how they translate to the new and modern methods. I really appreciate you taking the time to put this together.
Great job, Anton! I have been looking for somebody to put the entire dotnet core authentication pipeline into one video/course! You did just that. Thank you very much.
@@RawCoding Hi Anton really a great tutorial. But I m stuck at this one part, hope you won't mind helping me out. The problem statement is as follows : I have coded up exactly as you have demonstrated at 20:05 timestamp, now let's consider there is no cookie stored intitally and the very first api I hit is /Username, at this point the middleware steps in, checks that there is no cookie in the request header and throws error. Why doesn't the same thing happen when we hit the /login route, I mean why doesn't the authentication middleware stop it here ?
Is there a proper order to watch this playlist? This video is the first one in the playlist ASP.NET Core Authentication and Authorization Tutorials. In anycase, ill watch them all to to see if it fits what if I can learn something that would help me on what I want to implement! Thanks! Cheers! E.
@@ajitkumarsingh871 he might be using Ctrl + mouse click. That's how it is done in Visual Studio 2022. I do not know what IDE he is using, but it might be using the same shortcuts as VS 2022
Appreciate your knowledge of middleware. I personally feel that a high level view is hard to grasp. There are many options and hard to know what to use or how they differ. I currently have a setup with login via google, twitter, facebook and custom sign-in all with cookies. I was considering azure b2c.. I have watched your other videos on identity server which supported my decision to start as simple as possible and build from there.
That sounds good Anton. One thing I found about external auth is that localhost needed less configuration with services and middleware than a production domain.
Epic content Anton 💪, keep it up. If you could zoom in a little for text in responses, if when they aren't super important that would be a nice addition 😊
Great job, love the way you explained. Most awaited topic for me. Can you please create a playlist to implement Authentication in Web API. Thank you very much.
Since there is a lot of logic going on under the covers matching cookie strings, it would be nice to know which places the strings you chose are important names. For example "set-cookie" seems important. In other cases you used "cookie". It isn't clear where these must match.
"set-cookie" - header which forces the browser to save the cookie or clear it. "cookie" - refers to the authentication scheme (identifier for the "a lot of logic going on under the covers matching cookie strings")
Dude, you are awesome. I am 10 years in this industry and I am learning so much from you. Where did you get your knowledge from? Would you share your secret?
In this specific video there is more than one thing which i haven't got complete grasp on those are are we actually able to create the cookie with session (I mean how does the session work here) do the session have their theoretical timelimit as usual because here are just not at all using the session in the context i just cant understand how does it actually related to sessions (FOR ME THIS IS JUST A COOKIE AUTHENTICATION WITH PROTECTION) OKAY NOW I GET IT THE UNDERLYING MICROSOFT handles the cookies with claimsprinciple applies the protection and also responsible for setting it to the response.headers and we can able to access the session authentication timelimit using the Services which could probably works for setting custom properties on that Cookie
the authentication is stateless for the server (no session, nothing in memory, nothing in nor database) its always created from the cookie which has all the information data protected inside of it. The browser is the on that holds the cookie (aka authentication session). So there are 2 sessions, 1 of which is being used.
I think this is supposed to be the first video in the series, but it looks like you started with some sort of console project already created. What all did you select when starting this project? I need to know how to start with Step 1.
I'd avoid it like the plague - but I think it's good if you have alot of info about the user inside the cookie and you don't want to pass around a enormous cookie back and forth. You can see it stores the session id claim rather than the user. It could also be good for terminating someones sign in session.
@@RawCoding So it stores the User info in the Server and have a tiny cookie that contains only the session id claim, and then the server finds the User BySessionId. Did I get the flow and the idea ?
I think you need to do a longer video series on this subject. Way too much here for one video, much less the myriad of other topics that need to be discussed.
Hi Anton! Your videos are great! I have a question. Why you don't use methods like these: - ctx.Response.Cookies.Append("auth", "anton"); - ctx.Request.Cookies.TryGetValue("auth", out string? authValue); using these framework methods eliminates additional code and helps you focus on authentication topic. it's just a recommendation ) Thank you very much!
probably a dumb question but if you are just exposing an api and the client is not necessarily in a browser does the cookie approach still work or do you need to switch it to something else? jwt perhaps?
Very nice video. Could you do one about more in-depth authentication details like, DefaultSchema, FallbackSchema, Redirect and so on? Thanks for the videos so far.
@@maksadnahibhoolna-wc2ef If you play around with the API you find settings like these, but there is no clear explanation from Microsoft on how and when to use these.
@@octaviandobre Hey just like you said I was trying to play around a little with the code as demonstrated at 20:05 (basically with the use of Authentication service and middleware provided by microsoft). Suppose the situation is that there is no cookie stored initially, then the very first api i hit is /Username, as a result the authentication middleware kicks in and fails to authentiate this api since no cookie is present. Now the question that keeps bugging me is why don't we notice same behaviour when we hit the /login api for very first time (when initially there is no cookie stored), like why doesn't the authenctication middleware kick in and fail to authenticate /login api call ? please help
cookies are automatically handled by browsers tokens are for cross domain access delegation, tho that can still be achieved with cookies in some scenarios
15:55 how am I supposed to get the cookie if u add the middleware that requires cookie? And the only way to get the "login" endpoint (that gives u cookie) is THROUGH that middleware
@@RawCoding I m exactly at this instance of code in visual studio 2022 and it doesn't loads up the implementation. Does it need the resharper plugin to further load the decompiled files ?
Why var authCookie = ctx.Request.Headers.Cookie.FirstOrDefault(x => x.StartsWith("auth=")); can return null but ctx.Request.Cookies.TryGetValue("auth", out string? authCookie); works well?
As soon as I move the authCookie code into the custom middleware section (~ 12:00) I get a null exceptions every time I restart the application, regardless of the endpoint. And that sorta makes sense to me: if the middleware runs for every request, then on the first request this line of code -> var protectedPayload = authCookie.Split("=").Last(); ...is going to throw a null ref exception since the browser can't set a cookie until after it's been told to, no? Thing is, I don't understand how yours doesn't throw a null ref exception. I believe I've copied the code exactly -> using System.Security.Claims; using Microsoft.AspNetCore.DataProtection; var builder = WebApplication.CreateBuilder(args); builder.Services.AddDataProtection(); builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped(); var app = builder.Build(); //Custom middleware app.Use((ctx, next) => { var idp = ctx.RequestServices.GetRequiredService(); var protector = idp.CreateProtector("auth-cookie"); var authCookie = ctx.Request.Headers.Cookie.FirstOrDefault(x => x.StartsWith("auth=")); var protectedPayload = authCookie.Split("=").Last(); var payload = protector.Unprotect(protectedPayload); var parts = payload.Split(":"); var key = parts[0]; var value = parts[1]; var claims = new List(); claims.Add(new Claim(key, value)); var identity = new ClaimsIdentity(claims); ctx.User = new ClaimsPrincipal(identity); return next(); }); //Recognize Authenticated Session app.MapGet("/username", (HttpContext ctx, IDataProtectionProvider idp) => { return ctx.User.FindFirst("usr").Value; }); //Create Authenticate Session app.MapGet("/login", (AuthService auth) => { //Encrypt auth cookie auth.SignIn(); return "Ok"; }); app.Run(); public class AuthService { private readonly IDataProtectionProvider _idp; private readonly IHttpContextAccessor _accessor; public AuthService(IDataProtectionProvider idp, IHttpContextAccessor accessor) { _idp = idp; _accessor = accessor; } public void SignIn() { var protector = _idp.CreateProtector("auth-cookie"); _accessor.HttpContext.Response.Headers["set-cookie"] = $"auth={protector.Protect("usr:john")}"; } } Thank you in advance for any tips.
I have the same issue. It seems to me we wouldn't want that middleware method to run on the /login endpoint, but only on the /username endpoint and any subsequent methods designed to be used after login has taken place, but the way it's written it's going to run on every endpoint. I also don't know why it's not creating an issue for him. It might be that he's rebuilding without restarting the browser, so the user cookie was already set from previous runs, but it's hard to tell exactly just watching the video.
a key is created & stored outside of your app (per app) That key is then used to encrypt/decrypt (protect/unprotect) when app is restarted and key is found in the same place that it would be generated in. Data protection api: learn.microsoft.com/en-us/aspnet/core/security/data-protection/introduction?view=aspnetcore-7.0 Key Management: learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/default-settings?view=aspnetcore-7.0
WHO ARE YOU AND WHAT DID YOU DO TO ANTON?
Anton is gone, you can call me Tony )
Same thought 😂
raw heading
😂
In what sense?
Finally I have time to watch this series that was recommended to me quite some time ago. I'm really enjoying it so far, I love how much detail you are going into!
Hope you enjoy it Pete! And that you’re doing great!
Man this is really helpful. a lot of stuff online, documentation and such is so abstracted that, as a beginner, I have absolutely no idea what is going on. Getting under the hood makes things more clear. Thank you.
Just love the way you explain things from scratch and with perfect pace and explanations. Your work is awesome.
Agree )
@@1dfe-4e68-bd9f Same here!
i really like how you explain and remind everything you write, not just like other tutorials they literally just copy paste what they see on the second monitor
This is a really really really good video. It is always good to show the manual stuff then how they translate to the new and modern methods. I really appreciate you taking the time to put this together.
That was indeed a deep dive on how auth is working under the hood. thanks for this awesome explanation!
Great job, Anton! I have been looking for somebody to put the entire dotnet core authentication pipeline into one video/course! You did just that. Thank you very much.
Glad you enjoyed it, don't forget to share!
@@RawCoding Hi Anton really a great tutorial. But I m stuck at this one part, hope you won't mind helping me out.
The problem statement is as follows : I have coded up exactly as you have demonstrated at 20:05 timestamp, now let's consider there is no cookie stored intitally and the very first api I hit is /Username, at this point the middleware steps in, checks that there is no cookie in the request header and throws error.
Why doesn't the same thing happen when we hit the /login route, I mean why doesn't the authentication middleware stop it here ?
Fantastic video! I've used many sources to learn about authentication but this is exactly what I needed. Good Job!
great video Anton. You and nick are a credit to the RUclips tech space. Love what you do
By nick do you mean Nick Chapsas?
There's Patrick God and there's you, going into all the little details (which I absolutely love)
Is there a proper order to watch this playlist? This video is the first one in the playlist ASP.NET Core Authentication and Authorization Tutorials. In anycase, ill watch them all to to see if it fits what if I can learn something that would help me on what I want to implement! Thanks!
Cheers!
E.
Great thanks anton, definitely going to watch more of your videos
Glad you enjoyed
I laughed too hard at 16:20 when you casually scrolled through 500 lines of code for a supposed key-value store. awesome video :)
Hey At 20:41 from here how did Anton transition to the Implementation of AuthenticationService from this point ?
@@ajitkumarsingh871 he might be using Ctrl + mouse click. That's how it is done in Visual Studio 2022. I do not know what IDE he is using, but it might be using the same shortcuts as VS 2022
Damn, what a great explanation, especially the first part. Spasibo 🤝
Appreciate your knowledge of middleware. I personally feel that a high level view is hard to grasp. There are many options and hard to know what to use or how they differ. I currently have a setup with login via google, twitter, facebook and custom sign-in all with cookies. I was considering azure b2c.. I have watched your other videos on identity server which supported my decision to start as simple as possible and build from there.
I'll be covering external auth a bit better in these series
That sounds good Anton. One thing I found about external auth is that localhost needed less configuration with services and middleware than a production domain.
Epic content Anton 💪, keep it up.
If you could zoom in a little for text in responses, if when they aren't super important that would be a nice addition 😊
Cheers, and yeah that was a bit of a mistake from me )
such an amazing video! removes the ambiguity so well! thank you dude ❤️
This channel is so underrated
Thanks a lot for updating this to .Net 7
Great explanation of claims. At last. Thank you!
Glad you liked it :)
I loved the explanation and as i practiced the code with the session, i felt like i learned a lot.
Awesome explanation! Thanks Anton!
Thank you for watching!
Your video was very helpful, I'm still learning and getting the hang of it still. I'm into House and EDM. I look forward to seeing more of your
🎶
Great job, love the way you explained. Most awaited topic for me.
Can you please create a playlist to implement Authentication in Web API.
Thank you very much.
Cheers, and keep watching the playlist if you’d like to learn how to authenticate apis
Since there is a lot of logic going on under the covers matching cookie strings, it would be nice to know which places the strings you chose are important names. For example "set-cookie" seems important. In other cases you used "cookie". It isn't clear where these must match.
"set-cookie" - header which forces the browser to save the cookie or clear it.
"cookie" - refers to the authentication scheme (identifier for the "a lot of logic going on under the covers matching cookie strings")
wow.. thank you so much for this 🥳
Thank you for watching, you’re awesome!
Dude, you are awesome. I am 10 years in this industry and I am learning so much from you. Where did you get your knowledge from? Would you share your secret?
Thanks, my secrets are - learning Clojure & reading other peoples code
Great content, looking foreward for the next video 😀
Just discovered you, you are great dude, keep it up
Thanks for the video. What editor do you use ?
Rider
In this specific video
there is more than one thing which i haven't got complete grasp on
those are
are we actually able to create the cookie with session (I mean how does the session work here)
do the session have their theoretical timelimit as usual
because here are just not at all using the session in the context
i just cant understand how does it actually related to sessions
(FOR ME THIS IS JUST A COOKIE AUTHENTICATION WITH PROTECTION)
OKAY NOW I GET IT THE UNDERLYING MICROSOFT
handles the cookies with claimsprinciple applies the protection and also responsible for setting it to the response.headers
and we can able to access the session authentication timelimit using the Services which could probably works for setting custom properties on that Cookie
the authentication is stateless for the server (no session, nothing in memory, nothing in nor database) its always created from the cookie which has all the information data protected inside of it. The browser is the on that holds the cookie (aka authentication session). So there are 2 sessions, 1 of which is being used.
@@RawCoding Thank You SO much for this great Explanation🙌🙌🙌
I think this is supposed to be the first video in the series, but it looks like you started with some sort of console project already created. What all did you select when starting this project? I need to know how to start with Step 1.
It’s an empty asp.net core app
Dude, this is gold
Thank you for watching
Great! I really enjoyed. Hope more videos Net auth, and Vuejs also ✅⚡️
You got some good posters there bro😂
man of culture
Awesome, you're one of the best!
enjoyed every bit of your video , thank you for the great content
Organization is a key to success
Thank you Anton one more time.
What would be a scenario to store Authentication session (cookie) in the BE 23:49 ?
I'd avoid it like the plague - but I think it's good if you have alot of info about the user inside the cookie and you don't want to pass around a enormous cookie back and forth. You can see it stores the session id claim rather than the user.
It could also be good for terminating someones sign in session.
@@RawCoding So it stores the User info in the Server and have a tiny cookie that contains only the session id claim, and then the server finds the User BySessionId. Did I get the flow and the idea ?
Sounds like you do!
@@RawCoding thanks a million
It's amazing! Good explanation! I really enjoy this video!
Thank you very match!
This is absolutely great. Thanks a lot!
I think you need to do a longer video series on this subject. Way too much here for one video, much less the myriad of other topics that need to be discussed.
Feel free to leave bullet points of what you’d like me to cover or perhaps questions that you have, there will be more videos.
@@RawCoding Authentication and Authorization in Microservices Arch would be nice video
Hi Anton! Your videos are great! I have a question. Why you don't use methods like these:
- ctx.Response.Cookies.Append("auth", "anton");
- ctx.Request.Cookies.TryGetValue("auth", out string? authValue);
using these framework methods eliminates additional code and helps you focus on authentication topic. it's just a recommendation )
Thank you very much!
Good suggestion, I didnt focus on correctness/safety for the introductory example
This was great video. Thank you so much!
probably a dumb question but if you are just exposing an api and the client is not necessarily in a browser does the cookie approach still work or do you need to switch it to something else? jwt perhaps?
Cookies and Tokens are just a string in a header
Is there any tutorial from you or someone you know that actually covers Authentication in Blazor and explain it well?
Nope, I'll do it at some point
Thank you for this awsom video
I really like this video. Thank you very much for sharing this.
Advanced but quality content. Thanks.
glad you liked it
This is insane! Thank you!
10/10 software engineering points for content, 11/10 man of culture points for a butt pic on a background,
Awesome content!! Thank you!
Very nice video. Could you do one about more in-depth authentication details like, DefaultSchema, FallbackSchema, Redirect and so on? Thanks for the videos so far.
That is possible
@octaviandobre Did you find any resources over these topics to dive deeper into ? Also where did you heard about FallbackSchema from ?
@@RawCoding are you planning to make videos on these topics anytime soon ?
@@maksadnahibhoolna-wc2ef If you play around with the API you find settings like these, but there is no clear explanation from Microsoft on how and when to use these.
@@octaviandobre Hey just like you said I was trying to play around a little with the code as demonstrated at 20:05 (basically with the use of Authentication service and middleware provided by microsoft).
Suppose the situation is that there is no cookie stored initially, then the very first api i hit is /Username, as a result the authentication middleware kicks in and fails to authentiate this api since no cookie is present.
Now the question that keeps bugging me is why don't we notice same behaviour when we hit the /login api for very first time (when initially there is no cookie stored), like why doesn't the authenctication middleware kick in and fail to authenticate /login api call ?
please help
Great video! Thanks!
Thank you for watching :)
Amazing content. Subscribed. Simply Brilliant.
Buy why 66k subscribers only :(,
Hey Anton, How about some RUclips sweetness on Blazor Server Authentication??
Nice video :) but what happen to your hair?
Great job Man
suppose in your aks cluster one pod generated the cookie will get recognized by another pod if the cookie is sent to it?
Yes, if you share protection keys
Looking good! 👍🏽
Thank you very much!
Really nice video!!!
Антон, спасибо
Пожалуйста 🙏
NICE VIDEO!!
Excellent video
How are you getting into the ASP.NET sources in this video? When I try it, I only see the type definitions.
Find Implementation keybind (usually F12)
@@RawCoding I tried out Rider and I see that it has a decompiler. So that is what you were using. That solves that mystery.
Thanks for the videos!
Great video. Thanks
thanks you the video was awesome!
how is this any different than a jason web token? other than the encription/decription algorithm?
cookies are automatically handled by browsers
tokens are for cross domain access delegation, tho that can still be achieved with cookies in some scenarios
Why do most Oauth implementations store the token in a Cookie vs the Authentication Header Variable?
Can we use this sort of cookie authentication if our front end is a mobile app, like Blazor hybrid ?
Yes
15:55
how am I supposed to get the cookie if u add the middleware that requires cookie? And the only way to get the "login" endpoint (that gives u cookie) is THROUGH that middleware
the middleware attempts to load the ClaimsPrinciple from the cookie, it doesn't do any authorization yet.
@@RawCoding my bad. I got confused in my own thoughts. Thank u for what u're doing Jake Gyllenhaal
Is AddDataProtection still needed if using jwt token instead of cookie since the jwt token is somewhat encrypted ?
ruclips.net/video/8FvN5bhVYxY/видео.html
You’ll need an asymmetric key to sign the token.
Great! It works in .NET 6?
Yes
At 20:41 from here how did you transition to the Implementation of SignInAsync() function ?
Perhaps he was using Ctrl + mouse click
The action is called: go to definition or go to implementation.
@@RawCoding I m exactly at this instance of code in visual studio 2022 and it doesn't loads up the implementation. Does it need the resharper plugin to further load the decompiled files ?
You are the best!
Thank you!
Legend
Why var authCookie = ctx.Request.Headers.Cookie.FirstOrDefault(x => x.StartsWith("auth=")); can return null
but ctx.Request.Cookies.TryGetValue("auth", out string? authCookie); works well?
thank you so much
How many legs? Three 🤔... it makes sense 14:39
thanks bro
no thank you!
PREACH!!!
As soon as I move the authCookie code into the custom middleware section (~ 12:00) I get a null exceptions every time I restart the application, regardless of the endpoint. And that sorta makes sense to me: if the middleware runs for every request, then on the first request this line of code ->
var protectedPayload = authCookie.Split("=").Last();
...is going to throw a null ref exception since the browser can't set a cookie until after it's been told to, no?
Thing is, I don't understand how yours doesn't throw a null ref exception. I believe I've copied the code exactly ->
using System.Security.Claims;
using Microsoft.AspNetCore.DataProtection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDataProtection();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped();
var app = builder.Build();
//Custom middleware
app.Use((ctx, next) =>
{
var idp = ctx.RequestServices.GetRequiredService();
var protector = idp.CreateProtector("auth-cookie");
var authCookie = ctx.Request.Headers.Cookie.FirstOrDefault(x => x.StartsWith("auth="));
var protectedPayload = authCookie.Split("=").Last();
var payload = protector.Unprotect(protectedPayload);
var parts = payload.Split(":");
var key = parts[0];
var value = parts[1];
var claims = new List();
claims.Add(new Claim(key, value));
var identity = new ClaimsIdentity(claims);
ctx.User = new ClaimsPrincipal(identity);
return next();
});
//Recognize Authenticated Session
app.MapGet("/username", (HttpContext ctx, IDataProtectionProvider idp) =>
{
return ctx.User.FindFirst("usr").Value;
});
//Create Authenticate Session
app.MapGet("/login", (AuthService auth) =>
{
//Encrypt auth cookie
auth.SignIn();
return "Ok";
});
app.Run();
public class AuthService
{
private readonly IDataProtectionProvider _idp;
private readonly IHttpContextAccessor _accessor;
public AuthService(IDataProtectionProvider idp, IHttpContextAccessor accessor)
{
_idp = idp;
_accessor = accessor;
}
public void SignIn()
{
var protector = _idp.CreateProtector("auth-cookie");
_accessor.HttpContext.Response.Headers["set-cookie"] = $"auth={protector.Protect("usr:john")}";
}
}
Thank you in advance for any tips.
I have the same issue. It seems to me we wouldn't want that middleware method to run on the /login endpoint, but only on the /username endpoint and any subsequent methods designed to be used after login has taken place, but the way it's written it's going to run on every endpoint. I also don't know why it's not creating an issue for him. It might be that he's rebuilding without restarting the browser, so the user cookie was already set from previous runs, but it's hard to tell exactly just watching the video.
Thank youuuuuuuu
Who are you? Where is Anton??
Names Tony, we’re gonna be making real programming videos now!
salam qaqa
appreciate it
Hey mate! After this series would you mind doing videos on different data structures and algorithms
maybe, check this out tho: ruclips.net/video/nVRSiitEPZc/видео.html
Thank you :)
Thank you for this amazing explanation about how .NET auth works. It's just terrible and not explained anywhere properly.
this protector is how unprotect? even I restarted the backend still able to unprotect, how is keeping the salt or key?
a key is created & stored outside of your app (per app) That key is then used to encrypt/decrypt (protect/unprotect) when app is restarted and key is found in the same place that it would be generated in.
Data protection api: learn.microsoft.com/en-us/aspnet/core/security/data-protection/introduction?view=aspnetcore-7.0
Key Management: learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/default-settings?view=aspnetcore-7.0
@@RawCoding thanks for the answer, yes I have found the folder and changed the new tests :) it worked
Hola alguien puede porporcionarme el poryecto para ir siguiendo el curso. Gracias
awesome
how the hell do we remember which method takes which parameter, .net is so much about mugging what microsoft has done.
Any language that has skds or libraries will be like that regardless of who makes it.
14:39 How many legs? 🤣🤣🤣
I have paid for the source code but i didn't get source code. please help me how to download this source code.
Hi there you should have gotten the link in a message , please dm me on discord if you have any problems
But I have a problem
He said 3 legs???
Why did you left Microsoft? :P
Never been )))