Skip to content

Commit

Permalink
Authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
K authored and K committed Feb 18, 2021
0 parents commit 3f3ab0e
Show file tree
Hide file tree
Showing 56 changed files with 9,599 additions and 0 deletions.
Binary file not shown.
995 changes: 995 additions & 0 deletions Auth.Demo/.vs/Auth.Demo/config/applicationhost.config

Large diffs are not rendered by default.

Binary file added Auth.Demo/.vs/Auth.Demo/v16/.suo
Binary file not shown.
13 changes: 13 additions & 0 deletions Auth.Demo/Auth.Demo.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.10" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.5.0" />
</ItemGroup>


</Project>
7 changes: 7 additions & 0 deletions Auth.Demo/Auth.Demo.csproj.user
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Controller_SelectedScaffolderID>ApiControllerWithActionsScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
</Project>
25 changes: 25 additions & 0 deletions Auth.Demo/Auth.Demo.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30907.101
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Auth.Demo", "Auth.Demo.csproj", "{C9707185-F0EF-4C41-8940-5FDD749DE729}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C9707185-F0EF-4C41-8940-5FDD749DE729}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C9707185-F0EF-4C41-8940-5FDD749DE729}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C9707185-F0EF-4C41-8940-5FDD749DE729}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C9707185-F0EF-4C41-8940-5FDD749DE729}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E0636C94-CE0B-4F0B-A0E0-48B134C03A82}
EndGlobalSection
EndGlobal
6 changes: 6 additions & 0 deletions Auth.Demo/Controllers/Inventory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Auth.Demo.Controllers
{
public class Inventory
{
}
}
32 changes: 32 additions & 0 deletions Auth.Demo/Controllers/InventoryController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Auth.Demo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class InventoryController : ControllerBase
{
// GET: api/<InventoryController>
[Authorize(Roles = "Administrator, User")]
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

[Authorize(Roles = "Administrator")]
// POST api/<InventoryController>
[HttpPost]
public void Post([FromBody] Inventory value)
{
}

}
}
51 changes: 51 additions & 0 deletions Auth.Demo/Controllers/NameController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Auth.Demo.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class NameController : ControllerBase
{

private readonly ICustomAuthenticationManager customAuthenticationManager;

public NameController(ICustomAuthenticationManager customAuthenticationManager)
{
this.customAuthenticationManager = customAuthenticationManager;
}

// GET: api/Name
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "New York", "New Jersey" };
}

// GET: api/Name/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
return "New Jersey";
}

[AllowAnonymous]
[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody] UserCred userCred)
{
var token = customAuthenticationManager.Authenticate(userCred.Username, userCred.Password);

if (token == null)
return Unauthorized();

return Ok(token);
}
}
}
8 changes: 8 additions & 0 deletions Auth.Demo/Controllers/UserCred.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Auth.Demo.Controllers
{
public class UserCred
{
public string Username { get; set; }
public string Password { get; set; }
}
}
84 changes: 84 additions & 0 deletions Auth.Demo/CustomAuthenticationHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Auth.Demo
{
public class BasicAuthenticationOptions : AuthenticationSchemeOptions
{
}
public class CustomAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
private readonly ICustomAuthenticationManager customAuthenticationManager;

public CustomAuthenticationHandler(
IOptionsMonitor<BasicAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
ICustomAuthenticationManager customAuthenticationManager)
: base(options, logger, encoder, clock)
{
this.customAuthenticationManager = customAuthenticationManager;
}

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.ContainsKey("Authorization"))
return AuthenticateResult.Fail("Unauthorized");

string authorizationHeader = Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authorizationHeader))
{
return AuthenticateResult.NoResult();
}

if (!authorizationHeader.StartsWith("bearer", StringComparison.OrdinalIgnoreCase))
{
return AuthenticateResult.Fail("Unauthorized");
}

string token = authorizationHeader.Substring("bearer".Length).Trim();

if (string.IsNullOrEmpty(token))
{
return AuthenticateResult.Fail("Unauthorized");
}

try
{
return validateToken(token);
}
catch (Exception ex)
{
return AuthenticateResult.Fail(ex.Message);
}
}

private AuthenticateResult validateToken(string token)
{
var validatedToken = customAuthenticationManager.Tokens.FirstOrDefault(t => t.Key == token);
if (validatedToken.Key == null)
{
return AuthenticateResult.Fail("Unauthorized");
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, validatedToken.Value.Item1),
new Claim(ClaimTypes.Role, validatedToken.Value.Item2)
};

var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new GenericPrincipal(identity, new[] { validatedToken.Value.Item2 });
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
}
31 changes: 31 additions & 0 deletions Auth.Demo/CustomAuthenticationManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Auth.Demo
{
public class CustomAuthenticationManager : ICustomAuthenticationManager
{
private readonly IList<User> users = new List<User>
{
new User { Username= "test1", Password= "password1", Role = "Administrator" },
new User { Username= "test2", Password= "password2", Role = "User" }
};

private readonly IDictionary<string, Tuple<string, string>> tokens =
new Dictionary<string, Tuple<string, string>>();
public IDictionary<string, Tuple<string, string>> Tokens => tokens;
public string Authenticate(string username, string password)
{
if (!users.Any(u => u.Username == username && u.Password == password))
{
return null;
}
var token = Guid.NewGuid().ToString();
tokens.Add(token, new Tuple<string, string> (username,
users.First(u => u.Username == username && u.Password == password).Role));
return token;
}
}
}
13 changes: 13 additions & 0 deletions Auth.Demo/ICustomAuthenticationManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Auth.Demo
{
public interface ICustomAuthenticationManager
{
string Authenticate(string username, string password);
IDictionary<string, Tuple<string, string>> Tokens { get; }
}
}
26 changes: 26 additions & 0 deletions Auth.Demo/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Auth.Demo
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
30 changes: 30 additions & 0 deletions Auth.Demo/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57223",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/name",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Auth.Demo": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/name",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
58 changes: 58 additions & 0 deletions Auth.Demo/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Auth.Demo
{
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.AddControllers();
var tokenKey = Configuration.GetValue<string>("TokenKey");
var key = Encoding.ASCII.GetBytes(tokenKey);

services.AddAuthentication("Basic").AddScheme<BasicAuthenticationOptions, CustomAuthenticationHandler>("Basic",null);
services.AddSingleton<ICustomAuthenticationManager, CustomAuthenticationManager>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseAuthentication();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Loading

0 comments on commit 3f3ab0e

Please sign in to comment.