Napojení Swashbuckle/Swagger v ASP.NET Core aplikaci na Google OpenID Connect

Pokud máme API, které je s authentizací pomocí JWT (JwtBearer) a chceme pomocí Swashbuckle/Swaggeru naše API testovat, je možné se pomocí Swashbuckle/Swaggeru přihlásit a získaný token (id_token/JWT) předávat  do API automaticky.

Swashbuckle/Swagger má podporu pro OAuth2, nikoliv však pro OpenID Connect. Avšak implementace OAuth Googlu umožní získat id_token (JWT) pro OpenID Connect. Chce to však jeden trik v javascriptu, který vymění hodnotu response_type „token“ za „token id_token“.


public IServiceProvider ConfigureServices(IServiceCollection services)
{

...

services
.AddAuthentication(options => options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => ... );

...

services.AddSwaggerGen(c =>
{
...

c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = "https://accounts.google.com/o/oauth2/v2/auth",
TokenUrl = "https://www.googleapis.com/oauth2/v4/token",
Scopes = new Dictionary<string, string>
{
{ "openid profile email", "Default scopes" }
}
});

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

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{

app.UseSwaggerUI(c =>
{
// Swashbuckle/Swagger podporují jen OAuth. Pro OpenID Connect je potřeba namísto "response_type=token" posílat "response_type=token id_token". To zajistíme hackem v javascriptu.
// Google OAuth navíc vyžaduje parametr nonce, který je v hacku rovněž přidán.
c.InjectOnCompleteJavaScript("/swagger-ui-customization.js");

c.ConfigureOAuth2("client-id", "client-secret", "http://localhost:PORT/swagger/ui/o2c-html", "application-name");
c.SwaggerEndpoint("/swagger/current/swagger.json", "Current");
});

Třída AuthorizeCheckOperationFilter zajišťuje doplnění informací o security pro Swashbuckle/Swagger:


internal class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
// Alternativní implementace: https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Dummy.Core/SwaggerExtensions/AssignOAuth2SecurityRequirements.cs
// Check for authorize attribute
var hasAuthorize = context.ApiDescription.ControllerAttributes().OfType<AuthorizeAttribute>().Any() || context.ApiDescription.ActionAttributes().OfType<AuthorizeAttribute>().Any();


if (hasAuthorize)
{
// přidá do dokumentace možnou odpověd - 401
operation.Responses.Add("401", new Response { Description = "Unauthorized" });

// přidá informaci o tom, že se má použít pro volání metody authentizační token (zobrazí se červený vykřičník)
operation.Security = new List<IDictionary<string, IEnumerable<string>>>
{
new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", new string[] { "openid profile email" } }
}
};
}
}
}

Dále je potřeba do rootu webu umístit soubor swagger-ui-customization.js, který provádí ukrutný hack nad window.open:


// Swagger UI does not support custom response_type parameters. Azure Active Directory requires an 'id_token' value to
// be passed instead of 'token' (See https://github.com/swagger-api/swagger-ui/issues/1974).
window.swaggerUiAuth = window.swaggerUiAuth || {};
window.swaggerUiAuth.tokenName = 'id_token';

if (!window.isOpenReplaced) {
window.open = function (open) {
return function (url) {
url = url.replace('response_type=token', 'response_type=token%20id_token&nonce=456');
console.log(url);
return open.call(window, url);
};
}(window.open);
window.isOpenReplaced = true;
}

Moderní přístup k JavaScriptu – záznam [Pavel Kříž, HAVIT Vzdělávací okénko 12.10.2017]

Záznam z interního vzdělávacího okénka HAVIT z 12.10.2017 je publikován na našem HAVIT YouTube Channel. Téma prezentoval Pavel Kříž:

Dotčená témata:

  • Transpillers – TypeScript, Babel
  • Flow, ESLint, TSlint,
  • Literal Objects
  • Revealing Module Pattern
  • CommonJS
  • AMD – Asynchronous Module Definition
  • Modules
  • Array
  • Event Loop
  • Asynchronní operace v JS
  • Promise
  • TypeScript – async/await, class, arrow,

Pattern matching – od C# k F# – záznam [Martin Havel, HAVIT Vzdělávací okénko 5.10.2017]

Záznam z interního vzdělávacího okénka HAVIT z 5.10.2017 je publikován na našem HAVIT YouTube Channel. Téma prezentoval Martin Havel:

