net-core认证和授权

public virtual bool IsAuthenticated
        {
            get { return !string.IsNullOrEmpty(_authenticationType); }
        }

登录代码:

   IList<Claim> calims = new List<Claim>();
    calims.Add(new Claim("name","ybd"));
    ClaimsIdentity identity = new ClaimsIdentity(calims);
    var claimsPrincipal = new ClaimsPrincipal(identity); // 这里要加type
    await ctx.SignInAsync("ybd-cookie",claimsPrincipal);

AuthenticationService

/// <summary>
/// Sign a principal in for the specified authentication scheme.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/>.</param>
/// <param name="scheme">The name of the authentication scheme.</param>
/// <param name="principal">The <see cref="ClaimsPrincipal"/> to sign in.</param>
/// <param name="properties">The <see cref="AuthenticationProperties"/>.</param>
/// <returns>A task.</returns>
public virtual async Task SignInAsync(HttpContext context, string? scheme, ClaimsPrincipal principal, AuthenticationProperties? properties)
{
    if (principal == null)
    {
        throw new ArgumentNullException(nameof(principal));
    }
 
    if (Options.RequireAuthenticatedSignIn)
    {
        if (principal.Identity == null)
        {
            throw new InvalidOperationException("SignInAsync when principal.Identity == null is not allowed when AuthenticationOptions.RequireAuthenticatedSignIn is true.");
        }
        if (!principal.Identity.IsAuthenticated)
        {
            throw new InvalidOperationException("SignInAsync when principal.Identity.IsAuthenticated is false is not allowed when AuthenticationOptions.RequireAuthenticatedSignIn is true.");
        }
    }
 
    if (scheme == null)
    {
        var defaultScheme = await Schemes.GetDefaultSignInSchemeAsync();
        scheme = defaultScheme?.Name;
        if (scheme == null)
        {
            throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultSignInScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).");
        }
    }
 
    // 关键代码  获得身份验证处理程序
    var handler = await Handlers.GetHandlerAsync(context, scheme);
    if (handler == null)
    {
        throw await CreateMissingSignInHandlerException(scheme);
    }
 
    var signInHandler = handler as IAuthenticationSignInHandler;
    if (signInHandler == null)
    {
        throw await CreateMismatchedSignInHandlerException(scheme, handler);
    }
 
    await signInHandler.SignInAsync(principal, properties);
}

 

posted @ 2023-05-23 21:39  vba是最好的语言  阅读(42)  评论(0编辑  收藏  举报