Skip to content

Commit

Permalink
Merge pull request #17 from DeeJayTC/5-auth
Browse files Browse the repository at this point in the history
Add Authorization & JWT Handling
  • Loading branch information
DeeJayTC committed Apr 15, 2022
2 parents 1505017 + d7889ff commit 2dd1062
Show file tree
Hide file tree
Showing 29 changed files with 887 additions and 351 deletions.
8 changes: 0 additions & 8 deletions TCDev.APIGenerator.sln
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TCDev.APIGenerator.Caching", "src\TCDev.APIGenerator.Caching\TCDev.APIGenerator.Caching.csproj", "{0C8E23AD-AC5D-41D4-9F67-0ECF3D1C4BE1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TCDev.APIGenerator.GraphQL", "src\TCDev.APIGenerator.GraphQL\TCDev.APIGenerator.GraphQL.csproj", "{EDEA4DF4-49DF-4205-9B8E-61D76F26BA8D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TCDev.APIGenerator.Schema", "src\TCDev.APIGenerator.Schema\TCDev.APIGenerator.Schema.csproj", "{94E59385-D259-40A1-A373-1FBD0A42CD63}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApiGenerator", "ApiGenerator", "{4189D7E0-F171-4267-AC64-C9A83BB1B559}"
Expand Down Expand Up @@ -59,11 +57,6 @@ Global
{0C8E23AD-AC5D-41D4-9F67-0ECF3D1C4BE1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0C8E23AD-AC5D-41D4-9F67-0ECF3D1C4BE1}.SampleAppJson|Any CPU.ActiveCfg = SampleAppJson|Any CPU
{0C8E23AD-AC5D-41D4-9F67-0ECF3D1C4BE1}.SampleAppNuget|Any CPU.ActiveCfg = SampleAppNuget|Any CPU
{EDEA4DF4-49DF-4205-9B8E-61D76F26BA8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EDEA4DF4-49DF-4205-9B8E-61D76F26BA8D}.DebugWithSampleApp|Any CPU.ActiveCfg = DebugWithSampleApp|Any CPU
{EDEA4DF4-49DF-4205-9B8E-61D76F26BA8D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EDEA4DF4-49DF-4205-9B8E-61D76F26BA8D}.SampleAppJson|Any CPU.ActiveCfg = SampleAppJson|Any CPU
{EDEA4DF4-49DF-4205-9B8E-61D76F26BA8D}.SampleAppNuget|Any CPU.ActiveCfg = SampleAppNuget|Any CPU
{94E59385-D259-40A1-A373-1FBD0A42CD63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{94E59385-D259-40A1-A373-1FBD0A42CD63}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94E59385-D259-40A1-A373-1FBD0A42CD63}.DebugWithSampleApp|Any CPU.ActiveCfg = DebugWithSampleApp|Any CPU
Expand Down Expand Up @@ -106,7 +99,6 @@ Global
{FE869C02-6C9A-4D9B-BBE2-56F1B21B2A55} = {4189D7E0-F171-4267-AC64-C9A83BB1B559}
{303BF897-594C-4911-91CF-3887A8B8E839} = {8CC9B68F-E1C2-45B3-8814-B9FF4E1B2AB8}
{0C8E23AD-AC5D-41D4-9F67-0ECF3D1C4BE1} = {4189D7E0-F171-4267-AC64-C9A83BB1B559}
{EDEA4DF4-49DF-4205-9B8E-61D76F26BA8D} = {4189D7E0-F171-4267-AC64-C9A83BB1B559}
{94E59385-D259-40A1-A373-1FBD0A42CD63} = {4189D7E0-F171-4267-AC64-C9A83BB1B559}
{BA9E04E6-4B66-4369-9B2F-C6CEC9499851} = {8CC9B68F-E1C2-45B3-8814-B9FF4E1B2AB8}
{7F3574D1-7421-4824-A0BB-522F3BC9BAC4} = {4189D7E0-F171-4267-AC64-C9A83BB1B559}
Expand Down
3 changes: 3 additions & 0 deletions sample/ApiGeneratorSampleApp/ApiDefinition.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
"name": "MakeJSON",
"route": "/MakeJSON",
"idType": "int",
"authorize": true,
"scopesRead": [ "all.read" ],
"scopesWrite": [ "all.write" ],
"Fields": [
{
"name": "Name",
Expand Down
37 changes: 33 additions & 4 deletions sample/ApiGeneratorSampleApp/Model/Car.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
namespace ApiGeneratorSampleApI.Model
{

[Api("/car")]
public class Car : IObjectBase<Guid>
[Api("/car",
authorize: true,
requiredReadScopes: new string[] { "car.read" },
requiredWriteScopes: new string[] { "car.write" })]
public class Car : IObjectBase<Guid>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Expand All @@ -24,11 +27,16 @@ public class Car : IObjectBase<Guid>
public string Color { get; set; }

public Make? Make { get; set; }

public Model? Model { get; set; }
}


[Api("/carMakes")]
public class Make : IObjectBase<Guid>
[Api("/carMakes",
authorize: true,
requiredReadScopes: new string[] { "make.read" },
requiredWriteScopes: new string[] { "make.write" })]
public class Make : IObjectBase<Guid>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Expand All @@ -37,5 +45,26 @@ public class Make : IObjectBase<Guid>
public string Name { get; set; }

public string Description { get; set; }


public Model? Model { get; set; }
}



[Api("/carModel",
authorize: true,
requiredReadScopes: new string[] { "model.read" },
requiredWriteScopes: new string[] { "model.write" })]
public class Model : IObjectBase<Guid>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[SwaggerIgnore]
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; }

public string Description { get; set; }
}

}
6 changes: 3 additions & 3 deletions sample/ApiGeneratorSampleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using TCDev.ApiGenerator.Extension;
using TCDev.APIGenerator.Identity;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