Dotčená témata:

  • funkcionální programování
  • geneze projektu kalkulačky v F#

ASP.NET Core Intro – záznam [Jiří Kanda, HAVIT Vzdělávací okénko 21.9.2017]

Záznam z interního vzdělávacího okénka HAVIT z 21.9.2017 je publikován na našem HAVIT YouTube Channel. Téma prezentoval Jiří Kanda:

Dotčená témata:

  • Web vs WebAPI vs. Frontend
  • SSR – Server-side Rendering
  • ASP.NET Core vs. .NET Standard
  • Struktura projektu
  • Startup.cs
  • Program.cs

IMMUTABLE JS [Pavel Kříž, HAVIT Vzdělávací okénko 17.8.2017]

Záznam z interního vzdělávacího okénka HAVIT ze 17.8.2017 je publikován na našem HAVIT YouTube Channel. Téma prezentoval Pavel Kříž:

Dotčená témata:

  • React připomenutí
  • Immutable JS

TCP/IP Fundamentals – záznam [Jiří Kanda, HAVIT Vzdělávací okénko 21.9.2017]

Záznam z interního vzdělávacího okénka HAVIT z 21.9.2017, kde nám Jiří Kanda připomenul základy TCP/IP. Záznam je publikován na našem HAVIT YouTube Channel:

Dotčená témata:

  • komunikační vrstvy
    • Vrstva síťového rozhraní – Ethernet
    • Síťová vrstva – IP
    • Transportní vrstva – TCP
    • Aplikační vrstva – HTTP, SMTP, …
  • IP Datagram
  • UDP Datagram
  • TCP Segement
  • ARP, DHCP
  • IP Address Classes, privátní segmenty
  • NAT
  • ICMP, ping, tracert, telnet

REST WebAPI – záznam [Miroslav Holec, HAVIT Vzdělávací okénko 29.6.2017]

Záznam z interního vzdělávacího okénka HAVIT z 29.6.2017 je publikován na našem HAVIT YouTube Channel. Téma prezentoval Miroslav Holec:

Viz též předchozí díl Úvod do RESTful WebAPI – záznam [Miroslav Holec, HAVIT Vzdělávací okénko 22.6.2017].

Úvod do RESTful WebAPI – záznam [Miroslav Holec, HAVIT Vzdělávací okénko 22.6.2017]

Záznam z interního vzdělávacího okénka HAVIT z 22.6.2017 je publikován na našem HAVIT YouTube Channel. Téma prezentoval Miroslav Holec:

Dotčená témata:

  • REST API
  • REST vs. RESTful
  • ASP.NET WebAPI
  • Request / Response
  • Postman
  • Resources
  • HTTP Verbs
  • Verzování
  • Content Negotiation
  • Hypermedia

WinDbg: SOSEX Help – Command Reference

SOSEX je jedno z mála rozšíření Windows Debuggeru pro .NET (managed code). Přidává pár užitečných příkazů k základnímu SOS, není však snadné seznam podporovaných příkazů online najít.
Seznam příkazů se dá získat přes !sosex.help. Výstup se může hodit, pokud hledáte, která extension bude pro váš scénář diagnostiky nejpříhodnější.

0:000> !sosex.help
SOSEX - Copyright 2007-2015 by Steve Johnson - http://www.stevestechspot.com/
To report bugs or offer feedback about SOSEX, please email sjjohnson@pobox.com
Quick Ref:
--------------------------------------------------
bhi       [filename]                                     BuildHeapIndex - Builds an index file for heap objects.
bpsc      (Deprecated.  Use !mbp instead)
chi                                                      ClearHeapIndex - Frees all resources used by the heap index and removes it from memory.
dlk       [-d]                                           Displays deadlocks between SyncBlocks and/or ReaderWriterLocks
dumpfd    <FieldAddr>                                    Dumps the properties of a FieldDef structure
dumpgen   <GenNum> [-free] [-stat] [-type <TYPE_NAME>]   Dumps the contents of the specified generation
                   [-nostrings] [-live] [-dead] [-short]
