zoukankan      html  css  js  c++  java
  • Security Cookies登录验证核心详解

    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Claims;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace CookieSessionSample
    {
        public class Startup
        {
            public void ConfigureServices(IServiceCollection services)
            {
                // This can be removed after https://github.com/aspnet/IISIntegration/issues/371
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                }).AddCookie(o => o.SessionStore = new MemoryCacheTicketStore());
            }
    
            public void Configure(IApplicationBuilder app)
            {
                app.UseAuthentication();
    
                app.Run(async context =>
                {
                    if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                    {    //正常验证流程不是写这里,这里意思是上述验证发现未登录,
                    //一般可以通过自定义用户密码验证操作通过验证后,构建下属登录凭证
                        // Make a large identity
                        var claims = new List<Claim>(1001);
                        claims.Add(new Claim(ClaimTypes.Name, "bob"));
                        for (int i = 0; i < 1000; i++)
                        {
                            claims.Add(new Claim(ClaimTypes.Role, "SomeRandomGroup" + i, ClaimValueTypes.String, "IssuedByBob", "OriginalIssuerJoe"));
                        }
    
                        //写入登录验证方案与凭证到Cookies
                        await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                            new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)));   
    
                        context.Response.ContentType = "text/plain";
                        await context.Response.WriteAsync("Hello First timer");
                        return;
                    }
    
                    context.Response.ContentType = "text/plain";
                    await context.Response.WriteAsync("Hello old timer");
                });
            }
        }
    }
    
  • 相关阅读:
    ZOJ 1001 A + B Problem
    献给那些心软的人!!
    将表格的数据插入另一个表格
    把链接 显示为方框
    【ibus】设置ibus输入法(pinyin & sunpinyin)
    [Mongo] How to Install Mongo on Debian(不要安装)
    [Sinatra、Mongo] Mongo
    Sinatra+SQLite3+DataMapper
    [sinatra] Sinatra再入门
    [slim] Slim
  • 原文地址:https://www.cnblogs.com/ms_senda/p/12501157.html
Copyright © 2011-2022 走看看