//builder.Services.AddApiGeneratorServices(builder.Configuration, JsonClassBuilder.CreateClass());
builder.Services.AddApiGeneratorIdentity(builder.Configuration);
builder.Services.AddApiGeneratorServices(builder.Configuration, Assembly.GetExecutingAssembly());

var app = builder.Build();
Expand All @@ -23,8 +24,7 @@
app.UseStaticFiles();
app.UseRouting();

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

app.UseEndpoints(endpoints =>
{
Expand Down
4 changes: 2 additions & 2 deletions sample/ApiGeneratorSampleApp/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ For more info see https://aka.ms/dotnet-template-ms-identity-platform
"Api": {
"Swagger": {
"EnableProduction": "false", // Enable/Disable for production builds
"Description": "Sample Swagger Config",
"Description": "Smoower API Sample",
"Version": "v1",
"Title": "ssass Swagger Config Title",
"Title": "Smoower sample config",
"ContactMail": "Me@me.de",
"ContactUri": "https://www.myuri.com"
},
Expand Down
2 changes: 1 addition & 1 deletion sample/SampleAppJson/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseAutomaticApiMigrations();
app.UseHttpsRedirection();

app.UseAuthorization();
Expand Down
41 changes: 41 additions & 0 deletions src/TCDev.APIGenerator.Identity/ServiceExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace TCDev.APIGenerator.Identity
{
public static class ServiceExtension
{
public static IServiceCollection ConfigureIdentity(this IServiceCollection services, IConfiguration configuration)
{
string domain = $"https://{configuration["Auth0:Domain"]}/";
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = domain;
options.Audience = configuration["Auth0:Audience"];
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.NameIdentifier
};
});


return services;
}

public static IApplicationBuilder UseApiGeneratorAuthentication(this IApplicationBuilder app)
{
app.UseAuthentication();
app.UseAuthorization();

return app;
}


}
}
13 changes: 13 additions & 0 deletions src/TCDev.APIGenerator.Identity/TCDev.APIGenerator.Identity.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.3" />
</ItemGroup>

