Skip to content

Commit

Permalink
June 2020 update
Browse files Browse the repository at this point in the history
  • Loading branch information
scottbrady91 committed Jun 28, 2020
1 parent 46382ed commit 9c07982
Show file tree
Hide file tree
Showing 72 changed files with 3,003 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Api.NSwag/Api.NSwag.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

<ItemGroup>
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="NSwag.AspNetCore" Version="13.6.2" />
</ItemGroup>

</Project>
31 changes: 31 additions & 0 deletions Api.NSwag/Controllers/WeatherForecastController.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 Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Api.NSwag.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = {
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
26 changes: 26 additions & 0 deletions Api.NSwag/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Api.NSwag
{
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>();
});
}
}
72 changes: 72 additions & 0 deletions Api.NSwag/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using NSwag;
using NSwag.AspNetCore;
using NSwag.Generation.Processors.Security;

namespace Api.NSwag
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();

services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication("Bearer", options =>
{
options.ApiName = "api1";
options.Authority = "https://localhost:5000";
});

services.AddOpenApiDocument(options =>
{
options.DocumentName = "v1";
options.Title = "Protected API";
options.Version = "v1";

options.AddSecurity("oauth2", new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = "https://localhost:5000/connect/authorize",
TokenUrl = "https://localhost:5000/connect/token",
Scopes = new Dictionary<string, string> { { "api1", "Demo API - full access" } }
}
}
});

options.OperationProcessors.Add(new OperationSecurityScopeProcessor("oauth2"));
});
}

public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();

app.UseRouting();

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

app.UseOpenApi();
app.UseSwaggerUi3(options =>
{
options.OAuth2Client = new OAuth2ClientSettings
{
ClientId = "demo_api_swagger",
ClientSecret = null,
AppName = "Demo API - Swagger",
UsePkceWithAuthorizationCodeGrant = true
};
});

app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
}
}
15 changes: 15 additions & 0 deletions Api.NSwag/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;

namespace Api.NSwag
{
public class WeatherForecast
{
public DateTime Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string Summary { get; set; }
}
}
14 changes: 14 additions & 0 deletions Api.Swashbuckle/Api.Swashbuckle.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

<ItemGroup>
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.5.1" />
</ItemGroup>


</Project>
31 changes: 31 additions & 0 deletions Api.Swashbuckle/Controllers/WeatherForecastController.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 Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Api.Swashbuckle.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = {
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
26 changes: 26 additions & 0 deletions Api.Swashbuckle/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Api.Swashbuckle
{
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>();
});
}
}
97 changes: 97 additions & 0 deletions Api.Swashbuckle/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Api.Swashbuckle
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();

services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication("Bearer", options =>
{
options.ApiName = "api1";
options.Authority = "https://localhost:5000";
});

services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo {Title = "Protected API", Version = "v1"});

options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri("https://localhost:5000/connect/authorize"),
TokenUrl = new Uri("https://localhost:5000/connect/token"),
Scopes = new Dictionary<string, string>
{
{"api1", "Demo API - full access"}
}
}
}
});

options.OperationFilter<AuthorizeCheckOperationFilter>();
});
}

public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();

app.UseRouting();

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

app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

options.OAuthClientId("demo_api_swagger");
options.OAuthAppName("Demo API - Swagger");
options.OAuthUsePkce();
});

app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
}

public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() ||
context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any();

if (hasAuthorize)
{
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });

operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
[new OpenApiSecurityScheme {Reference = new OpenApiReference {Type = ReferenceType.SecurityScheme, Id = "oauth2"}}]
= new[] {"api1"}
}
};
}
}
}
}
15 changes: 15 additions & 0 deletions Api.Swashbuckle/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;

namespace Api.Swashbuckle
{
public class WeatherForecast
{
public DateTime Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string Summary { get; set; }
}
}
45 changes: 45 additions & 0 deletions IdentityServer/Config.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using IdentityServer4.Models;
using System.Collections.Generic;

namespace IdentityServer
{
public static class Config
{
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};

public static IEnumerable<ApiScope> ApiScopes =>
new[]
{
new ApiScope("api1", "Full access to API #1") // "full access" scope
};

public static IEnumerable<ApiResource> ApiResources =>
new[]
{
new ApiResource("api1", "API #1") {Scopes = {"api1"}}
};

public static IEnumerable<Client> Clients =>
new[]
{
// Swashbuckle & NSwag
new Client
{
ClientId = "demo_api_swagger",
ClientName = "Swagger UI for demo_api",
ClientSecrets = {new Secret("secret".Sha256())}, // change me!
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = true,
RequireClientSecret = false,
RedirectUris = {"https://localhost:5001/swagger/oauth2-redirect.html"},
AllowedCorsOrigins = {"https://localhost:5001"},
AllowedScopes = {"api1"}
}
};
}
}
Loading

0 comments on commit 9c07982

Please sign in to comment.