asp.netcore Authentication
2022-12-21 14:23 qgbo 阅读(26) 评论(0) 收藏 举报Authentication is for getting the user infomation from cookie/token..
We use Authentication like this:
builder.Services.AddAuthentication("cookie") .AddCookie();
the AddCookie() define we get info from cookie;
public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, string? displayName, Action<CookieAuthenticationOptions> configureOptions) { builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>()); builder.Services.AddOptions<CookieAuthenticationOptions>(authenticationScheme).Validate(o => o.Cookie.Expiration == null, "Cookie.Expiration is ignored, use ExpireTimeSpan instead."); return builder.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(authenticationScheme, displayName, configureOptions); }
The first line define where the Options<CookieAuthenticationOptions> come from when we use it in progarm.
The implenment define loginpath properties,etc
The CookieManager deine how to get the cookie string.
.net7 如下代码:
public static class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddControllers();
services.AddHttpClient();
services.AddAuthorization();
services.AddAuthentication("cookie").AddCookie("cookie");
services.AddSwaggerGen();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.Use(async (context, n) =>
{
if (context.Request?.Cookies["username"]?.ToString() != null)
{
var s = new ClaimsPrincipal();
s.AddIdentity(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, context.Request.Cookies["username"].ToString()) }));
context.User = s;
}
await n();
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
app.UseSwaggerUI();
}
}
controller:
public class AuthController : ControllerBase
{
[HttpGet]
[Route("/auth")]
public string auth([FromServices] ILogger<AuthController> _logger)
{
_logger.LogWarning("_logger auth " + HttpContext.User.Identity.Name);
return "ok";
}
[HttpPost]
[Route("/login")]
public string login([FromServices] ILogger<AuthController> _logger, string username, string password)
{
HttpContext.Response.Cookies.Append("username", username);
HttpContext.Response.Cookies.Append("password", password);
_logger.LogInformation("login ok");
return "ok";
}
}
这样可以登录了
气功波(18037675651)
浙公网安备 33010602011771号