Last active
August 6, 2024 01:53
-
-
Save MufidJamaluddin/58ac257ad4b2d8cdb1cc3f2708a303f7 to your computer and use it in GitHub Desktop.
Middleware JWT in Cookie
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
/** | |
* Middleware Handle JWT in Cookie | |
* @author Mufid Jamaluddin | |
**/ | |
namespace IssueTracker.Middleware | |
{ | |
public static class JwtInCookieMiddleware | |
{ | |
public const string JWT_COOKIE_KEY = "token"; | |
public static void UseJwtInCookie(this IApplicationBuilder app) | |
{ | |
app.Use(async (context, next) => | |
{ | |
bool is_cookie_used = true; | |
if (!context.Request.Headers.TryGetValue("Authorization", out StringValues headerToken)) | |
{ | |
is_cookie_used = true; | |
} | |
if (string.IsNullOrEmpty(headerToken)) | |
{ | |
is_cookie_used = true; | |
} | |
if (is_cookie_used) | |
{ | |
if (!context.Request.Cookies.TryGetValue(JWT_COOKIE_KEY, out string cookieToken)) | |
{ | |
cookieToken = headerToken; | |
} | |
context.Request.Headers.Add("Authorization", | |
string.Format(CultureInfo.InvariantCulture, "Bearer {0}", cookieToken) | |
); | |
} | |
// EKSEKUSI PROSES SELANJUTNYA HINGGA DAPET RESPON "APLIKASI" (MODUL INTI) | |
await next.Invoke(); | |
if (is_cookie_used) | |
{ | |
context.Response.Headers.Add("ext","TAMBAHAN RESPON DARI SAYA.. SAYA KENAL KAMU DARI COOKIE BROWSER MILIKMU..."); | |
} | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment