在.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;

四、远程identityServer4端增加专门用于登出的页面(给客户端调用)

复制代码
        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);
        }
复制代码

五、mvc端添加登出功能

复制代码
            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里类似下面的代码注释掉

<authentication mode="Forms">
      <forms loginUrl="~/Account/Logon" defaultUrl="~/Home/Index" protection="All" slidingExpiration="true" />
    </authentication>
    <authorization>
      <deny users="?" />
      <allow users="*" />
</authorization>

 

posted @   星星c#  阅读(1591)  评论(11编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示