325
CHAPTER 8 | Make secure .NET Microservices and Web Applications
Authenticate with an OpenID Connect or OAuth 2.0 Identity provider
If user information is stored in Azure Active Directory or another identity solution that supports
OpenID Connect or OAuth 2.0, you can use the
Microsoft.AspNetCore.Authentication.OpenIdConnect
package to authenticate using the OpenID
Connect workflow. For example, to authenticate to the Identity.Api microservice in
eShopOnContainers, an ASP.NET Core web application can use middleware from that
package as
shown in the following simplified example in
Program.cs
:
// Program.cs
var
identityUrl = builder.
Configuration
.
GetValue
<
string
>(
"IdentityUrl"
);
var
callBackUrl = builder.
Configuration
.
GetValue
<
string
>(
"CallBackUrl"
);
var
sessionCookieLifetime = builder.
Configuration
.
GetValue
(
"SessionCookieLifetimeMinutes"
,
60
);
// Add Authentication services
services.
AddAuthentication
(options =>
{
options.
DefaultScheme
= CookieAuthenticationDefaults.
AuthenticationScheme
;
options.
DefaultChallengeScheme
= JwtBearerDefaults.
AuthenticationScheme
;
})
.
AddCookie
(setup => setup.
ExpireTimeSpan
= TimeSpan.
FromMinutes
(sessionCookieLifetime))
.
AddOpenIdConnect
(options =>
{
options.
SignInScheme
= CookieAuthenticationDefaults.
AuthenticationScheme
;
options.
Authority
= identityUrl.
ToString
();
options.
SignedOutRedirectUri
= callBackUrl.
ToString
();
options.
ClientId
= useLoadTest ?
"mvctest"
:
"mvc"
;
options.
ClientSecret
=
"secret"
;
options.
ResponseType
= useLoadTest ?
"code id_token token"
:
"code id_token"
;
options.
SaveTokens
=
Dostları ilə paylaş: