繁体   English   中英

如何使用自定义登录服务器验证 asp.net web 应用程序?

[英]How can I authenticate asp.net web application with custom login server?

我正在使用 asp.net 内核制作自定义单点登录服务。 我制作了登录服务器,它在 cookie 中返回 JWT 令牌并进行验证。 我想将我的 web 应用程序连接到登录服务器,因此 web 应用程序可以识别用户是否通过登录服务器登录。 是否可以使用 web 应用程序中的startup.cs设置来做到这一点? 如果是这样,我该怎么做? 我不想将令牌检查过程放在每个操作中。

提前致谢

据我所知,在 asp.net 内核中,我们可以提供 jwtbear 身份验证验证来检查用户是否登录。 所有这些东西都是在 web 应用程序而不是登录服务器上提供的。 如果您将令牌发送到登录服务器,web 应用程序如何知道用户是否登录。

通常,我们会在 web 应用端直接检查用户令牌是否有效。

我们可以设置登录服务器和 web 应用程序使用相同的 Issuer、Audience 和 SecretKey。

然后我们可以直接在 web 应用程序中验证用户,而不是登录服务器。

更多细节,您可以参考以下代码:

登录服务器生成令牌:

    public static string GetToken3()
    {

        var key = Encoding.ASCII.GetBytes
        ("YourKey-2374-OFFKDI940NG7:56753253-tyuw-5769-0921-kfirox29zoxv");
        //Generate Token for user 
        var JWToken = new JwtSecurityToken(
            issuer: "http://localhost:45092/",
            audience: "http://localhost:45092/",
            claims: new List<Claim>
{
    new Claim(ClaimTypes.Name, "Users2222" )
},
            notBefore: new DateTimeOffset(DateTime.Now).DateTime,
            expires: new DateTimeOffset(DateTime.Now.AddDays(1)).DateTime,
            //Using HS256 Algorithm to encrypt Token  
            signingCredentials: new SigningCredentials
            (new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
        );
        string token = new JwtSecurityTokenHandler().WriteToken(JWToken);
        return token;
    }

web 应用程序验证令牌:

        //Provide a secret key to Encrypt and Decrypt the Token
        var SecretKey = Encoding.ASCII.GetBytes
             ("YourKey-2374-OFFKDI940NG7:56753253-tyuw-5769-0921-kfirox29zoxv");

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = "http://localhost:45092/",
        ValidAudience = "http://localhost:45092/",
        IssuerSigningKey = new SymmetricSecurityKey(
            SecretKey),
        ClockSkew = TimeSpan.Zero
    }
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM