Skip to content
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// using System.Globalization;
// using System.Linq;
// using System.Net;
// using System.Threading.Tasks;

// using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions;
// using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Configurations;
// using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Extensions;

// namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.FunctionApp.V3Static.Configurations
// {
// public class OpenApiHttpTriggerAuthorization : DefaultOpenApiHttpTriggerAuthorization
// {
// public override async Task<OpenApiAuthorizationResult> AuthorizeAsync(IHttpRequestDataObject req)
// {
// var result = default(OpenApiAuthorizationResult);
// var authtoken = (string) req.Headers["Authorization"];
// if (authtoken.IsNullOrWhiteSpace())
// {
// result = new OpenApiAuthorizationResult()
// {
// StatusCode = HttpStatusCode.Unauthorized,
// ContentType = "text/plain",
// Payload = "Unauthorized",
// };

// return await Task.FromResult(result).ConfigureAwait(false);
// }

// if (authtoken.StartsWith("Bearer", ignoreCase: true, CultureInfo.InvariantCulture) == false)
// {
// result = new OpenApiAuthorizationResult()
// {
// StatusCode = HttpStatusCode.Unauthorized,
// ContentType = "text/plain",
// Payload = "Invalid auth format",
// };

// return await Task.FromResult(result).ConfigureAwait(false);
// }

// var token = authtoken.Split(' ').Last();
// if (token != "secret")
// {
// result = new OpenApiAuthorizationResult()
// {
// StatusCode = HttpStatusCode.Forbidden,
// ContentType = "text/plain",
// Payload = "Invalid auth token",
// };

// return await Task.FromResult(result).ConfigureAwait(false);
// }

