1、添加引用web
一、添加owin引用 版本:1.0.0.0
二、添加 Microsoft.Owin.Security.Cookies 版本:4.1.0
三、添加System.IdentityModel.Tokens.Jwt 版本:5.6.0
四、添加Microsoft.Owin.Security.OpenIdConnect 版本:4.1.0
五、添加Microsoft.Owin.Host.SystemWeb 版本:4.1.0api
2、添加Startup.cs類cookie
public class Startup { public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { Authority = "http://localhost:5000", //ID Server ClientId = "mvc", ResponseType = "id_token code", SignInAsAuthenticationType = "Cookies", RedirectUri = "http://localhost:63931/signin-oidc", //URL of website Scope = "openid", RequireHttpsMetadata = false, }); } }
3、獲得用戶IDsession
var aaa = User.Identity; userId = ((System.Security.Claims.ClaimsIdentity)aaa).Claims.Where(c => c.Type == "sub").First().Value;
4、遠程identityServer4端增長專門用於登出的頁面(給客戶端調用)mvc
public async Task<IActionResult> RemoteLogout(string returnUrl) { if (User?.Identity.IsAuthenticated == true) { // delete local authentication cookie await _signInManager.SignOutAsync(); // raise the logout event await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName())); } return Redirect(returnUrl); }
5、mvc端添加登出功能app
List<string> lstKeys = new List<string> { "idsrv.session", ".AspNetCore", ".AspNet.Cookies" }; for (int i = 0; i < this.Request.Cookies.Count; i++) { string cookieName = this.Request.Cookies[i].Name; if (lstKeys.Where(c => cookieName.Contains(c)).Any()) { this.Response.Cookies[cookieName].Expires = DateTime.Now.AddDays(-1); } } //調用遠程api清除遠程的當前用戶登陸信息 return Redirect("http://212.19.31.12:5000/Account/RemoteLogout?returnUrl=http://localhost:63931");
備註:若是之前用的是Forms認證,就須要把web.config裏相似下面的代碼註釋掉async
<authentication mode="Forms"> <forms loginUrl="~/Account/Logon" defaultUrl="~/Home/Index" protection="All" slidingExpiration="true" /> </authentication> <authorization> <deny users="?" /> <allow users="*" /> </authorization>