Created
October 20, 2018 10:23
-
-
Save hoetz/4351982f9de2a93d19bb2228ef02b17c to your computer and use it in GitHub Desktop.
Secure ASP.NET Core F# Api with Azure AD
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module AzureAdAuth | |
open System | |
open Microsoft.Extensions.DependencyInjection | |
open Microsoft.Extensions.Options | |
open Microsoft.AspNetCore.Authentication.JwtBearer | |
open Microsoft.IdentityModel.Tokens | |
open System.Text | |
open System.Threading.Tasks | |
type AzureAdOptions() = | |
member val FrontendClientId = "" with get, set | |
member val Instance = "" with get, set | |
member val TenantId = "" with get, set | |
type ConfigureAzureOptions(azureOptions : IOptions<AzureAdOptions>) = | |
let internalConfigure (_ : string) (options : JwtBearerOptions) = | |
options.Audience <- azureOptions.Value.FrontendClientId | |
options.Authority <- sprintf "%s%s" azureOptions.Value.Instance | |
azureOptions.Value.TenantId | |
options.SaveToken <- true | |
options.RequireHttpsMetadata <- false | |
options.TokenValidationParameters <- TokenValidationParameters | |
(ValidIssuer = options.Authority) | |
options.Events <- new JwtBearerEvents() | |
options.Events.OnAuthenticationFailed <- fun x -> | |
let s = sprintf "Failed with %s" x.Exception.Message | |
x.Response.ContentLength <- Nullable<int64>((int64) (s.Length)) | |
x.Response.Body.Write(Encoding.UTF8.GetBytes(s), 0, s.Length) | |
Task.FromResult(0) :> Task | |
interface IConfigureNamedOptions<JwtBearerOptions> with | |
member __.Configure(name : string, options : JwtBearerOptions) = | |
internalConfigure name options | |
member __.Configure(options : JwtBearerOptions) = | |
internalConfigure Options.DefaultName options | |
type Microsoft.AspNetCore.Authentication.AuthenticationBuilder with | |
member this.AddAzureAd(configureOptions : Action<AzureAdOptions>) = | |
this.Services.Configure(configureOptions) |> ignore | |
this.Services.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureAzureOptions> | |
() |> ignore | |
this.AddJwtBearer() |> ignore | |
this |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment