在.netframework 4.5.2项目上集成identityserver4的登录功能

一、添加引用

1、添加owin引用 版本:1.0.0.0
2、添加 Microsoft.Owin.Security.Cookies 版本:4.1.0
3、添加System.IdentityModel.Tokens.Jwt 版本:5.6.0
4、添加Microsoft.Owin.Security.OpenIdConnect 版本:4.1.0
5、添加Microsoft.Owin.Host.SystemWeb 版本:4.1.0

二、添加Startup.cs类

    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,
            });
        }
    }

三、得到用户ID

            var aaa = User.Identity;
            userId = ((System.Security.Claims.ClaimsIdentity)aaa).Claims.Where(c => c.Type == "sub").First().Value;

四、添加登出功能

            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 RedirectToAction("Index");

猜你喜欢

转载自www.cnblogs.com/wjx-blog/p/12294049.html