Skip to content

Commit 64ffe8b

Browse files
committed
testauth
1 parent 440aa6b commit 64ffe8b

File tree

76 files changed

+40668
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

76 files changed

+40668
-0
lines changed

.idea/.idea.JwkTest/.idea/.gitignore

+13
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/.idea.JwkTest/.idea/codeStyles/codeStyleConfig.xml

+5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/.idea.JwkTest/.idea/encodings.xml

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/.idea.JwkTest/.idea/indexLayout.xml

+8
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/.idea.JwkTest/.idea/misc.xml

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/.idea.JwkTest/riderModule.iml

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

JwkTest.sln

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApi", "TestApi\TestApi.csproj", "{75BD055F-135A-4C0D-A761-D68ECE3CC7E9}"
4+
EndProject
5+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProxyAuth", "ProxyAuth\ProxyAuth.csproj", "{3CB4337B-100E-4DBB-9BB4-46CA2FB9794B}"
6+
EndProject
7+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestMvc", "TestMvc\TestMvc.csproj", "{AFD43908-569A-4DD3-8235-88658A819EC9}"
8+
EndProject
9+
Global
10+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
11+
Debug|Any CPU = Debug|Any CPU
12+
Release|Any CPU = Release|Any CPU
13+
EndGlobalSection
14+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
15+
{75BD055F-135A-4C0D-A761-D68ECE3CC7E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
16+
{75BD055F-135A-4C0D-A761-D68ECE3CC7E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
17+
{75BD055F-135A-4C0D-A761-D68ECE3CC7E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
18+
{75BD055F-135A-4C0D-A761-D68ECE3CC7E9}.Release|Any CPU.Build.0 = Release|Any CPU
19+
{3CB4337B-100E-4DBB-9BB4-46CA2FB9794B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
20+
{3CB4337B-100E-4DBB-9BB4-46CA2FB9794B}.Debug|Any CPU.Build.0 = Debug|Any CPU
21+
{3CB4337B-100E-4DBB-9BB4-46CA2FB9794B}.Release|Any CPU.ActiveCfg = Release|Any CPU
22+
{3CB4337B-100E-4DBB-9BB4-46CA2FB9794B}.Release|Any CPU.Build.0 = Release|Any CPU
23+
{AFD43908-569A-4DD3-8235-88658A819EC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
24+
{AFD43908-569A-4DD3-8235-88658A819EC9}.Debug|Any CPU.Build.0 = Debug|Any CPU
25+
{AFD43908-569A-4DD3-8235-88658A819EC9}.Release|Any CPU.ActiveCfg = Release|Any CPU
26+
{AFD43908-569A-4DD3-8235-88658A819EC9}.Release|Any CPU.Build.0 = Release|Any CPU
27+
EndGlobalSection
28+
EndGlobal

ProxyAuth/AuthMiddleware.cs

+91
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.IdentityModel.Tokens.Jwt;
4+
using System.Linq;
5+
using System.Security.Claims;
6+
using System.Security.Cryptography.X509Certificates;
7+
using System.Threading.Tasks;
8+
using Microsoft.AspNetCore.Http;
9+
using Microsoft.IdentityModel.Tokens;
10+
using Newtonsoft.Json;
11+
12+
namespace ProxyAuth
13+
{
14+
public class AuthMiddleware : IMiddleware
15+
{
16+
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
17+
{
18+
using var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
19+
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
20+
var certificate2Collection = store.Certificates.Find(X509FindType.FindByIssuerName, "localhost", false);
21+
22+
var certificate = certificate2Collection[0];
23+
24+
25+
if (!AcceptJson(context.Request.Headers) || !TryGetReturnUrl(context.Request.Query, out var returnUrl))
26+
{
27+
await next(context);
28+
return;
29+
}
30+
31+
var identity = GetIdentity();
32+
33+
var now = DateTime.UtcNow;
34+
var jwt = new JwtSecurityToken(
35+
issuer: "proxyauth",
36+
audience: "test",
37+
notBefore: now,
38+
claims: identity.Claims,
39+
expires: now.Add(TimeSpan.FromMinutes(30)),
40+
signingCredentials: new X509SigningCredentials(certificate)
41+
);
42+
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
43+
44+
if (!string.IsNullOrEmpty(returnUrl))
45+
{
46+
context.Response.Cookies.Append("access_token", encodedJwt, new CookieOptions
47+
{
48+
HttpOnly = true
49+
});
50+
context.Response.Redirect(returnUrl);
51+
return;
52+
}
53+
54+
var response = JsonConvert.SerializeObject(new { access_token = encodedJwt });
55+
context.Response.StatusCode = StatusCodes.Status200OK;
56+
context.Response.ContentType = "application/json";
57+
context.Response.ContentLength = response.Length;
58+
await context.Response.WriteAsync(response);
59+
}
60+
61+
private static bool TryGetReturnUrl(IQueryCollection query, out string returnUrl)
62+
{
63+
if (!query.TryGetValue("return_url", out var returnUrls))
64+
{
65+
returnUrl = null;
66+
return false;
67+
}
68+
69+
returnUrl = returnUrls.FirstOrDefault();
70+
return !string.IsNullOrEmpty(returnUrl);
71+
}
72+
73+
private static bool AcceptJson(IHeaderDictionary headers)
74+
{
75+
return headers.TryGetValue("Accept", out var values) && values.Any(x => x == "application/json");
76+
}
77+
78+
private ClaimsIdentity GetIdentity()
79+
{
80+
var claims = new List<Claim>
81+
{
82+
new Claim(ClaimsIdentity.DefaultNameClaimType, "testapi"),
83+
new Claim(ClaimsIdentity.DefaultRoleClaimType, "role")
84+
};
85+
var claimsIdentity =
86+
new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
87+
ClaimsIdentity.DefaultRoleClaimType);
88+
return claimsIdentity;
89+
}
90+
}
91+
}

ProxyAuth/Program.cs

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using Microsoft.AspNetCore.Hosting;
2+
using Microsoft.Extensions.Hosting;
3+
4+
namespace ProxyAuth
5+
{
6+
public class Program
7+
{
8+
public static void Main(string[] args)
9+
{
10+
CreateHostBuilder(args).Build().Run();
11+
}
12+
13+
public static IHostBuilder CreateHostBuilder(string[] args) =>
14+
Host.CreateDefaultBuilder(args)
15+
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
16+
}
17+
}
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
{
2+
"$schema": "http://json.schemastore.org/launchsettings.json",
3+
"iisSettings": {
4+
"windowsAuthentication": false,
5+
"anonymousAuthentication": true,
6+
"iisExpress": {
7+
"applicationUrl": "http://localhost:43432",
8+
"sslPort": 44365
9+
}
10+
},
11+
"profiles": {
12+
"IIS Express": {
13+
"commandName": "IISExpress",
14+
"launchBrowser": true,
15+
"launchUrl": "weatherforecast",
16+
"environmentVariables": {
17+
"ASPNETCORE_ENVIRONMENT": "Development"
18+
}
19+
},
20+
"ProxyAuth": {
21+
"commandName": "Project",
22+
"launchBrowser": true,
23+
"launchUrl": "weatherforecast",
24+
"applicationUrl": "https://localhost:5001;http://localhost:5000",
25+
"environmentVariables": {
26+
"ASPNETCORE_ENVIRONMENT": "Development"
27+
}
28+
}
29+
}
30+
}

ProxyAuth/ProxyAuth.csproj

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>netcoreapp3.1</TargetFramework>
5+
</PropertyGroup>
6+
7+
<ItemGroup>
8+
<Content Update="appsettings.Development.json">
9+
<DependentUpon>appsettings.json</DependentUpon>
10+
</Content>
11+
</ItemGroup>
12+
13+
<ItemGroup>
14+
<PackageReference Include="Newtonsoft.Json" Version="10.0.1" />
15+
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
16+
</ItemGroup>
17+
18+
19+
</Project>

ProxyAuth/Startup.cs

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using Microsoft.AspNetCore.Builder;
2+
using Microsoft.AspNetCore.Hosting;
3+
using Microsoft.Extensions.Configuration;
4+
using Microsoft.Extensions.DependencyInjection;
5+
using Microsoft.Extensions.Hosting;
6+
7+
namespace ProxyAuth
8+
{
9+
public class Startup
10+
{
11+
public Startup(IConfiguration configuration)
12+
{
13+
Configuration = configuration;
14+
}
15+
16+
public IConfiguration Configuration { get; }
17+
18+
// This method gets called by the runtime. Use this method to add services to the container.
19+
public void ConfigureServices(IServiceCollection services)
20+
{
21+
services.AddScoped<AuthMiddleware>();
22+
}
23+
24+
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
25+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
26+
{
27+
if (env.IsDevelopment())
28+
{
29+
app.UseDeveloperExceptionPage();
30+
}
31+
32+
app.UseMiddleware<AuthMiddleware>();
33+
}
34+
}
35+
}
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Debug",
5+
"Microsoft": "Debug",
6+
"Microsoft.Hosting.Lifetime": "Debug"
7+
}
8+
}
9+
}

ProxyAuth/appsettings.json

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft": "Warning",
6+
"Microsoft.Hosting.Lifetime": "Information"
7+
}
8+
},
9+
"AllowedHosts": "*"
10+
}

