#regionHandler to set up its own schema
services.AddAuthenticationCore(options => options.AddScheme<MyHandler>("myScheme"."demo myScheme"));
#endregion

#regionSupports policy authentication and authorization services

// Specify the policy column that passes the policy validation
services.AddSingleton<IAuthorizationHandler, AdvancedRequirement>();

services.AddAuthorization(options =>
{
    //AdvancedRequirement is an alias
    options.AddPolicy("AdvancedRequirement", policy =>
    {
        policy.AddRequirements(new NameAuthorizationRequirement("1"));
    });
}).AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.LoginPath = new PathString("/Fourth/Login");
    options.ClaimsIssuer = "Cookie";
});

#endregion

#regionSchame to verify

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;// "Richard"; //
})
.AddCookie(options =>
{
    options.LoginPath = new PathString("/Fourth/Login");// This specifies that if the validation fails, the page will be redirected to
    options.ClaimsIssuer = "Cookie";
});
#endregion
Copy the code
#regionBasic authentication and authorization modelLogin app. The Map ("/login", builder => builder.Use(next =>
{
    return async (context) =>
    {
        var claimIdentity = new ClaimsIdentity();  // This ClaimsIdentity can be understood as an ID card
        claimIdentity.AddClaim(new Claim(ClaimTypes.Name, "XT")); // The carrier of user information
        // Scheme can be understood as an identifier corresponding to the ID card
        await context.SignInAsync("myScheme".new ClaimsPrincipal(claimIdentity));
        await context.Response.WriteAsync($"Hello, ASP.NET Core! {context.User.Identity.Name} Login");
    };
}));
/ / exit
app.Map("/logout", builder => builder.Use(next =>
{
    return async (context) =>
    {
        await context.SignOutAsync("myScheme");
    };
}));

app.Use(next => // Verify id
{
    return async (context) =>
    {
        var result = await context.AuthenticateAsync("myScheme");
        if(result? .Principal ! =null)
        {
            context.User = result.Principal;
            await next(context);
        }
        else
        {
            await context.ChallengeAsync("myScheme"); }}; });// What permission does the id card have
app.Use(async (context, next) =>
{
    var user = context.User;
    if (user.Identity.Name.Equals("XT"))//user? .Identity? .isauthenticated there is no authorization check, only check the name
    {
        await next();
    }
    else
    {
        await context.ForbidAsync("myScheme");
    }
    //if (user? .Identity? .IsAuthenticated ?? false)
    / / {
    // if (user.Identity.Name ! = "jim") await context.ForbidAsync("eScheme");
    // else await next();
    / /}
    //else
    / / {
    // await context.ChallengeAsync("eScheme");
    / /}
});

// Access protected resources
app.Map("/resource", builder => builder.Run(async (context) =>
{
    await context.Response.WriteAsync($"Hello, ASP.NET Core! {context.User.Identity.Name}");
}));

app.Run(async (HttpContext context) =>
{
    await context.Response.WriteAsync("Hello World, success!");
});
#endregion
Copy the code

Related classes

/// <summary>
///Custom handler
///There is usually a unified certification authority that is responsible for issuing and destroying certificates (login and logout), while other services are only used to validate certificates and do not SingIn/SingOut.
/// </summary>
public class MyHandler : IAuthenticationHandler.IAuthenticationSignInHandler.IAuthenticationSignOutHandler
{
    public AuthenticationScheme Scheme { get; private set; }
    protected HttpContext Context { get; private set; }

    public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
    {
        Scheme = scheme;
        Context = context;
        return Task.CompletedTask;
    }

    /// <summary>
    ///certification
    /// </summary>
    /// <returns></returns>
    public async Task<AuthenticateResult> AuthenticateAsync()
    {
        var cookie = Context.Request.Cookies["myCookie"];
        if (string.IsNullOrEmpty(cookie))
        {
           return  AuthenticateResult.NoResult();
        }
        return AuthenticateResult.Success(this.Deserialize(cookie));
    }

    /// <summary>
    ///There is no login requirement
    /// </summary>
    /// <param name="properties"></param>
    /// <returns></returns>
    public Task ChallengeAsync(AuthenticationProperties properties)
    {
        Context.Response.Redirect("/login");
        return Task.CompletedTask;
    }

    /// <summary>
    ///No permissions
    /// </summary>
    /// <param name="properties"></param>
    /// <returns></returns>
    public Task ForbidAsync(AuthenticationProperties properties)
    {
        Context.Response.StatusCode = 403;
        return Task.CompletedTask;
    }

    /// <summary>
    ///The login
    /// </summary>
    /// <param name="user"></param>
    /// <param name="properties"></param>
    /// <returns></returns>
    public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
    {
        var ticket = new AuthenticationTicket(user, properties, Scheme.Name);
        Context.Response.Cookies.Append("myCookie".this.Serialize(ticket));
        return Task.CompletedTask;
    }

    /// <summary>
    ///exit
    /// </summary>
    /// <param name="properties"></param>
    /// <returns></returns>
    public Task SignOutAsync(AuthenticationProperties properties)
    {
        Context.Response.Cookies.Delete("myCookie");
        return Task.CompletedTask;
    }
    private AuthenticationTicket Deserialize(string content)
    {
        byte[] byteTicket = System.Text.Encoding.Default.GetBytes(content);
        return TicketSerializer.Default.Deserialize(byteTicket);
    }

    private string Serialize(AuthenticationTicket ticket)
    {

        / / need to introduce Microsoft. AspNetCore. Authentication

        byte[] byteTicket = TicketSerializer.Default.Serialize(ticket);
        returnEncoding.Default.GetString(byteTicket); }}public class TicketDataFormat : SecureDataFormat<AuthenticationTicket>// IDataSerializer<AuthenticationTicket>//
{
    public TicketDataFormat(IDataProtector protector)
        : base(TicketSerializer.Default, protector){}}Copy the code
/// <summary>
///Policy Indicates a Policy or rule
/// </summary>
public class AdvancedRequirement : AuthorizationHandler<NameAuthorizationRequirement>, IAuthorizationRequirement
{ 
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NameAuthorizationRequirement requirement)
    {
        // The user information can be obtained from the database for verification
        // We can do a rule validation here
        // This can also be verified by configuration files
        if(context.User ! =null && context.User.HasClaim(c => c.Type == ClaimTypes.Sid))
        {
            string sid = context.User.FindFirst(c => c.Type == ClaimTypes.Sid).Value;
            if (!sid.Equals(requirement.RequiredName))
            {
                context.Succeed(requirement);
            }
        }
        returnTask.CompletedTask; }}Copy the code
public class RoleAuthorizationRequirement : AuthorizationHandler<RoleAuthorizationRequirement>, IAuthorizationRequirement
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleAuthorizationRequirement requirement)
    {
        throw newNotImplementedException(); }}Copy the code