امن سازی برنامههای ASP.NET Core توسط IdentityServer 4x - قسمت پنجم - پیاده سازی ورود و خروج از سیستم
نویسنده: وحید نصیری
تاریخ: ۱۳۹۷/۰۶/۱۴ ۱۹:۴۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
https://idpHostAddress/connect/authorize? client_id=imagegalleryclient &redirect_uri=https://clientapphostaddress/signin-oidcoidc &scope=openid profile &response_type=code id_token &response_mode=form_post &nonce=63626...n2eNMxA0
namespace DNT.IDP
{
public static class Config
{
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientName = "Image Gallery",
ClientId = "imagegalleryclient",
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = new List<string>
{
"https://localhost:5001/signin-oidc"
},
PostLogoutRedirectUris = new List<string>
{
"https://localhost:5001/signout-callback-oidc"
},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
},
ClientSecrets =
{
new Secret("secret".Sha256())
}
}
};
}
}
} namespace ImageGallery.MvcClient.WebApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
}).AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "https://localhost:6001";
options.ClientId = "imagegalleryclient";
options.ResponseType = "code id_token";
//options.CallbackPath = new PathString("...")
//options.SignedOutCallbackPath = new PathString("...")
options.Scope.Add("openid");
options.Scope.Add("profile");
options.SaveTokens = true;
options.ClientSecret = "secret";
options.GetClaimsFromUserInfoEndpoint = true;
}); namespace ImageGallery.MvcClient.WebApp
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication(); namespace ImageGallery.MvcClient.WebApp.Controllers
{
[Authorize]
public class GalleryController : Controller
{
// ....
public async Task WriteOutIdentityInformation()
{
var identityToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.IdToken);
Debug.WriteLine($"Identity token: {identityToken}");
foreach (var claim in User.Claims)
{
Debug.WriteLine($"Claim type: {claim.Type} - Claim value: {claim.Value}");
}
} public async Task<IActionResult> Index()
{
await WriteOutIdentityInformation();
// ....
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-area="" asp-controller="Gallery" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Gallery" asp-action="AddImage">Add an image</a></li>
@if (User.Identity.IsAuthenticated)
{
<li><a asp-area="" asp-controller="Gallery" asp-action="Logout">Logout</a></li>
}
</ul>
</div>
namespace ImageGallery.MvcClient.WebApp.Controllers
{
[Authorize]
public class GalleryController : Controller
{
public async Task Logout()
{
// Clears the local cookie ("Cookies" must match the name of the scheme)
await HttpContext.SignOutAsync("Cookies");
await HttpContext.SignOutAsync("oidc");
} PostLogoutRedirectUris = new List<string>
{
"https://localhost:5001/signout-callback-oidc"
},
options.Scope.Add("openid");
options.Scope.Add("profile"); options.GetClaimsFromUserInfoEndpoint = true;
.AddOpenIdConnect("oidc", config =>
{
config.CallbackPath = "/home/ExternalLoginCallBack"; //...
.AddOpenIdConnect("oidc", options =>
{
// ...
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = async ctx =>
{
// how to access claims
var user = ctx.Principal;
var email = user.Claims.FirstOrDefault(claim => claim.Type == "email").Value;
// how to access services
var db = ctx.HttpContext.RequestServices.GetRequiredService<MyDb>();
// ....
}
};
}); [HttpGet]
[Route("signin")]
public async Task SignIn()
{
if (!User.Identity.IsAuthenticated)
{
await HttpContext.ChallengeAsync("oidc", new AuthenticationProperties
{
RedirectUri = "/YourController/YourAction",
});
}
} public IActionResult Logout()
{
return SignOut(new AuthenticationProperties { RedirectUri = "/YourController/YourAction" }, "Cookies", "oidc");
} new Client
{
ClientName = "Native Client (Hybrid with PKCE)",
ClientId = "native.hybrid",
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = new List<string>
{
"https://notused"
},
PostLogoutRedirectUris = new List<string>
{
"https://notused"
},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Address,
"roles",
"imagegalleryapi",
"country",
"subscriptionlevel"
},
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowOfflineAccess = true,
RequireClientSecret = false,
RequireConsent = false,
RequirePkce = true,
UpdateAccessTokenClaimsOnRefresh = true,
AccessTokenType = AccessTokenType.Reference,
RefreshTokenUsage = TokenUsage.ReUse
} var options = new OidcClientOptions
{
Authority = "https://localhost:6001",
ClientId = "native.hybrid",
ClientSecret = "secret",
Scope = "openid profile email imagegalleryapi",
RedirectUri = "xamarinformsclients://callback",
Browser = browser,
ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect
}; System.InvalidOperationException: 'Error loading discovery document: Error connecting to https://localhost:6001/.well-known/openid-configuration. Network subsystem is down.'
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
var options = new OidcClientOptions();
options.BackchannelHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate, chain, sslPolicyErrors) => true
};