防止在 Asp.NET MVC 中使用 OpenId Connect 登录

Prevent login using OpenId Connect in Asp.NET MVC

我有一个 OpenIdConnect 服务 运行 (Thinktecture IdSvr),我可以完美地登录到我的应用程序。

当用户使用 OpenId Connect 成功登录时,我想检查他们是否存在于我的客户端用户存储中,然后允许他们继续或注销。

为此,我正在处理 OpenIdConnectAuthenticationOptions.Notifications 中的 AuthorizationCodeReceived 事件,但我不知道如何阻止用户成功登录。

我假设不设置 n.AuthenticationTicket 会阻止创建原则。

var userInfoClient = GetUserInfoClient();

var userInfo = await userInfoClient.GetAsync();
var email = GetEmailAddr(userInfo);

var user = GetClientUser(email)

if (user != null)
{
    // access and refresh token
    var tokenClient = GetTokenClient();

    var tokenResponse = await GetToken(tokenClient);

    claims.Add(new Claim("access_token", tokenResponse .AccessToken));
    claims.Add(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse .ExpiresIn).ToLocalTime().ToString()));
    claims.Add(new Claim("refresh_token", tokenResponse .RefreshToken));
    claims.Add(new Claim("id_token", n.ProtocolMessage.IdToken));

    n.AuthenticationTicket = new AuthenticationTicket(
        new ClaimsIdentity(
            claims.Distinct(new ClaimComparer()),
            n.AuthenticationTicket.Identity.AuthenticationType),
            n.AuthenticationTicket.Properties);
}

这很简单。我所做的只是在 AuthorizationCodeReceived 事件中抛出一个新的 SecurityException