</Project>
86 changes: 56 additions & 30 deletions src/TCDev.APIGenerator.Schema/JsonClassDefinition.cs
Original file line number Diff line number Diff line change
@@ -1,45 +1,71 @@
using Newtonsoft.Json;
// TCDev.de 2022/04/07
// TCDev.APIGenerator.Schema.JsonClassDefinition.cs
// https://github.com/DeeJayTC/net-dynamic-api

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace TCDev.APIGenerator.Schema
{
[Flags]
public enum Events
{
POST,
PUT,
DELETE,
ALL = POST | PUT | DELETE
}
[Flags]
public enum Events
{
POST,
PUT,
DELETE,
ALL = POST | PUT | DELETE
}


public class JsonClassDefinition
{
public string Name { get; set; }

[JsonProperty("route")]
public string RouteTemplate { get; set; } = "/";

[JsonProperty("caching")]
public bool EnableCaching { get; set; }

[JsonProperty("idType")]
public string IdType { get; set; } = "int";

public bool Authorize { get; set; } = false;

public class JsonClassDefinition
{
public string Name { get; set; }
[JsonProperty("ScopesRead")]
public List<string> ScopesReadList { get; set; } = new List<string>();

[JsonProperty("route")]
public string RouteTemplate { get; set; } = "/";
[JsonProperty("ScopesWrite")]
public List<string> ScopesWriteList { get; set; } = new List<string>();

[JsonProperty("caching")]
public bool EnableCaching { get; set; } = false;

[JsonProperty("idType")]
public string IdType { get; set; } = "int";
[JsonIgnore]
public string ScopesRead {
get
{
return ScopesReadList.Any() ? string.Join(",", ScopesReadList.Select(p => $"\"{p}\"").ToList()) : string.Empty;
}
}
[JsonIgnore]
public string ScopesWrite
{
get
{
return ScopesWriteList.Any() ? string.Join(",", ScopesWriteList.Select(p => $"\"{p}\"").ToList()) : string.Empty;
}
}

public List<Field> Fields { get; set; }
}
public List<Field> Fields { get; set; }
}


public class Field
{
public string Name { get; set; }
public string Type { get; set; }
public bool Nullable { get; set; }
}
public class Field
{
public string Name { get; set; }
public string Type { get; set; }
public bool Nullable { get; set; }
public string MaxLength { get; set; }
}
}
54 changes: 54 additions & 0 deletions src/TCDev.APIGenerator/Attributes/ApiAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// TCDev.de 2022/04/10
// TCDev.APIGenerator.ApiAttribute.cs
// https://github.com/DeeJayTC/net-dynamic-api

using System;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace TCDev.ApiGenerator.Attributes
{
[AttributeUsage(AttributeTargets.Class)]
public class ApiAttribute : Attribute
{
/// <summary>
/// Attribute defining auto generated controller for the class
/// </summary>
/// <param name="route">The full base route for the class ie /myclass/ </param>
/// <param name="requiredReadScopes"></param>
/// <param name="requiredWriteScopes"></param>
/// <param name="fireEvents"></param>
/// <param name="authorize"></param>
/// <param name="cache"></param>
/// <param name="cacheDuration"></param>
/// <param name="methods">The methods to generate for this endpoint</param>
public ApiAttribute(
string route,
ApiMethodsToGenerate methods = ApiMethodsToGenerate.All,
string[] requiredReadScopes = null,
string[] requiredWriteScopes = null,
bool fireEvents = false,
bool authorize = true,
bool cache = false,
int cacheDuration = 50000)
{
this.Route = route;
this.Options = new ApiAttributeAttributeOptions
{
RequiredReadScopes = requiredReadScopes,
RequiredWriteScopes = requiredWriteScopes,
Authorize = authorize,
Cache = cache,
CacheDuration = cacheDuration,
FireEvents = fireEvents,
Methods = methods
};
}

public string Route { get; set; }
public ApiAttributeAttributeOptions Options { get; set; }

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ public class ApiAttributeAttributeOptions
/// <summary>
/// Claims required for read access
/// </summary>
public string[] RequiredReadClaims { get; set; } = new string[0];
public string[] RequiredReadScopes { get; set; } = new string[0];

/// <summary>
/// Claims required for write access
/// </summary>
public string[] RequiredWriteClaims { get; set; } = new string[0];
public string[] RequiredWriteScopes { get; set; } = new string[0];

/// <summary>
/// Wether authorized access is required or not
/// </summary>
public bool Authorize { get; set; } = true;
public bool Authorize { get; set; } = false;

/// <summary>
/// Cache responses
Expand Down

0 comments on commit 2dd1062

Please sign in to comment.