TestApi/Controllers/TestController.cs

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using Microsoft.AspNetCore.Authorization;
5+
using Microsoft.AspNetCore.Mvc;
6+
using Microsoft.Extensions.Logging;
7+
8+
namespace TestApi.Controllers
9+
{
10+
[ApiController]
11+
[Route("[controller]")]
12+
public class TestController : ControllerBase
13+
{
14+
private static readonly string[] Summaries =
15+
{
16+
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17+
};
18+
19+
private readonly ILogger<TestController> _logger;
20+
21+
public TestController(ILogger<TestController> logger)
22+
{
23+
_logger = logger;
24+
}
25+
26+
[Authorize]
27+
[Route("GetLogin")]
28+
public IActionResult GetLogin()
29+
{
30+
return Ok($"Ваш логин: {User.Identity.Name}");
31+
}
32+
33+
[Authorize(Roles = "role")]
34+
[Route("getrole")]
35+
public IActionResult GetRole()
36+
{
37+
return Ok("Ваша роль: role");
38+
}
39+
40+
[HttpGet]
41+
public IEnumerable<WeatherForecast> Get()
42+
{
43+
var rng = new Random();
44+
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
45+
{
46+
Date = DateTime.Now.AddDays(index),
47+
TemperatureC = rng.Next(-20, 55),
48+
Summary = Summaries[rng.Next(Summaries.Length)]
49+
})
50+
.ToArray();
51+
}
52+
}
53+
}

TestApi/Program.cs

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using Microsoft.AspNetCore.Hosting;
2+
using Microsoft.Extensions.Hosting;
3+
4+
namespace TestApi
5+
{
6+
public class Program
7+
{
8+
public static void Main(string[] args)
9+
{
10+
CreateHostBuilder(args).Build().Run();
11+
}
12+
13+
private static IHostBuilder CreateHostBuilder(string[] args) =>
14+
Host.CreateDefaultBuilder(args)
15+
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
16+
}
17+
}

0 commit comments

Comments
 (0)