// return await Task.FromResult(result).ConfigureAwait(false);
// }
// }
// }
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Azure.Functions.Worker.Extensions.OpenApi.Functions;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Linq;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
Expand All @@ -15,10 +16,44 @@ namespace Microsoft.Azure.Functions.Worker.Extensions.OpenApi.Extensions
public static class OpenApiHttpRequestDataExtensions
{
/// <summary>
/// Gets the <see cref="QueryCollection"/> instance from the <see cref="HttpRequestData"/>.
/// Gets the <see cref="IHeaderDictionary"/> instance from the <see cref="HttpRequestData"/>.
/// </summary>
/// <param name="req"><see cref="HttpRequestData"/> instance.</param>
/// <returns>Returns <see cref="QueryCollection"/> instance.</returns>
/// <returns>Returns <see cref="IHeaderDictionary"/> instance.</returns>
public static IHeaderDictionary Headers(this HttpRequestData req)
{
req.ThrowIfNullOrDefault();

var headers = req.Headers.ToDictionary(p => p.Key, p => new StringValues(p.Value.ToArray()));
if (headers.IsNullOrDefault() || headers.Any() == false)
{
headers = new Dictionary<string, StringValues>();
}

return new HeaderDictionary(headers);
}

/// <summary>
/// Gets the <see cref="StringValues"/> object from the header of <see cref="HttpRequestData"/>.
/// </summary>
/// <param name="req"><see cref="HttpRequestData"/> instance.</param>
/// <param name="key">Header key.</param>
/// <returns>Returns <see cref="StringValues"/> object.</returns>
public static StringValues Header(this HttpRequestData req, string key)
{
req.ThrowIfNullOrDefault();

var headers = Headers(req);
var value = headers.ContainsKey(key) ? headers[key] : new StringValues(default(string));

return value;
}

/// <summary>
/// Gets the <see cref="IQueryCollection"/> instance from the <see cref="HttpRequestData"/>.
/// </summary>
/// <param name="req"><see cref="HttpRequestData"/> instance.</param>
/// <returns>Returns <see cref="IQueryCollection"/> instance.</returns>
public static IQueryCollection Queries(this HttpRequestData req)
{
req.ThrowIfNullOrDefault();
Expand All @@ -33,7 +68,7 @@ public static IQueryCollection Queries(this HttpRequestData req)
}

/// <summary>
/// Gets the <see cref="StringValues"/> object from the <see cref="HttpRequestData"/>.
/// Gets the <see cref="StringValues"/> object from the querystring of <see cref="HttpRequestData"/>.
/// </summary>
/// <param name="req"><see cref="HttpRequestData"/> instance.</param>
/// <param name="key">Querystring key.</param>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Threading.Tasks;

using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Extensions;
using Microsoft.Extensions.Logging;

Expand Down Expand Up @@ -37,20 +38,34 @@ public async Task<HttpResponseData> RenderSwaggerDocument(HttpRequestData req, s
log.LogInformation($"swagger.{extension} was requested.");

var fi = new FileInfo(ctx.FunctionDefinition.PathToAssembly);
var request = new HttpRequestObject(req);
var result = default(string);
var response = default(HttpResponseData);
try
{
result = await (await this._context.SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin: false))
.Document
.InitialiseDocument()
.AddMetadata(this._context.OpenApiConfigurationOptions.Info)
.AddServer(new HttpRequestObject(req), this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
.AddNamingStrategy(this._context.NamingStrategy)
.AddVisitors(this._context.GetVisitorCollection())
.Build(this._context.ApplicationAssembly, this._context.OpenApiConfigurationOptions.OpenApiVersion)
.RenderAsync(this._context.GetOpenApiSpecVersion(this._context.OpenApiConfigurationOptions.OpenApiVersion), this._context.GetOpenApiFormat(extension))
.ConfigureAwait(false);
var auth = await this._context
.SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin: false)
.AuthorizeAsync(request)
.ConfigureAwait(false);
if (!auth.IsNullOrDefault())
{
response = req.CreateResponse(auth.StatusCode);
response.Headers.Add("Content-Type", auth.ContentType);
await response.WriteStringAsync(auth.Payload).ConfigureAwait(false);

return response;
}

result = await this._context
.Document
.InitialiseDocument()
.AddMetadata(this._context.OpenApiConfigurationOptions.Info)
.AddServer(request, this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
.AddNamingStrategy(this._context.NamingStrategy)
.AddVisitors(this._context.GetVisitorCollection())
.Build(this._context.ApplicationAssembly, this._context.OpenApiConfigurationOptions.OpenApiVersion)
.RenderAsync(this._context.GetOpenApiSpecVersion(this._context.OpenApiConfigurationOptions.OpenApiVersion), this._context.GetOpenApiFormat(extension))
.ConfigureAwait(false);

response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", this._context.GetOpenApiFormat(extension).GetContentType());
Expand Down Expand Up @@ -82,20 +97,34 @@ public async Task<HttpResponseData> RenderOpenApiDocument(HttpRequestData req, s
log.LogInformation($"{version}.{extension} was requested.");

var fi = new FileInfo(ctx.FunctionDefinition.PathToAssembly);
var request = new HttpRequestObject(req);
var result = default(string);
var response = default(HttpResponseData);
try
{
result = await (await this._context.SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin: false))
.Document
.InitialiseDocument()
.AddMetadata(this._context.OpenApiConfigurationOptions.Info)
.AddServer(new HttpRequestObject(req), this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
.AddNamingStrategy(this._context.NamingStrategy)
.AddVisitors(this._context.GetVisitorCollection())
.Build(this._context.ApplicationAssembly, this._context.GetOpenApiVersionType(version))
.RenderAsync(this._context.GetOpenApiSpecVersion(version), this._context.GetOpenApiFormat(extension))
.ConfigureAwait(false);
var auth = await this._context
.SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin: false)
.AuthorizeAsync(request)
.ConfigureAwait(false);
if (!auth.IsNullOrDefault())
{
response = req.CreateResponse(auth.StatusCode);
response.Headers.Add("Content-Type", auth.ContentType);
await response.WriteStringAsync(auth.Payload).ConfigureAwait(false);

return response;
}

result = await this._context
.Document
.InitialiseDocument()
.AddMetadata(this._context.OpenApiConfigurationOptions.Info)
.AddServer(request, this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
.AddNamingStrategy(this._context.NamingStrategy)
.AddVisitors(this._context.GetVisitorCollection())
.Build(this._context.ApplicationAssembly, this._context.GetOpenApiVersionType(version))
.RenderAsync(this._context.GetOpenApiSpecVersion(version), this._context.GetOpenApiFormat(extension))
.ConfigureAwait(false);

response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", this._context.GetOpenApiFormat(extension).GetContentType());
Expand Down Expand Up @@ -126,17 +155,31 @@ public async Task<HttpResponseData> RenderSwaggerUI(HttpRequestData req, Functio
log.LogInformation("SwaggerUI page was requested.");

var fi = new FileInfo(ctx.FunctionDefinition.PathToAssembly);
var request = new HttpRequestObject(req);
var result = default(string);
var response = default(HttpResponseData);
try
{
result = await (await this._context.SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin: false))
.SwaggerUI
.AddMetadata(this._context.OpenApiConfigurationOptions.Info)
.AddServer(new HttpRequestObject(req), this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
.BuildAsync(this._context.PackageAssembly, this._context.OpenApiCustomUIOptions)
.RenderAsync("swagger.json", this._context.GetDocumentAuthLevel(), this._context.GetSwaggerAuthKey())
.ConfigureAwait(false);
var auth = await this._context
.SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin: false)
.AuthorizeAsync(request)
.ConfigureAwait(false);
if (!auth.IsNullOrDefault())
{
response = req.CreateResponse(auth.StatusCode);
response.Headers.Add("Content-Type", auth.ContentType);
await response.WriteStringAsync(auth.Payload).ConfigureAwait(false);

return response;
}

result = await this._context
.SwaggerUI
.AddMetadata(this._context.OpenApiConfigurationOptions.Info)
.AddServer(request, this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
.BuildAsync(this._context.PackageAssembly, this._context.OpenApiCustomUIOptions)
.RenderAsync("swagger.json", this._context.GetDocumentAuthLevel(), this._context.GetSwaggerAuthKey())
.ConfigureAwait(false);

response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", ContentTypeHtml);
Expand Down Expand Up @@ -167,16 +210,21 @@ public async Task<HttpResponseData> RenderOAuth2Redirect(HttpRequestData req, Fu
log.LogInformation("The oauth2-redirect.html page was requested.");

var fi = new FileInfo(ctx.FunctionDefinition.PathToAssembly);
var request = new HttpRequestObject(req);
var result = default(string);
var response = default(HttpResponseData);
try
{
result = await (await this._context.SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin: false))
.SwaggerUI
.AddServer(new HttpRequestObject(req), this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
.BuildOAuth2RedirectAsync(this._context.PackageAssembly)
.RenderOAuth2RedirectAsync("oauth2-redirect.html", this._context.GetDocumentAuthLevel(), this._context.GetSwaggerAuthKey())
.ConfigureAwait(false);
await this._context
.SetApplicationAssemblyAsync(fi.Directory.FullName, appendBin: false)
.ConfigureAwait(false);

result = await this._context
.SwaggerUI
.AddServer(request, this._context.HttpSettings.RoutePrefix, this._context.OpenApiConfigurationOptions)
.BuildOAuth2RedirectAsync(this._context.PackageAssembly)
.RenderOAuth2RedirectAsync("oauth2-redirect.html", this._context.GetDocumentAuthLevel(), this._context.GetSwaggerAuthKey())
.ConfigureAwait(false);

response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", ContentTypeHtml);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public HttpRequestObject(HttpRequestData req)
? new HostString(req.Url.Authority)
: new HostString(req.Url.Host, req.Url.Port);

this.Headers = req.Headers();
this.Query = req.Queries();
this.Body = req.Body;
}
Expand All @@ -37,6 +38,9 @@ public HttpRequestObject(HttpRequestData req)
/// <inheritdoc/>
public virtual HostString Host { get; }

/// <inheritdoc/>
public virtual IHeaderDictionary Headers { get; }

/// <inheritdoc/>
public virtual IQueryCollection Query { get;}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,24 @@ public virtual async Task<IOpenApiHttpTriggerContext> SetApplicationAssemblyAsyn
return this;
}

/// <inheritdoc />
public virtual async Task<OpenApiAuthorizationResult> AuthorizeAsync(IHttpRequestDataObject req)
{
var result = default(OpenApiAuthorizationResult);
var type = this.ApplicationAssembly
.GetLoadableTypes()
.SingleOrDefault(p => p.HasInterface<IOpenApiHttpTriggerAuthorization>());
if (type.IsNullOrDefault())
{
return result;
}

var auth = Activator.CreateInstance(type) as IOpenApiHttpTriggerAuthorization;
result = await auth.AuthorizeAsync(req).ConfigureAwait(false);

return result;
}

/// <inheritdoc />
public virtual VisitorCollection GetVisitorCollection()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,15 @@ public interface IHttpRequestDataObject
/// </summary>
HostString Host { get; }

/// <summary>
/// Gets the header collection.
/// </summary>
IHeaderDictionary Headers { get; }

/// <summary>
/// Gets the query collection.
/// </summary>
IQueryCollection Query { get;}
IQueryCollection Query { get; }

/// <summary>
/// Gets the request payload stream.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.Threading.Tasks;

using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Configurations;

namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions
{
/// <summary>
/// This provides interfaces to HTTP trigger authorisation for OpenAPI endpoints.
/// </summary>
public interface IOpenApiHttpTriggerAuthorization
{
/// <summary>
/// Authorizes the endpoint.
/// </summary>
/// <param name="req"><see cref="IHttpRequestDataObject"/> instance.</param>
/// <returns>Returns <see cref="OpenApiAuthorizationResult"/> instance.</returns>
Task<OpenApiAuthorizationResult> AuthorizeAsync(IHttpRequestDataObject req);
}
}
Loading