代码改变世界

C# auth

  qgbo  阅读(5)  评论(0编辑  收藏  举报


1,这个是好的:

  

2. 多重身份

  

 

 

复制代码
[18:12] Qi, Gongbo (CN)(EXTERN)
using Microsoft.AspNetCore.Authentication;

using Microsoft.AspNetCore.Authentication.Cookies;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.DataProtection;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Http.Features;

using Microsoft.AspNetCore.Identity;

using Microsoft.Extensions.Options;

using System.Security.Claims;

using System.Xml.Linq;
 
var builder = WebApplication.CreateBuilder(args);
 
// Add services to the container.
 
builder.Services.AddAuthentication(options => {

    options.DefaultAuthenticateScheme = "Cookies";

    options.DefaultSignInScheme = "Cookies";

    options.DefaultChallengeScheme = "Cookies";

    options.RequireAuthenticatedSignIn = false;

}).AddCookie("Cookies",

options =>

{
 
    options.ExpireTimeSpan = TimeSpan.FromSeconds(30);

}
 
);
 
 
builder.Services.AddAuthorization(options =>

{

    options.AddPolicy("AtLeast21",

        policy =>

        {

            policy.AuthenticationSchemes = new[] { "Cookies" };

            policy.RequireUserName("zhangsan");

        }

     );

});
 
 
var app = builder.Build();
 
// Configure the HTTP request pipeline.

app.Use(async (context, n) => {
 
    var endpoint = context.GetEndpoint();

    var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
 
    var policies = endpoint?.Metadata.GetOrderedMetadata<AuthorizationPolicy>() ?? Array.Empty<AuthorizationPolicy>();

    var _policyProvider = context.RequestServices.GetService<IAuthorizationPolicyProvider>();

    var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData, policies);
 
    await n(context);

});
 
app.UseAuthentication();

app.UseAuthorization();
 
 
 
app.MapGet("/weatherforecast", (HttpContext httpContext) =>

{

    return "forecast"+ httpContext.Request.Cookies.FirstOrDefault().Value;

}).RequireAuthorization("AtLeast21");
 
 
app.MapGet("/Account/Login", async (IAuthenticationService authenticationService, HttpContext httpContext, IDataProtectionProvider dataProtection) =>

{

    var claims = new Claim[] { new Claim(ClaimTypes.Name, "zhangsan") };

    var id = new ClaimsIdentity(claims);
 
 
    var principal = new ClaimsPrincipal(id);
 
    // await authenticationService.SignInAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, principal, 

    //     new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromSeconds(45)) });
 
   

    var dataProtector = dataProtection.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2");
 
    var ticket = new AuthenticationTicket(principal, null, "Cookies");
 
    var cookies = new TicketDataFormat(dataProtector).Protect(ticket);
 
    httpContext.Response.Cookies.Append(CookieAuthenticationDefaults.CookiePrefix + Uri.EscapeDataString("Cookies"), cookies);

    httpContext.Response.Headers.Location = "/weatherforecast";

    httpContext.Response.StatusCode = 302;

    //httpContext.Response.Redirect("/weatherforecast");

    await httpContext.Response.WriteAsync("rrrrrrrrrr");

    Console.WriteLine("sssss");

    return Task.CompletedTask;

});
 
app.Run();
 
View Code
复制代码

 

 

复制代码
 1 using Microsoft.AspNetCore.Authentication;
 2 using Microsoft.AspNetCore.Authorization;
 3 using Microsoft.AspNetCore.DataProtection;
 4 using Microsoft.AspNetCore.Http;
 5 using Microsoft.AspNetCore.Identity;
 6 using Microsoft.Extensions.Options;
 7 using System.Security.Claims;
 8 
 9 var builder = WebApplication.CreateBuilder(args);
10 
11 // Add services to the container.
12 
13 builder.Services.AddAuthentication(options => {
14     options.DefaultAuthenticateScheme = "Cookies";
15     options.DefaultSignInScheme = "Cookies";
16     options.DefaultChallengeScheme = "Cookies";
17 }).AddCookie("Cookies");
18 
19 
20 builder.Services.AddAuthorization(options =>
21 {
22     options.AddPolicy("AtLeast21",
23         policy =>
24         {
25             policy.AuthenticationSchemes = new[] { "Cookies" };
26             policy.RequireUserName("zhangsan");
27         }
28      );
29 });
30 
31 
32 var app = builder.Build();
33 
34 // Configure the HTTP request pipeline.
35 app.Use(async (context, n) => {
36 
37     var endpoint = context.GetEndpoint();
38     var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
39 
40     var policies = endpoint?.Metadata.GetOrderedMetadata<AuthorizationPolicy>() ?? Array.Empty<AuthorizationPolicy>();
41     var _policyProvider = context.RequestServices.GetService<IAuthorizationPolicyProvider>();
42     var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData, policies);
43 
44     await n(context);
45 });
46 
47 app.UseAuthentication();
48 app.UseAuthorization();
49 
50 
51 
52 
53 
54 app.MapGet("/weatherforecast", () =>
55 {
56     return "forecast";
57 }).RequireAuthorization("AtLeast21");
58 
59 
60 app.MapGet("/Account/Login", context =>
61 {
62     var claims = new Claim[] { new Claim(ClaimTypes.Name,"zhangsan") };
63     var id = new ClaimsIdentity(claims);
64 
65 
66     var principle = new ClaimsPrincipal(id);
67 
68     var protector= DataProtectionProvider.Create("aa").CreateProtector("aa");
69 
70 
71     var s = new AuthenticationTicket(principle,"Cookies");
72     var cookies= new SecureDataFormat<AuthenticationTicket>(TicketSerializer.Default, protector).Protect(s);
73 
74     context.Response.Cookies.Append("Cookies", cookies);
75     return Task.CompletedTask;
76 });
77 
78 app.Run();
View Code
复制代码

 

 

复制代码
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddAuthentication("").AddCookie();


builder.Services.AddAuthorization();


var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseAuthentication();
app.UseAuthorization();


app.MapGet("/weatherforecast", () =>
{
    return "forecast";
}).RequireAuthorization();


app.MapGet("/Account/Login", context =>
{
    var claims = new Claim[] { new Claim(ClaimTypes.Name,"zhangsan") };
    var id = new ClaimsIdentity(claims);


    var principle = new ClaimsPrincipal(id);

    var protector= DataProtectionProvider.Create("aa").CreateProtector("aa");


    var s = new AuthenticationTicket(principle,"Cookies");
    var cookies= new SecureDataFormat<AuthenticationTicket>(TicketSerializer.Default, protector).Protect(s);

    context.Response.Cookies.Append("cookies", cookies);
    context.Response.StatusCode = 200;
    context.Response.Redirect(context.Request.Query["ReturnUrl"]);
    return Task.CompletedTask;
});

app.Run();
View Code
复制代码

 

 

openid

  

相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示