feat: cookies
This commit is contained in:
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
bin/
|
||||
obj/
|
||||
/packages/
|
||||
riderModule.iml
|
||||
/_ReSharper.Caches/
|
||||
13
.idea/.idea.Auths/.idea/.gitignore
generated
vendored
Normal file
13
.idea/.idea.Auths/.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Rider ignored files
|
||||
/modules.xml
|
||||
/contentModel.xml
|
||||
/projectSettingsUpdater.xml
|
||||
/.idea.Auths.iml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
4
.idea/.idea.Auths/.idea/encodings.xml
generated
Normal file
4
.idea/.idea.Auths/.idea/encodings.xml
generated
Normal file
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" />
|
||||
</project>
|
||||
8
.idea/.idea.Auths/.idea/indexLayout.xml
generated
Normal file
8
.idea/.idea.Auths/.idea/indexLayout.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="UserContentModel">
|
||||
<attachedFolders />
|
||||
<explicitIncludes />
|
||||
<explicitExcludes />
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/.idea.Auths/.idea/vcs.xml
generated
Normal file
6
.idea/.idea.Auths/.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
28
Auths.sln
Normal file
28
Auths.sln
Normal file
@@ -0,0 +1,28 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Auths", "Auths\Auths.csproj", "{72E18756-5750-453E-B022-73EB71741490}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cookie.Basic", "Cookie.Basic\Cookie.Basic.csproj", "{3684B6DC-9301-496C-9832-FFC26084C496}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cookie.BuiltIn", "Cookie.BuiltIn\Cookie.BuiltIn.csproj", "{63CE5DC9-F976-430B-8B12-50FB3DA3F872}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{72E18756-5750-453E-B022-73EB71741490}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{72E18756-5750-453E-B022-73EB71741490}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{72E18756-5750-453E-B022-73EB71741490}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{72E18756-5750-453E-B022-73EB71741490}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{3684B6DC-9301-496C-9832-FFC26084C496}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3684B6DC-9301-496C-9832-FFC26084C496}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{3684B6DC-9301-496C-9832-FFC26084C496}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3684B6DC-9301-496C-9832-FFC26084C496}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{63CE5DC9-F976-430B-8B12-50FB3DA3F872}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{63CE5DC9-F976-430B-8B12-50FB3DA3F872}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{63CE5DC9-F976-430B-8B12-50FB3DA3F872}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{63CE5DC9-F976-430B-8B12-50FB3DA3F872}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
10
Auths/Auths.csproj
Normal file
10
Auths/Auths.csproj
Normal file
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
3
Auths/Program.cs
Normal file
3
Auths/Program.cs
Normal file
@@ -0,0 +1,3 @@
|
||||
// See https://aka.ms/new-console-template for more information
|
||||
|
||||
Console.WriteLine("Hello, World!");
|
||||
14
Cookie.Basic/Cookie.Basic.csproj
Normal file
14
Cookie.Basic/Cookie.Basic.csproj
Normal file
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.6"/>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
6
Cookie.Basic/Cookie.Basic.http
Normal file
6
Cookie.Basic/Cookie.Basic.http
Normal file
@@ -0,0 +1,6 @@
|
||||
@Cookie.Basic_HostAddress = http://localhost:5163
|
||||
|
||||
GET {{Cookie.Basic_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
174
Cookie.Basic/Program.cs
Normal file
174
Cookie.Basic/Program.cs
Normal file
@@ -0,0 +1,174 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
#region Basic
|
||||
|
||||
const string AuthCookie = "auth";
|
||||
|
||||
app.MapGet("/secured-method", (HttpContext ctx) =>
|
||||
{
|
||||
// authentication
|
||||
if (ctx.Request.Cookies.ContainsKey(AuthCookie))
|
||||
{
|
||||
var cookie = ctx.Request.Cookies[AuthCookie];
|
||||
var parts = cookie!.Split("&").ToList();
|
||||
var entityType = parts[1].Split(":")[1];
|
||||
|
||||
// authorization
|
||||
if (entityType == "admin")
|
||||
{
|
||||
return "secured message";
|
||||
}
|
||||
else if (entityType == "user")
|
||||
{
|
||||
return "common message";
|
||||
}
|
||||
}
|
||||
|
||||
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
return "Unauthorized";
|
||||
});
|
||||
|
||||
app.MapGet("/login-admin", (HttpContext ctx) =>
|
||||
{
|
||||
var cookie = "user:ivan&type:admin";
|
||||
ctx.Response.Headers["set-cookie"] = $"{AuthCookie}={cookie}";
|
||||
});
|
||||
|
||||
app.MapGet("/login-user", (HttpContext ctx) =>
|
||||
{
|
||||
var cookie = "user:danil&type:user";
|
||||
ctx.Response.Headers["set-cookie"] = $"{AuthCookie}={cookie}";
|
||||
});
|
||||
|
||||
#endregion
|
||||
|
||||
#region Secured
|
||||
//todo: add to services
|
||||
//builder.Services.AddDataProtection();
|
||||
|
||||
const string DataProtectorName = "cookie-protector";
|
||||
// https://learn.microsoft.com/ru-ru/dotnet/api/microsoft.aspnetcore.dataprotection.idataprotector?view=aspnetcore-8.0
|
||||
|
||||
|
||||
app.MapGet("/login-user-protected", (HttpContext ctx, [FromServices] IDataProtectionProvider protector) =>
|
||||
{
|
||||
var dp = protector.CreateProtector(DataProtectorName);
|
||||
var cookieProtected = dp.Protect("user:danil&type:user");
|
||||
ctx.Response.Headers["set-cookie"] = $"{AuthCookie}={cookieProtected}";
|
||||
});
|
||||
|
||||
app.MapGet("/secured-method-protected", (HttpContext ctx, [FromServices] IDataProtectionProvider protector) =>
|
||||
{
|
||||
var dp = protector.CreateProtector(DataProtectorName);
|
||||
|
||||
// authentication
|
||||
if (ctx.Request.Cookies.ContainsKey(AuthCookie))
|
||||
{
|
||||
var cookie = ctx.Request.Cookies[AuthCookie]!;
|
||||
|
||||
var cookieUnprotected = dp.Unprotect(cookie);
|
||||
|
||||
var parts = cookieUnprotected.Split("&").ToList();
|
||||
var entityType = parts[1].Split(":")[1];
|
||||
|
||||
// authorization
|
||||
if (entityType == "admin")
|
||||
{
|
||||
return "secured message";
|
||||
}
|
||||
else if (entityType == "user")
|
||||
{
|
||||
return "common message";
|
||||
}
|
||||
}
|
||||
|
||||
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
return "Unauthorized";
|
||||
});
|
||||
|
||||
#endregion
|
||||
|
||||
#region Claims
|
||||
|
||||
//todo: uncomment
|
||||
//
|
||||
// app.Use((ctx,next) =>
|
||||
// {
|
||||
// var protector = ctx.RequestServices.GetService<IDataProtectionProvider>();
|
||||
// var dp = protector.CreateProtector(DataProtectorName);
|
||||
//
|
||||
// // authentication
|
||||
// if (ctx.Request.Cookies.ContainsKey(AuthCookie))
|
||||
// {
|
||||
// var cookie = ctx.Request.Cookies[AuthCookie]!;
|
||||
//
|
||||
// var cookieUnprotected = dp.Unprotect(cookie);
|
||||
//
|
||||
// var parts = cookieUnprotected.Split("&").ToList();
|
||||
// var entityType = parts[1].Split(":")[1];
|
||||
// var entityName = parts[0].Split(":")[1];
|
||||
//
|
||||
// // authorization
|
||||
// var claims = new List<Claim>();
|
||||
// claims.Add(new Claim("Type", entityType));
|
||||
// claims.Add(new Claim("Name", entityName));
|
||||
//
|
||||
// var identity = new ClaimsIdentity(claims);
|
||||
// var user = new ClaimsPrincipal(identity);
|
||||
// ctx.User = user;
|
||||
//
|
||||
// return next();
|
||||
// }
|
||||
//
|
||||
// ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
// return Task.CompletedTask;
|
||||
// });
|
||||
|
||||
app.MapGet("/login-user-claims", (HttpContext ctx, [FromServices] IDataProtectionProvider protector) =>
|
||||
{
|
||||
var dp = protector.CreateProtector(DataProtectorName);
|
||||
var cookieProtected = dp.Protect("user:danil&type:user");
|
||||
ctx.Response.Headers["set-cookie"] = $"{AuthCookie}={cookieProtected}";
|
||||
});
|
||||
|
||||
app.MapGet("/secured-method-claims", (HttpContext ctx, [FromServices] IDataProtectionProvider protector) =>
|
||||
{
|
||||
var user = ctx.User;
|
||||
|
||||
if (user.FindFirst("Type")?.Value == "admin")
|
||||
{
|
||||
return "secured message";
|
||||
}
|
||||
else if (user.FindFirst("Type")?.Value == "user")
|
||||
{
|
||||
return "common message";
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
app.Run();
|
||||
41
Cookie.Basic/Properties/launchSettings.json
Normal file
41
Cookie.Basic/Properties/launchSettings.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:47194",
|
||||
"sslPort": 44336
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "http://localhost:5163",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7254;http://localhost:5163",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
8
Cookie.Basic/appsettings.Development.json
Normal file
8
Cookie.Basic/appsettings.Development.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
9
Cookie.Basic/appsettings.json
Normal file
9
Cookie.Basic/appsettings.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
14
Cookie.BuiltIn/Cookie.BuiltIn.csproj
Normal file
14
Cookie.BuiltIn/Cookie.BuiltIn.csproj
Normal file
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.6"/>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
6
Cookie.BuiltIn/Cookie.BuiltIn.http
Normal file
6
Cookie.BuiltIn/Cookie.BuiltIn.http
Normal file
@@ -0,0 +1,6 @@
|
||||
@Cookie.BuiltIn_HostAddress = http://localhost:5209
|
||||
|
||||
GET {{Cookie.BuiltIn_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
53
Cookie.BuiltIn/Program.cs
Normal file
53
Cookie.BuiltIn/Program.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
|
||||
{
|
||||
options.LoginPath = "/login";
|
||||
});
|
||||
// builder.Services.AddAuthorization();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseAuthentication();
|
||||
// app.UseAuthorization();
|
||||
app.MapGet("/secured-method", /*[Authorize]*/ (HttpContext ctx) =>
|
||||
{
|
||||
var user = ctx.User?.FindFirst("Name");
|
||||
if (user == null)
|
||||
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
|
||||
return user?.Value ?? "Unauthorized";
|
||||
});
|
||||
|
||||
app.MapGet("/login", async (HttpContext ctx) =>
|
||||
{
|
||||
var claims = new List<Claim>();
|
||||
claims.Add(new Claim("Type", "admin"));
|
||||
claims.Add(new Claim("Name", "ivan"));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
var user = new ClaimsPrincipal(identity);
|
||||
|
||||
await ctx.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);
|
||||
return "Ok";
|
||||
});
|
||||
|
||||
app.Run();
|
||||
41
Cookie.BuiltIn/Properties/launchSettings.json
Normal file
41
Cookie.BuiltIn/Properties/launchSettings.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:60915",
|
||||
"sslPort": 44335
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "http://localhost:5209",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7089;http://localhost:5209",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
8
Cookie.BuiltIn/appsettings.Development.json
Normal file
8
Cookie.BuiltIn/appsettings.Development.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
9
Cookie.BuiltIn/appsettings.json
Normal file
9
Cookie.BuiltIn/appsettings.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
Reference in New Issue
Block a user