finq      [GenNum] [-stat]                               Displays objects in the finalization queue
frq       [-stat]                                        Displays objects in the Freachable queue
gcgen     <ObjectAddr>                                   Displays the GC generation of the specified object
gch       [HandleType]... [-stat]                        Lists all GCHandles, optionally filtered by specified handle types
help      [CommandName]                                  Display this screen or details about the specified command
lhi       [filename]                                     LoadHeapIndex - load the heap index into memory.
mbc       <SOSEX breakpoint ID | *>                      Clears the specified or all managed breakpoints
mbd       <SOSEX breakpoint ID | *>                      Disables the specified or all managed breakpoints
mbe       <SOSEX breakpoint ID | *>                      Enables the specified or all managed breakpoints
mbl       [SOSEX breakpoint ID]                          Prints the specified or all managed breakpoints
mbm       <Type/MethodFilter> [ILOffset] [Options]       Sets a managed breakpoint on methods matching the specified filter
mbp       <SourceFile> <nLineNum> [ColNum] [Options]     Sets a managed breakpoint at the specified source code location
mdso      [Options]                                      Dumps object references on the stack and in CPU registers in the current context
mdt       [TypeName | VarName | MT] [ADDR] [Options]     Displays the fields of an object or type, optionally recursively
mdv       [nFrameNum]                                    Displays arguments and locals for a managed frame
mfrag     [-stat] [-mt:<MT>]                             Reports free blocks, the type of object following the free block, and fragmentation statistics
mframe    [nFrameNum]                                    Displays or sets the current managed frame for the !mdt and !mdv commands
mgu       // TODO: Document
mk        [FrameCount] [-l] [-p] [-a]                    Prints a stack trace of managed and unmanaged frames
mln       [expression]                                   Displays the type of managed data located at the specified address or the current instruction pointer
mlocks    [-d]                                           Lists all managed lock objects and CriticalSections and their owning threads
mroot     <ObjectAddr> [-all]                            Displays GC roots for the specified object
mt        (no parameters)                                Steps into the managed method at the current position
mu        [address] [-s] [-il] [-n]                      Displays a disassembly around the current instruction with interleaved source, IL and asm code
muf       [MD Address | Code Address] [-s] [-il] [-n]    Displays a disassembly with interleaved source, IL and asm code
mwaits    [-d | LockAddr]                                Lists all waiting threads and, if known, the locks they are waiting on
mx        <Filter String>                                Displays managed type/field/method names matching the specified filter string
rcw       [Object or SyncBlock Addr]                     Displays Runtime Callable Wrapper (RCW) COM interop data.
refs      <ObjectAddr> [-target|-source]                 Displays all references from and to the specified object
rwlock    [ObjectAddr | -d]                              Displays all RWLocks or, if provided a RWLock address, details of the specified lock
sosexhelp [CommandName]                                  Display this screen or details about the specified command
strings   [ModuleAddress] [Options]                      Search the managed heap or a module for strings matching the specified criteria

ListGcHandles - See gch

Use !help <command> or !sosexhelp <command> for more details about each command.
You can also use the /? (or -?) option on any command to get help for that command.

AppService: Nastavení časové zóny pomocí WEBSITE_TIME_ZONE App Setting (a mnoho dalších)

Ve výchozím stavu běží AppServices v UTC. Existuje však téměř nedokumentovaná možnost (nebo minimálně velmi málo známá), kterak časovou zónu aplikace změnit. Stačí přidat konkrétní nastavení mezi Application Settings vaší aplikace (v Azure Portalu) a KUDU se o správný čas postará. Dá se takto nastavit mnoho věcí:

  • WEBSITE_TIME_ZONE, např. Central Europe Standard Time (seznam podporovaných hodnot)
  • SCM_TOUCH_WEBCONFIG_AFTER_DEPLOYMENT = 1/0 – dělá, co říká (default je 1)
  • SCM_TRACE_LEVEL = 1..4 – v rozsahu od 1 do 4 můžete navýšit míru podrobností pro tracing  (default je 1 – nejnižší)
  • Volby pro Build/GIT
  • Volby pro ukládání site na disk a cachování
  • Nastavení verze Node/NPN
  • WEBSITE_LOAD_CERTIFICATES – načtení certifikátů
  • Nízkoúrovňové diagnostické přepínače
  • WEBSITE_DISABLE_SCM_SEPARATION – zajímavě vypadající volba, která vám umožní hostovat vaší aplikaci a SCM (Kudu) ve stejném sandboxu (a potenciálně tak ušetřit zdroje, zejména paměť) – bohužel je tato volba označena jako legacy-obsolete a unsupported (podle všeho funguje, ale ruku do ohně už za to nedávají)
  • …a mnoho dalších

Úplný seznam parametrů najdete v Project KUDU Wiki..