Adding OIDC and cookie middleware in HTTP pipeline

To use OpenID Connect Provider (OP), we need to add the middleware to our application's HTTP pipeline, so that unauthorized requests can be forwarded to the authorization server for user authentication.

Add cookie middleware and OIDC middleware as follows:

    app.UseCookieAuthentication(new CookieAuthenticationOptions 
{
AuthenticationScheme = "Cookies"
});

app.UseOpenIdConnectAuthentication(
new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
ClientId = "client",
Authority = "http://localhost:5000",
RequireHttpsMetadata = false,
SignInScheme = "Cookies",
Scope = {"openid", "profile", "roles" },
SaveTokens = true
});
Both the middlewares should be added before the MVC middleware.

OpenID Connect contains some properties, such as AuthentitcationScheme, which represent the name of the middleware and clientId to represent the ID of the client, and it has to be matched with the one defined in the authorization server. The authority that represents the authorization server URL, SignInScheme holds the authentication scheme of the local middleware used to store the token once returned from the authorization server. In our case, it's cookie middleware. Scope is the important part that represents what scopes are allowed or contained in the token. In our case, we have defined openid, profile, and roles, which means the client ID, name, website and role, and others will be available in the token. For example, if we only specify the openid and profile, the roles will not be contained in the token and if you have used roles to authorize controllers or the action method that will not work, it will navigate you to the access denied page on authorization. Setting SaveTokens to True actually saves the tokens in the cookie. Tokens are stored inside the properties section of the cookie.

The easiest way to access them is through the extension methods as follows:

    <p> 
@await ViewContext.HttpContext.Authentication
.GetTokenAsync("access_token")
</p>

Or for Refresh token call this

<p>
@await ViewContext.HttpContext.Authentication
.GetTokenAsync("access_token")
</p>

To study more about what claims are part of each scope, please go through this link https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.202