Skip to content

Commit

Permalink
dotnet 5 port and Adding Basic Auth
Browse files Browse the repository at this point in the history
Large number of changes throughout including:

- Port code to dotnet 5
- Adding BasicAuth option
- Adding POST to the previous GET calls
- Removing version drafter GitHub Action
- Removing unused Azure DevOps YML build pipelines
- Removing the GitHub Action temporarily
- Adding a Deploy to Azure button.
  • Loading branch information
joelbyford authored Jan 25, 2021
2 parents 04a7e42 + f1d5c60 commit a82706b
Show file tree
Hide file tree
Showing 16 changed files with 294 additions and 186 deletions.
4 changes: 0 additions & 4 deletions .github/release-drafter.yml

This file was deleted.

35 changes: 0 additions & 35 deletions .github/workflows/dotnetcore-build.yml

This file was deleted.

31 changes: 0 additions & 31 deletions .github/workflows/dotnetcore-deploy.yml

This file was deleted.

14 changes: 0 additions & 14 deletions .github/workflows/release-drafter.yml

This file was deleted.

8 changes: 0 additions & 8 deletions .whitesource

This file was deleted.

113 changes: 113 additions & 0 deletions DeployTemplates/AzureLinuxWebAppArm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.1",
"parameters": {
"siteName": {
"type": "string",
"defaultValue": "[concat('WebApp-', uniqueString(resourceGroup().id))]",
"metadata": {
"description": "The name of the WebApp/ApiApp being deployed"
}
},
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Location for all resources."
}
},
"sku": {
"type": "string",
"allowedValues": [
"F1",
"D1",
"B1",
"B2",
"B3",
"S1",
"S2",
"S3",
"P1",
"P2",
"P3",
"P4"
],
"defaultValue": "F1",
"metadata": {
"description": "The pricing tier for the hosting plan."
}
},
"workerSize": {
"type": "string",
"allowedValues": [
"0",
"1",
"2"
],
"defaultValue": "0",
"metadata": {
"description": "The instance size of the hosting plan (small, medium, or large)."
}
},
"repoURL": {
"type": "string",
"defaultValue": "https://github.com/joelbyford/QrCodeApiApp.git",
"metadata": {
"description": "The URL for the GitHub repository *CHANGE IF YOU HAVE FORKED THIS REPO*."
}
},
"branch": {
"type": "string",
"defaultValue": "master",
"metadata": {
"description": "The branch of the GitHub repository to use."
}
}
},
"variables": {
"hostingPlanName": "[concat('hpn-', resourceGroup().name)]"
},
"resources": [
{
"type": "Microsoft.Web/serverfarms",
"apiVersion": "2020-06-01",
"name": "[variables('hostingPlanName')]",
"location": "[parameters('location')]",
"sku": {
"name": "[parameters('sku')]",
"capacity": "[parameters('workerSize')]"
},
"properties": {
"name": "[variables('hostingPlanName')]"
}
},
{
"type": "Microsoft.Web/sites",
"apiVersion": "2020-06-01",
"name": "[parameters('siteName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
],
"properties": {
"serverFarmId": "[variables('hostingPlanName')]"
},
"resources": [
{
"type": "sourcecontrols",
"apiVersion": "2020-06-01",
"name": "web",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Web/sites', parameters('siteName'))]"
],
"properties": {
"repoUrl": "[parameters('repoURL')]",
"branch": "[parameters('branch')]",
"isManualIntegration": true
}
}
]
}
]
}
13 changes: 6 additions & 7 deletions QrCodeApiApp/Controllers/EncodeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,18 @@ public class EncodeController : ControllerBase

// GET api/encode
[HttpGet]
public ActionResult<FileStreamResult> Get([RequiredFromQuery] string text, int size=250)
public FileResult Get([RequiredFromQuery] string text, int size=250)
{
return QrEncode(text, size);
}

// POST api/encode
// TODO: Add support for posting data instead of using a GET

//[HttpPost]
//public ActionResult<Bitmap> Post([FromBody] string text)
//{
// return QrEncode(text);
//}
[HttpPost]
public FileResult Post([FromBody] string body, int size=250)
{
return QrEncode(body, size);
}

private FileResult QrEncode(string value, int size=250, Bitmap bgImage=null )
{
Expand Down
8 changes: 4 additions & 4 deletions QrCodeApiApp/QrCodeApiApp.csproj
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="joelbyford.BasicAuth" Version="1.0.0" />
<PackageReference Include="Microsoft.OpenApi" Version="1.2.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
<PackageReference Include="System.Drawing.Common" Version="5.0.0" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="ZXing.Net" Version="0.16.6" />
</ItemGroup>

Expand Down
44 changes: 37 additions & 7 deletions QrCodeApiApp/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using joelbyford;
using System.IO;
using System.Text.Json;

namespace QrCodeApiApp
{
Expand All @@ -25,23 +29,49 @@ public Startup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc(o => o.InputFormatters.Insert(0, new TxtInputFormatter()));
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v5", new OpenApiInfo { Title = "QrCodeApiApp", Version = "v5" });
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "QrCodeApiApp v5"));
}
else
{
app.UseHsts();
//Insert the Basic Authentication Middleware handler *ONLY IF* it was enabled in appsettings.json
bool basicAuthEnabled = this.Configuration.GetValue<bool>("AppSettings:BasicAuth:Enabled");

if (basicAuthEnabled)
{
//Uses values from "BasicAuth" under "AppSettings" in the appsettings.json
String basicAuthRealm = this.Configuration.GetValue<String>("AppSettings:BasicAuth:Realm");
String basicAuthUserJson = this.Configuration.GetValue<String>("AppSettings:BasicAuth:UsersJson");

// Using the BasicAuth NuGet package from https://github.com/joelbyford/BasicAuth
Dictionary<string, string> basicAuthUsers = new Dictionary<string, string>();
var packageJson = File.ReadAllText(basicAuthUserJson);
basicAuthUsers = JsonSerializer.Deserialize<Dictionary<string, string>>(packageJson);
app.UseMiddleware<joelbyford.BasicAuth>(basicAuthRealm, basicAuthUsers);
}

app.UseHttpsRedirection();
app.UseMvc();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
52 changes: 52 additions & 0 deletions QrCodeApiApp/TxtInputFormatter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;

namespace QrCodeApiApp
{

// Thanks to https://github.com/RickStrahl/AspNetCoreRawRequestSample for the starting example here.
public class TxtInputFormatter : InputFormatter
{
public TxtInputFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}

//Accept text/plain and text/csv only
public override Boolean CanRead(InputFormatterContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));

var contentType = context.HttpContext.Request.ContentType;

if (contentType == "text/plain")
return true;
else
return false;
}

// handle the raw text input
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
var contentType = context.HttpContext.Request.ContentType;


if (contentType == "text/plain")
{
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync();
return await InputFormatterResult.SuccessAsync(content);
}
}

return await InputFormatterResult.FailureAsync();
}
}
}
Loading

0 comments on commit a82706b

Please sign in to comment.