Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/add auth #44

Merged
merged 6 commits into from
Apr 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ docker-compose -d up postgres
```
dotnet ef migrations add <Migration-name> --project DeUrgenta.Domain --startup-project DeUrgenta.Api
```
### Adding EF Core migration to User.Api
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eu aici in readme as pune si cum sa rulam database update

dotnet ef database update --startup-project ..\DeUrgenta.Api --context UserDbContext

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@trupci do we need this ? because we call Migrate database when adding db context

```
DeUrgenta.User.Api> dotnet ef migrations add Identity_initial_create --startup-project ..\DeUrgenta.Api\ -o Domain\Migrations --context UserDbContext
```

## Feedback

Expand Down
2 changes: 0 additions & 2 deletions Src/DeUrgenta.Admin.Api/Controller/BlogController.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using DeUrgenta.Admin.Api.Models;
using DeUrgenta.Admin.Api.Swagger;
using DeUrgenta.Admin.Api.Swagger.Blog;
using DeUrgenta.Common.Models;
using DeUrgenta.Common.Swagger;
Expand Down
1 change: 0 additions & 1 deletion Src/DeUrgenta.Admin.Api/Controller/EventsController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using DeUrgenta.Admin.Api.Models;
using DeUrgenta.Admin.Api.Swagger.Events;
Expand Down
10 changes: 0 additions & 10 deletions Src/DeUrgenta.Api/ApiAuthenticationScheme.cs

This file was deleted.

37 changes: 0 additions & 37 deletions Src/DeUrgenta.Api/AuthorizeCheckOperationFilter.cs

This file was deleted.

2 changes: 0 additions & 2 deletions Src/DeUrgenta.Api/DeUrgenta.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@

<ItemGroup>
<PackageReference Include="Hellang.Middleware.ProblemDetails" Version="5.3.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
54 changes: 54 additions & 0 deletions Src/DeUrgenta.Api/Extensions/AuthorizeCheckOperationFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace DeUrgenta.Api.Extensions
{
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var attributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true));

if (attributes.OfType<IAllowAnonymous>().Any())
{
return;
}

var authAttributes = attributes.OfType<IAuthorizeData>();

if (authAttributes.Any())
{
operation.Responses["401"] = new OpenApiResponse { Description = "Unauthorized" };

if (authAttributes.Any(att => !String.IsNullOrWhiteSpace(att.Roles) || !String.IsNullOrWhiteSpace(att.Policy)))
{
operation.Responses["403"] = new OpenApiResponse { Description = "Forbidden" };
}

operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "BearerAuth",
Type = ReferenceType.SecurityScheme
}
},
Array.Empty<string>()
}
}
};
}
}

}
}
47 changes: 26 additions & 21 deletions Src/DeUrgenta.Api/Extensions/SwaggerExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,43 +1,31 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using DeUrgenta.Infra.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
using Swashbuckle.AspNetCore.SwaggerUI;

namespace DeUrgenta.Api.Extensions
{
public static class SwaggerExtensions
{
public static IServiceCollection AddSwaggerFor(this IServiceCollection services, Assembly[] assemblies, IConfiguration config)
{
var authorizeEndpoint = $"{config.GetValue<string>("IdentityServerUrl")}/connect/authorize";
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Flows = new OpenApiOAuthFlows
{
Implicit = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri(authorizeEndpoint),
Scopes = new Dictionary<string, string>
{
{ "usersApi", "Access read operations" },
{ "backpackApi", "Access write operations" }
}
}
},
Description =
"JWT Authorization header using the Bearer scheme",
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = JwtBearerDefaults.AuthenticationScheme.ToLowerInvariant(),
In = ParameterLocation.Header,
Type = SecuritySchemeType.OAuth2,
Scheme = "Bearer"
Name = "Authorization",
BearerFormat = "JWT",
Description = "JWT Authorization header using the Bearer scheme."
});

c.OperationFilter<AuthorizeCheckOperationFilter>();
Expand Down Expand Up @@ -72,9 +60,26 @@ public static IServiceCollection AddSwaggerFor(this IServiceCollection services,
c.ExampleFilters();
});


services.AddSwaggerExamplesFromAssemblies(assemblies);
return services;
}

public static IApplicationBuilder UseConfigureSwagger(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.ConfigObject = new ConfigObject
{
Urls = new[]
{
new UrlDescriptor{Name = "api", Url = "/swagger/v1/swagger.json"}
}
};

});

