OpenID Connect is, it solves a different problem, and it's about authentication. So, the idea is that maybe this, this application doesn't need to talk to a back-end service. At least not in the first place. So what, but, but it needs to know who the user is, so. In OpenID Connect you're doing an, a round trip to a so-called authentication server, you type in the password at the authentication server and this returns a token back to the client application that allows it, to validate, your identity. And maybe at some point later, they're using OAuth to get another token to talk to a vacant service, but that, you know, out of two distinct a use case. OpenIDConnect is for Authentication and OAuth for delegating authorization.
2. Contains expiry
3. Signed
4. Client requests a token , issuer issues a token and the resource(API) consumes. The resource has a trust relationship with the token.
5. Are really small , so we can use them in mobile scenarios as well
Subject is the unique identifier of the user. Issuer does this to create a token
Consumer Level Validation can be done as follows
Use JwtSecurityHandler class for creating and validating a token. If the token validates to true then a claimprincipal object is created.ie: the USER obj that we use.
Call the Authorization endpoint and specify username and password at Identity provider level and get back authentication token, pass this token to Token endpoint and specify authenticate the client to get back a JWT token or the ID token , it contains the issuer and the Audience fields that specify if the token is actually meant for the API. Oauth didnt have this feature. Person who gets the authentication token could pass this token to other API's and would impersonate the user. But now each API knows whether the token sent is actually meant for them.
Basic working : user authenticates at the Authorization endpoint(IDP) and after consent is given a authorization code is issued to the client. Client call the Token endpoint passing this code , its clientid and secret to authenticate itself. Once the client is authenticated it gets back ID Token (JWT), access token and optional refresh token.
What most of them are really doing, I just alluded to that, is something called OpenID Connect. So, when you go, for example, to the Google's API documentation page they said that yeah we use OAuth 2. 0 for Login. But hold on, we are actually doing OpenID Connect but we, we're not calling it that way because we don't want to confuse people, okay? So, in other words OAuth2 itself is not good enough for authentication. You can make it good enough for authentication, but that involves two things. One is the user info endpoint. That should be in some sort of standard format. And one is the introduction of an extra token type, and that is all specified by OpenID Connect. So, OpenID Connect is a specification that is, that basically aims at the target that you don't need to know any specifics about the authentication provider A priori. Like you've just seen the screen that I've shown you from OAuth IO, they have support for 50 plus providers. The idea of Open, ID connect is that you don't need to have special case support for providers, because they are compatible with each other. So, Open, OpenID Connect builds on top of OAuth. They, they use the authorization code flow for server based applications and the implicit flow for client based applications. They add some, they add some constraints to OAuth2 as well. They, they add some new concepts like the user info endpoint I just talked about, and a new token type called the ID token which I'll show you in a second what that exactly is. And they added some, some other additional features which are missing from the OAuth core spec, like, for example, how can you discover an, an OpenID Connect provider. How can you a dynamically with an Open OpenID Connect provider. And also when we're talking about log in, we also need to talk about session management. So, for example, how do we log out again? And again, session management is not part at all of OAuth. So again, we need that that extra spec that is very, very similar to WS Federation, federated sign out or single sign out in, in the sample protocol for example, we just need these features.
So, let me show you the OpenID Connect Players. So you've seen here we have the user agent and the client. So, there's always a user agent involved. And either that's a browser, like a classical browser for Web applications, or it's of a few that is used in conjunction with a client application, like a native application or a, you know, a user agent based application. And you have the authorization endpoint and the token endpoint, and we know them already from OAuth. So, I said OpenID Connect is building on top of OAuth. So, when now an application like a client wants to initiate authentication, what it does is, it uses the standard OAuth messages to talk to an authorization endpoint. And the mindset here is really, do you want to allow the client to get access to your user profile and that includes authentication. So, when we're doing a get request to the authorized endpoint. We are passing in the client ID.
We are passing in the callback URI. And now what OAuth does is it defines scopes. So, an OpenID Connect request must start with a scope called OpenID. And then there are more things you can attach to that, like profile or e-mail, and I have a table later on that it shows you which types of values you can put in there. But OpenID profile means that you get access to the user's profile, like first name, last name, email address, and these things. Then, response time equals code, meaning we're doing the code flow here, and the state parameters again for anti CSRF attacks. Now, if the user is not authenticated already, then we need to make a round trip to the IDP. And again, just for reference here, these are the values of the scopes, like profile, email, address, phone and offline access, which means refresh token. Then again they are all specified in the OpenID Connect specification. But much more importantly, if the user is not authenticated, now we are making the round trip to the identity provider, and again, the user types in his user name and password into a UI. Now when authentication has succeeded, the consent screen is shown, just like in extended OAuth. And as I said, the mindset here is really like, do you want to allow this application called WebApp access to your profile? And if you click Yes here, you get back the authorization code. And then you use the authorization code to get a token response. So again, declined authenticates with the token endpoint using his client id and secret passes in the authorization code. And when all that security checks have succeeded we get back, the token response. And now, you see here, there's something special.
For the access token is the standard OAuth access token, which is basically, which can be used to talk to the user info endpoint. So, nothing special here with regards to OAuth2. Just the refresh token, which gives you longer lived access to the user info endpoint. But, there's a special token now called the ID token, and that one was missing from from the naive OAuth authentication implementations I showed you earlier. So the ID token is really a token that is meant for the client. So the client the client's responsibility is now to immediately validate this ID token. And what's inside of the ID token? Well, basically, there are four very important claims. A, where does the token come from? So, does it come from the OpenID Connect provider I just talked to. The subject identifies the user. The audience identifies for whom this token is for, and this token must be for the client that initiated the request. So, that allows the client to make sure that this token is actually for his own application. That was a feature that was missing in the naive implementation I showed you at the beginning. And obviously an expiration, so, you know, these tokens cannot be, kept alive forever. And the token is signed, obviously. And the client must validate the token, at this point. So, once the client has validated the ID token, he knows that the response that came back from the authorization server was actually really for his own application and is basically a fresh interaction because there's an expiration value involved, and so on and so forth.
So basically this, this is the, the very, very important extra feature that OpenID Connect adds on top of OAuth. So, we can really do authentication and not just, you know, assume once we get back some token from the authorization server, then authentication must have succeeded. But we cannot check it. With the ID token, we can really validate that authentication succeeded. And that, you know, all, all of the players are the ones, are legitimate, and not some, you know, part got substituted in the process. Okay, so now, once we know that the response was legitimate we already know that's a very important point here. If you already know who the user is. That's the subject claim, yeah? And if, if that's all we need to know, like having a unique handle for that user, then we are done. But if we want to know more about a user, like his first name, last name, and so on, then you would go to user info endpoint. Would use the access token to access the user info endpoint and get back the additional profile information about the user.
So, so that's OpenID Connect the authorization code flow. There's also an im, an implicit flow, which works exactly the same as the implicit flow with OAuth 2. Just adding the ID token user info endpoint to the mix. And that's basically how OpenID Connect works. And you can, you can see then I deliberately draw these different players into separate boxes, like the identity provider, the authorization endpoint and so on because OpenID allows you to basically separate them. So, like the identity provider could be like an Intranet server whereas the authorization endpoint is accessible for from the Internet or the user info endpoint and so on. Which also allows you, or allows for architectures where the credential database is separate from the profile database, for example. Okay, so, the last, really last step now would be the user info response. And again, this is a standardized format meaning the claims here, sub, name, email, they are, they are specified by OpenID Connect and the idea is that you simply get back a JSON encoded name value pair that includes the profile information.
OPENID Extras:
1. UserInfo Endpoint :when all the claims are included in the access token the size increases. So call this endpoint to access additional details.
2. ID token:
3. Discovery Endpoint:
Summary
https://app.pluralsight.com/player?course=oauth2-json-web-tokens-openid-connect-introduction&author=dominick-baier&name=oauthintro-m6-openid&clip=4&mode=live
You've seen that OpenID Connect builds on top of OAuth2. Adds a number of extra features, like standard scopes and claims. Like, that the token type is fixed to chart. The ID token concept is something they added as a standard spec component, and the user info endpoint, yeah? And the idea as, as, as I said earlier, is that once this all is in place, your application, you know, can use arbitrary OpenID Connect providers to authenticate without you having to write extra or special case code. Li, like it, it works today with OAuth2 authentication because there's no standard how to do authentication with OAuth2. OpenID Connect is not yet done. At least you know, there are a number of specs that make up OpenID Connect. One is called the basic profile. That is pretty stable now and it's, it's expected to not change substantially anymore until the spec is done. There are additional specs which are still under heavy development especially the things like dynamic registration. Discovery, and session management, and so on. But, yeah, going forward, for Internet-based applications OpenID Connect is the new protocol to do authentication. And, in the long term, will replace WS Federation, WS-Trust, and, similar 2p.
.AddCookie(o=>
{
o.LoginPath = "account/signIn";
});
Httpcontext has claims principal, when we have different authentication mechanisms we will have more than one claimsIdentity, in this case we are filling in claims identity for cookie based auth
we create a claims principal using the claimsIdentity and sign in using our httpcontext.So our httpcontext will have claims principal with claims identity array with all the different claims. We have set default auth scheme to cookie, so this cookie will have different options like shud it be persistent or not we can customize based on our needs.
public async Task<IActionResult> Login(LoginModel model)
{
// we get the user
var user = this.UserRepository.GetByUsernameAndPassword(model.Username, model.Password);
if (user == null) return Unauthorized();
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Role, user.Role),
new Claim("FavoriteColor", user.FavoriteColor)
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties { IsPersistent = model.RememberLogin });
return LocalRedirect(model.ReturnUrl);
}
return LocalRedirect(model.ReturnUrl); makes sure that the redirect happens to our own URL.
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/");
}
Signout by specifying the scheme name and then just redirect to needed url
when we sign in a user, a cookie is set. This cookie is called the identity cookie. Typically, a web application is stateless, and processes requests of potentially many concurrent users. A cookie is a way to know which request came from which user. Once we sign in the user, our application puts all user information in the cookie, including the claims, and encrypts it using a key only the server‑side application has. That same key is needed to decrypt the cookie. So when the cookie arrives in the browser, nobody can read it. Cookies are sent along automatically with each new request through the same server. When the server gets it, it will decrypt it using the key, read the user information, and reconstruct the ClaimsPrincipal object that is made available in the application. In ASP.NET Core, encryption works with a framework called data protection, which is used behind the scenes, which is automatically configured when you add cookie authentication support to your application. Data protection takes care of storing the key securely, and it rotates the key periodically.
when we logout the cookie dissapears.
Get the client id and secret from google. Right click on the project and click on manage user secrets.
The secrets file can be used by Configuration object. but this file doesnt get checked in.
Install this nuget to install the google auth middleware.
Since we have set the default auth scheme to cookie this will work with cookie auth. We need to configure it to use google to signin. With a call to AddGoogle, an authentication scheme is added to the application. The name of the scheme is simply Google by default. Would we run the application now, it would just work as before, without Google.
Because we have set the default scheme to the cookie scheme. That means that all scheme actions are done on that scheme. There are three scheme actions. Authenticate is about how the claims principle gets reconstructed on every request. Since we're using the cookie to do that, we want to keep it as it is. The challenge determines what happens if the user tries to access a resource for which authentication is required. We already saw that the cookie scheme will redirect to account/login by default when that happens. We want to change that now, since we want Google to take care of logins. Forbid determines what happens if the user accesses a resource she can't access because she doesn't have the rights. The cookie scheme will redirect to account/accessdenied by default, and that's still what we want
So we need to set the scheme actions accordingly.
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; // for reconstructing claims principaln
o.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;// for login use google scheme
o.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;// use forbidden url from this scheme
})
services.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; // for reconstructing claims principaln
//commented this code as when we use multiple login providers then this will always
// login from google
//o.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;// for login use google scheme
//o.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;// use forbidden url from this scheme
})
.AddCookie(o =>
{
o.LoginPath = "/Account/Login";
}).AddCookie(ExternalAuthenticationDefaults.AuthenticationScheme)
.AddGoogle(options =>
{
// we add a new cookie scheme and tell google to use this scheme when login
// we want google claims to be in a separate cookie
// check login from google to get more details
// when we sign in using google this cookie will have all the details.
// we read this cookie and create a new claims principal that will contain all
//the common claims needed by all login methods, since google will contain only its claims
options.SignInScheme = ExternalAuthenticationDefaults.AuthenticationScheme;
options.ClientId = Configuration["Google:ClientId"];
options.ClientSecret = Configuration["Google:Secret"];
});
Purpose Of JWT
1. Contain info about the issuer and claims2. Contains expiry
3. Signed
4. Client requests a token , issuer issues a token and the resource(API) consumes. The resource has a trust relationship with the token.
5. Are really small , so we can use them in mobile scenarios as well
Subject is the unique identifier of the user. Issuer does this to create a token
Consumer Level Validation can be done as follows
Use JwtSecurityHandler class for creating and validating a token. If the token validates to true then a claimprincipal object is created.ie: the USER obj that we use.
OAuth 2
The people that that build OAuth one they worked on a hosting company which didn't support SSL for example there. So the whole OAuth one protocol couldn't rely on any sort of transport protection, which us made them introduce pretty heavy crypto to rebuild some of the protection features. The other thing was that OAuth 1. 0 was designed to work with PHP 4, for example, which also had some constraints and, In the end, OAuth 1 0 was more complicated than its authors wanted it to be.
Normally cars (expensive) have 2 sets of keys a master key and a valet parking key. They valet parking key has limited access to the cars resources. ex; It can drive only a few kms. So Oauth2 is all about creating a valet parking key so that the client can access the resource on behalf of the user with limited features.
Authorization flow.. User authenticates itself , gets authentication code, sends authentication code and client credentials and authenticates itself and gets back access token.
In Implicit flow the client is a browser or mobile device, so it does not have to authenticate itself as to authenticate it would need to save its credentials hardcoded on the browser or the mobile device which is not safe.
OpenID Connect
Call the Authorization endpoint and specify username and password at Identity provider level and get back authentication token, pass this token to Token endpoint and specify authenticate the client to get back a JWT token or the ID token , it contains the issuer and the Audience fields that specify if the token is actually meant for the API. Oauth didnt have this feature. Person who gets the authentication token could pass this token to other API's and would impersonate the user. But now each API knows whether the token sent is actually meant for them.
Basic working : user authenticates at the Authorization endpoint(IDP) and after consent is given a authorization code is issued to the client. Client call the Token endpoint passing this code , its clientid and secret to authenticate itself. Once the client is authenticated it gets back ID Token (JWT), access token and optional refresh token.
What most of them are really doing, I just alluded to that, is something called OpenID Connect. So, when you go, for example, to the Google's API documentation page they said that yeah we use OAuth 2. 0 for Login. But hold on, we are actually doing OpenID Connect but we, we're not calling it that way because we don't want to confuse people, okay? So, in other words OAuth2 itself is not good enough for authentication. You can make it good enough for authentication, but that involves two things. One is the user info endpoint. That should be in some sort of standard format. And one is the introduction of an extra token type, and that is all specified by OpenID Connect. So, OpenID Connect is a specification that is, that basically aims at the target that you don't need to know any specifics about the authentication provider A priori. Like you've just seen the screen that I've shown you from OAuth IO, they have support for 50 plus providers. The idea of Open, ID connect is that you don't need to have special case support for providers, because they are compatible with each other. So, Open, OpenID Connect builds on top of OAuth. They, they use the authorization code flow for server based applications and the implicit flow for client based applications. They add some, they add some constraints to OAuth2 as well. They, they add some new concepts like the user info endpoint I just talked about, and a new token type called the ID token which I'll show you in a second what that exactly is. And they added some, some other additional features which are missing from the OAuth core spec, like, for example, how can you discover an, an OpenID Connect provider. How can you a dynamically with an Open OpenID Connect provider. And also when we're talking about log in, we also need to talk about session management. So, for example, how do we log out again? And again, session management is not part at all of OAuth. So again, we need that that extra spec that is very, very similar to WS Federation, federated sign out or single sign out in, in the sample protocol for example, we just need these features.
OpenID Code Flow
https://www.youtube.com/watch?v=lwaudf2h8FY -- Authorization vs Implicit
https://auth0.com/docs/flows -- Docs
We are passing in the callback URI. And now what OAuth does is it defines scopes. So, an OpenID Connect request must start with a scope called OpenID. And then there are more things you can attach to that, like profile or e-mail, and I have a table later on that it shows you which types of values you can put in there. But OpenID profile means that you get access to the user's profile, like first name, last name, email address, and these things. Then, response time equals code, meaning we're doing the code flow here, and the state parameters again for anti CSRF attacks. Now, if the user is not authenticated already, then we need to make a round trip to the IDP. And again, just for reference here, these are the values of the scopes, like profile, email, address, phone and offline access, which means refresh token. Then again they are all specified in the OpenID Connect specification. But much more importantly, if the user is not authenticated, now we are making the round trip to the identity provider, and again, the user types in his user name and password into a UI. Now when authentication has succeeded, the consent screen is shown, just like in extended OAuth. And as I said, the mindset here is really like, do you want to allow this application called WebApp access to your profile? And if you click Yes here, you get back the authorization code. And then you use the authorization code to get a token response. So again, declined authenticates with the token endpoint using his client id and secret passes in the authorization code. And when all that security checks have succeeded we get back, the token response. And now, you see here, there's something special.
For the access token is the standard OAuth access token, which is basically, which can be used to talk to the user info endpoint. So, nothing special here with regards to OAuth2. Just the refresh token, which gives you longer lived access to the user info endpoint. But, there's a special token now called the ID token, and that one was missing from from the naive OAuth authentication implementations I showed you earlier. So the ID token is really a token that is meant for the client. So the client the client's responsibility is now to immediately validate this ID token. And what's inside of the ID token? Well, basically, there are four very important claims. A, where does the token come from? So, does it come from the OpenID Connect provider I just talked to. The subject identifies the user. The audience identifies for whom this token is for, and this token must be for the client that initiated the request. So, that allows the client to make sure that this token is actually for his own application. That was a feature that was missing in the naive implementation I showed you at the beginning. And obviously an expiration, so, you know, these tokens cannot be, kept alive forever. And the token is signed, obviously. And the client must validate the token, at this point. So, once the client has validated the ID token, he knows that the response that came back from the authorization server was actually really for his own application and is basically a fresh interaction because there's an expiration value involved, and so on and so forth.
So basically this, this is the, the very, very important extra feature that OpenID Connect adds on top of OAuth. So, we can really do authentication and not just, you know, assume once we get back some token from the authorization server, then authentication must have succeeded. But we cannot check it. With the ID token, we can really validate that authentication succeeded. And that, you know, all, all of the players are the ones, are legitimate, and not some, you know, part got substituted in the process. Okay, so now, once we know that the response was legitimate we already know that's a very important point here. If you already know who the user is. That's the subject claim, yeah? And if, if that's all we need to know, like having a unique handle for that user, then we are done. But if we want to know more about a user, like his first name, last name, and so on, then you would go to user info endpoint. Would use the access token to access the user info endpoint and get back the additional profile information about the user.
So, so that's OpenID Connect the authorization code flow. There's also an im, an implicit flow, which works exactly the same as the implicit flow with OAuth 2. Just adding the ID token user info endpoint to the mix. And that's basically how OpenID Connect works. And you can, you can see then I deliberately draw these different players into separate boxes, like the identity provider, the authorization endpoint and so on because OpenID allows you to basically separate them. So, like the identity provider could be like an Intranet server whereas the authorization endpoint is accessible for from the Internet or the user info endpoint and so on. Which also allows you, or allows for architectures where the credential database is separate from the profile database, for example. Okay, so, the last, really last step now would be the user info response. And again, this is a standardized format meaning the claims here, sub, name, email, they are, they are specified by OpenID Connect and the idea is that you simply get back a JSON encoded name value pair that includes the profile information.
OPENID Extras:
1. UserInfo Endpoint :when all the claims are included in the access token the size increases. So call this endpoint to access additional details.
2. ID token:
3. Discovery Endpoint:
Summary
https://app.pluralsight.com/player?course=oauth2-json-web-tokens-openid-connect-introduction&author=dominick-baier&name=oauthintro-m6-openid&clip=4&mode=live
You've seen that OpenID Connect builds on top of OAuth2. Adds a number of extra features, like standard scopes and claims. Like, that the token type is fixed to chart. The ID token concept is something they added as a standard spec component, and the user info endpoint, yeah? And the idea as, as, as I said earlier, is that once this all is in place, your application, you know, can use arbitrary OpenID Connect providers to authenticate without you having to write extra or special case code. Li, like it, it works today with OAuth2 authentication because there's no standard how to do authentication with OAuth2. OpenID Connect is not yet done. At least you know, there are a number of specs that make up OpenID Connect. One is called the basic profile. That is pretty stable now and it's, it's expected to not change substantially anymore until the spec is done. There are additional specs which are still under heavy development especially the things like dynamic registration. Discovery, and session management, and so on. But, yeah, going forward, for Internet-based applications OpenID Connect is the new protocol to do authentication. And, in the long term, will replace WS Federation, WS-Trust, and, similar 2p.
Authorization Flow
Implicit Flow
Client Credentials
Setting up
we have to specify a default scheme name for asp.net core to carry different actions
when we have many schemes we need to specify a default one. Instead of using magic strings use the CookieAuthenticationDefaults etc.
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
The authorize attribute checks the default scheme we just configured. If you wanted to check another scheme, you can do so by setting the name of the scheme you want to check in the authentication schemes property.
or instead apply it globally
services.AddControllersWithViews(options => options.Filters.Add(new AuthorizeFilter()));
or instead apply it globally
services.AddControllersWithViews(options => options.Filters.Add(new AuthorizeFilter()));
or to all razor pages
services.AddRazorPages().AddMvcOptions(options => options.Filters.Add(new AuthorizeFilter()));
services.AddRazorPages().AddMvcOptions(options => options.Filters.Add(new AuthorizeFilter()));
when we try to access a controller with Authorize attribute, we get the following screen. The default cookie scheme is telling us to redirect to the Url. So we need to configure that in the cookie scheme.
Cookie Authenticaiton
We can change that default login path also..AddCookie(o=>
{
o.LoginPath = "account/signIn";
});
Httpcontext has claims principal, when we have different authentication mechanisms we will have more than one claimsIdentity, in this case we are filling in claims identity for cookie based auth
we create a claims principal using the claimsIdentity and sign in using our httpcontext.So our httpcontext will have claims principal with claims identity array with all the different claims. We have set default auth scheme to cookie, so this cookie will have different options like shud it be persistent or not we can customize based on our needs.
public async Task<IActionResult> Login(LoginModel model)
{
// we get the user
var user = this.UserRepository.GetByUsernameAndPassword(model.Username, model.Password);
if (user == null) return Unauthorized();
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Role, user.Role),
new Claim("FavoriteColor", user.FavoriteColor)
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties { IsPersistent = model.RememberLogin });
return LocalRedirect(model.ReturnUrl);
}
return LocalRedirect(model.ReturnUrl); makes sure that the redirect happens to our own URL.
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/");
}
Signout by specifying the scheme name and then just redirect to needed url
when we sign in a user, a cookie is set. This cookie is called the identity cookie. Typically, a web application is stateless, and processes requests of potentially many concurrent users. A cookie is a way to know which request came from which user. Once we sign in the user, our application puts all user information in the cookie, including the claims, and encrypts it using a key only the server‑side application has. That same key is needed to decrypt the cookie. So when the cookie arrives in the browser, nobody can read it. Cookies are sent along automatically with each new request through the same server. When the server gets it, it will decrypt it using the key, read the user information, and reconstruct the ClaimsPrincipal object that is made available in the application. In ASP.NET Core, encryption works with a framework called data protection, which is used behind the scenes, which is automatically configured when you add cookie authentication support to your application. Data protection takes care of storing the key securely, and it rotates the key periodically.
when we logout the cookie dissapears.
External Identity Providers
Our app needs to register with google, and we get an clientid and secret. when the user tries to login we present googles identity provide with our client id and secret , user then enters the credentials in googles login page and google sends back the approved set of claims to the redirect endpoint we specify while registering.Get the client id and secret from google. Right click on the project and click on manage user secrets.
The secrets file can be used by Configuration object. but this file doesnt get checked in.
Install this nuget to install the google auth middleware.
Since we have set the default auth scheme to cookie this will work with cookie auth. We need to configure it to use google to signin. With a call to AddGoogle, an authentication scheme is added to the application. The name of the scheme is simply Google by default. Would we run the application now, it would just work as before, without Google.
Because we have set the default scheme to the cookie scheme. That means that all scheme actions are done on that scheme. There are three scheme actions. Authenticate is about how the claims principle gets reconstructed on every request. Since we're using the cookie to do that, we want to keep it as it is. The challenge determines what happens if the user tries to access a resource for which authentication is required. We already saw that the cookie scheme will redirect to account/login by default when that happens. We want to change that now, since we want Google to take care of logins. Forbid determines what happens if the user accesses a resource she can't access because she doesn't have the rights. The cookie scheme will redirect to account/accessdenied by default, and that's still what we want
So we need to set the scheme actions accordingly.
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; // for reconstructing claims principaln
o.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;// for login use google scheme
o.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;// use forbidden url from this scheme
})
MULTIPLE PROVIDERS
services.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; // for reconstructing claims principaln
//commented this code as when we use multiple login providers then this will always
// login from google
//o.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;// for login use google scheme
//o.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;// use forbidden url from this scheme
})
.AddCookie(o =>
{
o.LoginPath = "/Account/Login";
}).AddCookie(ExternalAuthenticationDefaults.AuthenticationScheme)
.AddGoogle(options =>
{
// we add a new cookie scheme and tell google to use this scheme when login
// we want google claims to be in a separate cookie
// check login from google to get more details
// when we sign in using google this cookie will have all the details.
// we read this cookie and create a new claims principal that will contain all
//the common claims needed by all login methods, since google will contain only its claims
options.SignInScheme = ExternalAuthenticationDefaults.AuthenticationScheme;
options.ClientId = Configuration["Google:ClientId"];
options.ClientSecret = Configuration["Google:Secret"];
});
Comments
Post a Comment