return app;
}
}
}
62 changes: 12 additions & 50 deletions Src/DeUrgenta.Api/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
using System.Collections.Generic;
using System.Reflection;
using DeUrgenta.Admin.Api.Controller;
using DeUrgenta.Backpack.Api.Controllers;
using DeUrgenta.Certifications.Api.Controller;
using DeUrgenta.Api.Extensions;
using DeUrgenta.Common.Swagger;
using DeUrgenta.Domain;
using DeUrgenta.Group.Api.Controllers;
using Hellang.Middleware.ProblemDetails;
using DeUrgenta.Infra.Extensions;
using DeUrgenta.User.Api.Controller;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Hosting;
using DeUrgenta.User.Api.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Swashbuckle.AspNetCore.SwaggerUI;

namespace DeUrgenta.Api
{
Expand All @@ -27,48 +25,26 @@ public Startup(IConfiguration configuration, IWebHostEnvironment environment)
{
Configuration = configuration;
WebHostEnvironment = environment;
_swaggerClientName = configuration.GetValue<string>("SwaggerOidcClientName");
}

public IConfiguration Configuration { get; }
public IWebHostEnvironment WebHostEnvironment { get; }
public List<ApiAuthenticationScheme> AuthSchemes { get; set; }

private string _swaggerClientName;
private string _corsPolicyName;
private const string CorsPolicyName = "MyPolicy";

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();

var identityUrl = Configuration.GetValue<string>("IdentityServerUrl");
var apiSchemes = new List<ApiAuthenticationScheme>();

Configuration.GetSection("ApiConfiguration").Bind(apiSchemes);
var serviceBuilder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme);
foreach (var authScheme in apiSchemes)
{
serviceBuilder = serviceBuilder.AddIdentityServerAuthentication(authScheme.SchemeName, options =>
{
options.Authority = identityUrl;
options.ApiName = authScheme.ApiName;
options.ApiSecret = authScheme.ApiSecret;
options.RequireHttpsMetadata = !WebHostEnvironment.IsDevelopment();
});
}

services.AddDatabase(Configuration.GetConnectionString("DbConnectionString"));
services.AddDatabase<DeUrgentaContext>(Configuration.GetConnectionString("DbConnectionString"));
services.AddExceptionHandling(WebHostEnvironment);

services.AddBearerAuth(Configuration);

var applicationAssemblies = GetAssemblies();

services.AddSwaggerFor(applicationAssemblies, Configuration);
services.AddMediatR(applicationAssemblies);

_corsPolicyName = "MyPolicy";
services.AddCors(o => o.AddPolicy(_corsPolicyName, builder =>
services.AddCors(o => o.AddPolicy(CorsPolicyName, builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
Expand All @@ -78,38 +54,24 @@ public void ConfigureServices(IServiceCollection services)
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, Domain.DeUrgentaContext dbContext)
public void Configure(IApplicationBuilder app)
{
dbContext.Database.Migrate();
app.UseCors(_corsPolicyName);

if (WebHostEnvironment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseProblemDetails();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.OAuthClientId(_swaggerClientName);
c.OAuthAppName("Swagger UI");
c.ConfigObject = new ConfigObject
{
Urls = new[]
{
new UrlDescriptor{Name = "api", Url = "/swagger/v1/swagger.json"}
}
};

});
app.UseConfigureSwagger();

app.UseHttpsRedirection();

app.UseRouting();

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

app.UseCors(CorsPolicyName);

app.UseEndpoints(endpoints => endpoints.MapControllers());

}
Expand Down
40 changes: 13 additions & 27 deletions Src/DeUrgenta.Api/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,32 +1,18 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DbConnectionString": "Server=localhost;Port=5432;Database=de-urgenta-db;User Id=docker;Password=docker;"
},
"SwaggerOidcClientName": "swaggerClientLocalhost",
"ApiConfiguration": [
{
"SchemeName": "backpackApiAuthenticationScheme",
"ApiName": "backpackApi",
"ApiSecret": "svpqYnJSR8xzn8Rl"
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
{
"SchemeName": "usersApiAuthenticationScheme",
"ApiName": "usersApi",
"ApiSecret": "st4k!b7s$af201cv"
"AllowedHosts": "*",
"ConnectionStrings": {
"DbConnectionString": "Server=localhost;Port=5432;Database=de-urgenta-db;User Id=docker;Password=docker;",
"IdentityDbConnectionString": "Server=localhost;Port=5432;Database=de-urgenta-db;User Id=docker;Password=docker;"
},
{
"SchemeName": "certificationsApiAuthenticationScheme",
"ApiName": "certificationsApi",
"ApiSecret": "Mfrf5DIry96z851k"
"JwtConfig": {
"Secret": "llvudfvkwvepwkdnsnwmuulyvtrawppf",
"TokenExpirationInSeconds": 3600
}
],
"IdentityServerUrl": "https://localhost:5001"
}
Loading