From f5419701a720724e947ecf2cb8c744b2611f4312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Sun, 22 Nov 2026 21:08:49 +0300 Subject: [PATCH 01/17] feat(client): Manage Access Token When Transport with Header --- .../Program.cs | 17 +--- .../Contracts/Token/AccessToken.cs | 12 ++- .../Auth/Response/AuthResponseResolver.cs | 12 +-- .../Endpoints/LoginEndpointHandler.cs | 13 +++ .../Credentials/CredentialResponseWriter.cs | 29 ++++++- .../UAuthResourceRequestClient.cs | 16 +++- .../TScripts/uauth.js | 38 +++++++++ .../wwwroot/uauth.min.js | 2 +- .../Abstractions/IUAuthTokenStore.cs | 28 +++++++ .../Contracts/UAuthTransportResult.cs | 18 +++++ .../Extensions/ServiceCollectionExtensions.cs | 5 +- .../Infrastructure/InMemoryUAuthTokenStore.cs | 29 +++++++ .../Services/UAuthFlowClient.cs | 80 +++++++++++++++++- .../Client/UAuthTokenStoreTests.cs | 81 +++++++++++++++++++ 14 files changed, 346 insertions(+), 34 deletions(-) create mode 100644 src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthTokenStore.cs create mode 100644 src/client/CodeBeam.UltimateAuth.Client/Infrastructure/InMemoryUAuthTokenStore.cs create mode 100644 tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthTokenStoreTests.cs diff --git a/samples/blazor-server/CodeBeam.UltimateAuth.Sample.BlazorServer/Program.cs b/samples/blazor-server/CodeBeam.UltimateAuth.Sample.BlazorServer/Program.cs index 56ff01da..67534026 100644 --- a/samples/blazor-server/CodeBeam.UltimateAuth.Sample.BlazorServer/Program.cs +++ b/samples/blazor-server/CodeBeam.UltimateAuth.Sample.BlazorServer/Program.cs @@ -68,27 +68,12 @@ //o.Session.Lifetime = TimeSpan.FromSeconds(20); //o.Session.TouchInterval = TimeSpan.FromSeconds(9); //o.Session.IdleTimeout = TimeSpan.FromSeconds(10); - - o.GrantDelivery.Default = GrantDeliveryMode.Cookie; - // PureJwt access token cookie - o.Cookie.AccessToken.Name = "uat"; - o.Cookie.AccessToken.HttpOnly = true; - o.Cookie.AccessToken.SecurePolicy = CookieSecurePolicy.Always; - o.Cookie.AccessToken.SameSite = SameSiteMode.Lax; - o.Cookie.AccessToken.Path = "/"; - - // PureJwt refresh token cookie - o.Cookie.RefreshToken.Name = "uar"; - o.Cookie.RefreshToken.HttpOnly = true; - o.Cookie.RefreshToken.SecurePolicy = CookieSecurePolicy.Always; - o.Cookie.RefreshToken.SameSite = SameSiteMode.Lax; - o.Cookie.RefreshToken.Path = "/"; }) .AddUltimateAuthInMemory(); builder.Services.AddUltimateAuthClientBlazor(o => { - o.ApplicationProfile = UAuthApplicationProfile.BlazorServer; + o.ApplicationProfile = UAuthApplicationProfile.BlazorWasm; o.AutoDetectApplicationProfile = false; o.Login.AllowCredentialPost = true; //o.AutoRefresh.Interval = TimeSpan.FromSeconds(5); diff --git a/src/CodeBeam.UltimateAuth.Core/Contracts/Token/AccessToken.cs b/src/CodeBeam.UltimateAuth.Core/Contracts/Token/AccessToken.cs index 8c7169c3..e292e315 100644 --- a/src/CodeBeam.UltimateAuth.Core/Contracts/Token/AccessToken.cs +++ b/src/CodeBeam.UltimateAuth.Core/Contracts/Token/AccessToken.cs @@ -12,7 +12,7 @@ public sealed class AccessToken // TODO: TokenKind enum? /// - /// Token type: "jwt" or "opaque". + /// Token format (JWT or opaque). /// Used for diagnostics and middleware behavior. /// public TokenFormat Format { get; init; } @@ -23,9 +23,17 @@ public sealed class AccessToken public required DateTimeOffset ExpiresAt { get; init; } /// - /// Optional session id this token is bound to (Hybrid / SemiHybrid). + /// Optional session identifier associated with the token. /// public string? SessionId { get; init; } + /// + /// Optional token scope. + /// public string? Scope { get; init; } + + /// + /// Determines whether the token has expired. + /// + public bool IsExpired(DateTimeOffset now) => now >= ExpiresAt; } diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Response/AuthResponseResolver.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Response/AuthResponseResolver.cs index 7b8873af..210b7f00 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/Response/AuthResponseResolver.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Response/AuthResponseResolver.cs @@ -72,21 +72,13 @@ or UAuthMode.SemiHybrid effectiveMode is UAuthMode.Hybrid or UAuthMode.SemiHybrid or UAuthMode.PureJwt, - effectiveMode == UAuthMode.Hybrid - ? GrantDeliveryMode.Cookie - : effectiveMode == UAuthMode.PureOpaque - ? GrantDeliveryMode.None - : GrantDeliveryMode.Header, + GrantDeliveryMode.Cookie, delivery.RefreshToken, delivery.Default, applicationProfile, options); - return new EffectiveAuthResponse( - session, - accessToken, - refreshToken, - redirect); + return new EffectiveAuthResponse(session, accessToken, refreshToken, redirect); } private static EffectiveGrantDelivery ResolveGrant( diff --git a/src/CodeBeam.UltimateAuth.Server/Endpoints/LoginEndpointHandler.cs b/src/CodeBeam.UltimateAuth.Server/Endpoints/LoginEndpointHandler.cs index 483e17c4..7e485fef 100644 --- a/src/CodeBeam.UltimateAuth.Server/Endpoints/LoginEndpointHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Endpoints/LoginEndpointHandler.cs @@ -150,6 +150,19 @@ public async Task LoginAsync(HttpContext ctx) var decision = _redirectResolver.ResolveSuccess(authFlow, ctx); + if (ctx.Request.HasFormContentType) + { + var form = await ctx.GetCachedFormAsync(); + + if (form?["__uauth_response_mode"].FirstOrDefault() == "fetch") + { + return Results.Ok(new + { + RedirectUrl = decision.Enabled ? decision.TargetUrl : null + }); + } + } + return decision.Enabled ? Results.Redirect(decision.TargetUrl!) : Results.Ok(); diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/CredentialResponseWriter.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/CredentialResponseWriter.cs index 56de8b2d..093f8638 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/CredentialResponseWriter.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/CredentialResponseWriter.cs @@ -30,7 +30,34 @@ public void Write(HttpContext context, GrantKind kind, AuthSessionId sessionId) => WriteInternal(context, kind, sessionId.ToString()); public void Write(HttpContext context, GrantKind kind, AccessToken token) - => WriteInternal(context, kind, token.Token); + { + ArgumentNullException.ThrowIfNull(token); + + WriteInternal(context, kind, token.Token); + + if (kind != GrantKind.AccessToken) + return; + + var auth = _authContext.Current; + var delivery = auth.Response.AccessTokenDelivery; + + if (delivery.Mode != GrantDeliveryMode.Header) + return; + + var headerName = delivery.Name; + + if (string.IsNullOrWhiteSpace(headerName)) + throw new InvalidOperationException("Access token header name is missing."); + + var headers = context.Response.Headers; + + headers["X-UAuth-Access-Header"] = headerName; + headers["X-UAuth-Access-Expires"] = token.ExpiresAt.ToUniversalTime().ToString("O"); + headers["X-UAuth-Access-Format"] = token.Format.ToString().ToLowerInvariant(); + headers["X-UAuth-Access-HeaderFormat"] = delivery.HeaderFormat.ToString().ToLowerInvariant(); + + headers.CacheControl = "no-store"; + } public void Write(HttpContext context, GrantKind kind, RefreshTokenInfo token) => WriteInternal(context, kind, token.Token); diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthResourceRequestClient.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthResourceRequestClient.cs index 1c47da11..ddb22b6a 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthResourceRequestClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthResourceRequestClient.cs @@ -1,4 +1,5 @@ -using CodeBeam.UltimateAuth.Client.Contracts; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; @@ -11,12 +12,14 @@ internal sealed class UAuthResourceRequestClient : IUAuthResourceRequestClient { private readonly IJSRuntime _js; private readonly IUAuthClientBootstrapper _bootstrapper; + private readonly IUAuthTokenStore _tokenStore; private readonly UAuthClientOptions _options; - public UAuthResourceRequestClient(IJSRuntime js, IUAuthClientBootstrapper bootstrapper, IOptions options) + public UAuthResourceRequestClient(IJSRuntime js, IUAuthClientBootstrapper bootstrapper, IUAuthTokenStore tokenStore, IOptions options) { _js = js; _bootstrapper = bootstrapper; + _tokenStore = tokenStore; _options = options.Value; } @@ -37,6 +40,14 @@ public async Task SendAsync(string method, string try { + var accessToken = _tokenStore.Read(); + + if (accessToken is not null && accessToken.IsExpired(DateTimeOffset.UtcNow)) + { + _tokenStore.Clear(); + accessToken = null; + } + var result = await _js.InvokeAsync("uauth.resourceRequest", ct, new { @@ -46,6 +57,7 @@ public async Task SendAsync(string method, string payload, applicationProfile = _options.ApplicationProfile.ToString(), credentials = _options.Resource.Credentials.ToString(), + accessToken = accessToken?.Token, requestId }); diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/TScripts/uauth.js b/src/client/CodeBeam.UltimateAuth.Client.Blazor/TScripts/uauth.js index f25fe597..1e00f64f 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/TScripts/uauth.js +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/TScripts/uauth.js @@ -425,11 +425,33 @@ window.uauth.request = async function (options) { } } + const accessTokenHeader = response.headers.get("X-UAuth-Access-Header"); + + let accessToken = null; + let accessTokenExpiresAt = null; + let accessTokenFormat = null; + let accessTokenHeaderFormat = null; + + if (response.ok && accessTokenHeader) { + if (!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(accessTokenHeader)) { + throw new Error("Invalid access token header name."); + } + + accessToken = response.headers.get(accessTokenHeader); + accessTokenExpiresAt = response.headers.get("X-UAuth-Access-Expires"); + accessTokenFormat = response.headers.get("X-UAuth-Access-Format"); + accessTokenHeaderFormat = response.headers.get("X-UAuth-Access-HeaderFormat"); + } + return { retryAfter: response.headers.get("Retry-After"), ok: response.ok, status: response.status, refreshOutcome: response.headers.get("X-UAuth-Refresh"), + accessToken, + accessTokenExpiresAt, + accessTokenFormat, + accessTokenHeaderFormat, body: responseBody }; }; @@ -442,6 +464,7 @@ window.uauth.resourceRequest = async function (options) { payload = null, applicationProfile = "", credentials = "Auto", + accessToken = null, requestId } = options; @@ -529,6 +552,21 @@ window.uauth.resourceRequest = async function (options) { "X-Requested-With": "UAuth" }; + if (accessToken !== null) { + if (typeof accessToken !== "string" || + accessToken.length === 0 || + /[\r\n]/.test(accessToken)) { + throw new Error("Invalid Resource API access token."); + } + + if (requestUrl.protocol !== "https:" && + !["localhost", "127.0.0.1", "[::1]"].includes(requestUrl.hostname)) { + throw new Error("Bearer access token requests require HTTPS."); + } + + headers["Authorization"] = `Bearer ${accessToken}`; + } + let body = null; if (payload !== null && payload !== undefined) { diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/wwwroot/uauth.min.js b/src/client/CodeBeam.UltimateAuth.Client.Blazor/wwwroot/uauth.min.js index 145fa18e..7898fa09 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/wwwroot/uauth.min.js +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/wwwroot/uauth.min.js @@ -1 +1 @@ -window.uauth=window.uauth||{};window.uauth.storage={set:function(n,t,i){const r=n==="local"?window.localStorage:window.sessionStorage;r.setItem(t,i)},get:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;return i.getItem(t)},remove:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;i.removeItem(t)},exists:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;return i.getItem(t)!==null}};window.uauth.submitForm=async function(n,t=null){if(!n)return;if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const r=window.uauth.validateAuthUrl(n.action,t);n.action=r;let i=n.querySelector("input[name='__uauth_device']");i||(i=document.createElement("input"),i.type="hidden",i.name="__uauth_device",n.appendChild(i));i.value=window.uauth.deviceId;await window.uauth.antiforgery.appendToForm(n,t);n.submit()};window.uauth.tryAndCommit=async function(n){const{tryUrl:c,commitUrl:l,data:e,applicationProfile:o,trustedOrigin:u}=n,a=window.uauth.validateAuthUrl(c,u),v=window.uauth.validateAuthUrl(l,u),s=window.uauth.deviceId;if(!s)throw new Error("UAuth deviceId is not initialized.");const r=await window.uauth.postJson({url:a,payload:e,applicationProfile:o,trustedOrigin:u});if(!r||!Number.isInteger(r.status))throw new Error("Invalid UAuth transport response.");const i=r.status;if(i===429)return{isSuccess:!1,status:429,errorCode:"rate_limited",retryAfter:r.retryAfter??null};const y=i>=200&&i<300,h=i>=400&&i<500;if(!y&&!h)throw new Error(`Unexpected UAuth try response: HTTP ${i}.`);const t=r.body;if(!t||typeof t!="object"||Array.isArray(t)||typeof t.isSuccess!="boolean")throw new Error("Invalid UAuth try response body.");if(h&&t.isSuccess)throw new Error("Successful authentication result returned with HTTP error.");const f={isSuccess:t.isSuccess,reason:t.reason??null,remainingAttempts:t.remainingAttempts??null,lockoutUntilUtc:t.lockoutUntilUtc??null,requiresMfa:t.requiresMfa??!1,retryWithNewPkce:t.retryWithNewPkce??!1,previewReceipt:t.previewReceipt??null};if(f.isSuccess){const n=document.createElement("form");n.method="POST";n.action=v;for(const t of Object.keys(e)){const i=document.createElement("input");i.type="hidden";i.name=t;i.value=e[t]??"";n.appendChild(i)}if(f.previewReceipt){const t=document.createElement("input");t.type="hidden";t.name="PreviewReceipt";t.value=f.previewReceipt;n.appendChild(t)}const t=document.createElement("input");t.type="hidden";t.name="__uauth_application_profile";t.value=o??"";n.appendChild(t);const i=document.createElement("input");i.type="hidden";i.name="__uauth_device";i.value=s;n.appendChild(i);document.body.appendChild(n);try{await window.uauth.submitForm(n,u)}catch(r){n.remove();throw r;}}return f};window.uauth.post=async function(n){const{url:e,mode:t,data:i,applicationProfile:u,trustedOrigin:r}=n,f=window.uauth.validateAuthUrl(e,r);if(t==="navigate"){const n=document.createElement("form");n.method="POST";n.action=f;const t=document.createElement("input");t.type="hidden";t.name="__uauth_application_profile";t.value=u??"";n.appendChild(t);const e=document.createElement("input");if(e.type="hidden",e.name="__uauth_device",e.value=window.uauth.deviceId,n.appendChild(e),i)for(const t in i){const r=document.createElement("input");r.type="hidden";r.name=t;r.value=i[t];n.appendChild(r)}document.body.appendChild(n);try{await window.uauth.submitForm(n,r)}catch(o){n.remove();throw o;}return null}const o=t==="logout"||t==="logout-observe";return window.uauth.request({url:f,method:"POST",payload:i,applicationProfile:u,contentType:"form",credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!0,trustedOrigin:r,navigateOnSuccess:t==="logout",headers:o?{"X-UAuth-Logout-Mode":"observe"}:{}})};window.uauth.postJson=function(n){const t=window.uauth.validateAuthUrl(n.url,n.trustedOrigin);return window.uauth.request({url:t,method:"POST",payload:n.payload,applicationProfile:n.applicationProfile,contentType:"json",credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!0,trustedOrigin:n.trustedOrigin})};window.uauth.request=async function(n){const{followRedirects:a=!1,navigateOnSuccess:v=!1,url:h,method:y="GET",payload:r=null,applicationProfile:p="",contentType:c="json",credentials:s="same-origin",headers:w={}}=n;if(!h)throw new Error("Request URL is required.");const u=new URL(h,document.baseURI);if(!["http:","https:"].includes(u.protocol))throw new Error("Unsupported request URL protocol.");const i=y.toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE"].includes(i))throw new Error(`Unsupported HTTP method: ${i}`);if(!["same-origin","include","omit"].includes(s))throw new Error("Invalid credentials policy.");if(s==="include"&&u.origin!==window.location.origin&&!n.allowCrossOriginCredentials)throw new Error("Cross-origin credentials require explicit authorization.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const f={...w,"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":p,"X-Requested-With":"UAuth"};let e=null;if(r!==null&&r!==undefined){if(i==="GET")throw new Error("GET requests cannot contain a body.");if(c==="json")f["Content-Type"]="application/json",e=JSON.stringify(r);else if(c==="form"){f["Content-Type"]="application/x-www-form-urlencoded";e=new URLSearchParams;for(const[n,t]of Object.entries(r))e.append(n,t??"")}else throw new Error("Unsupported content type.");}if(i!=="GET"&&n.antiforgery===!0){const i=window.uauth.validateAuthUrl(window.uauth.antiforgery.tokenUrl,n.trustedOrigin);if(new URL(i).origin!==u.origin)throw new Error("UAuth antiforgery token origin differs from request origin.");const t=await window.uauth.antiforgery.getToken(n.trustedOrigin);f[t.headerName]=t.requestToken}let t;try{t=await fetch(u.href,{method:i,credentials:s,redirect:a?"follow":"error",headers:f,body:e})}catch(l){if(l instanceof TypeError)return{ok:!1,status:0,refreshOutcome:null,body:null};throw l;}let o=null;if(t.status!==204&&t.status!==205){const n=await t.text();if(n)try{o=JSON.parse(n)}catch{o=n}}if(v&&t.ok){const n=o?.redirectUrl;if(typeof n=="string"&&n.length>0){const t=new URL(n,window.location.origin);if(!["http:","https:"].includes(t.protocol))throw new Error("Invalid logout redirect protocol.");window.location.assign(t.href)}}return{retryAfter:t.headers.get("Retry-After"),ok:t.ok,status:t.status,refreshOutcome:t.headers.get("X-UAuth-Refresh"),body:o}};window.uauth.resourceRequest=async function(n){const{url:o,baseAddress:h,method:v="GET",payload:f=null,applicationProfile:y="",credentials:p="Auto",requestId:u}=n;if(!o||typeof o!="string")throw new Error("Resource request URL is required.");const i=h?new URL(h):new URL(window.location.origin+"/");if(!["http:","https:"].includes(i.protocol))throw new Error("Invalid Resource API protocol.");if(i.username||i.password||i.search||i.hash)throw new Error("Invalid Resource API base address.");const t=new URL(o,i);if(t.origin!==i.origin)throw new Error("Resource request target differs from configured API origin.");if(t.username||t.password)throw new Error("Resource URL cannot contain credentials.");if(!["http:","https:"].includes(t.protocol))throw new Error("Unsupported Resource API protocol.");const s=v.toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE"].includes(s))throw new Error("Unsupported Resource API method.");if(s==="GET"&&f!==null)throw new Error("GET requests cannot contain a body.");let r;switch(p.toLowerCase()){case"auto":r=t.origin===window.location.origin?"same-origin":"include";break;case"sameorigin":r="same-origin";break;case"include":r="include";break;case"omit":r="omit";break;default:throw new Error("Invalid Resource credentials mode.");}if(r==="include"&&t.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(t.hostname))throw new Error("Cross-origin credential requests require HTTPS.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const c={"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":y,"X-Requested-With":"UAuth"};let l=null;f!==null&&f!==undefined&&(c["Content-Type"]="application/json",l=JSON.stringify(f));const a=new AbortController;if(u){if(window.uauth.resourceRequests.has(u))throw new Error("Duplicate Resource request ID.");window.uauth.resourceRequests.set(u,a)}try{const n=await fetch(t.href,{method:s,credentials:r,redirect:"error",headers:c,body:l,signal:a.signal});let i=null;if(n.status!==204&&n.status!==205){const t=await n.text();t.length>0&&(i=t)}return{retryAfter:n.headers.get("Retry-After"),ok:n.ok,status:n.status,body:i,contentType:n.headers.get("Content-Type")}}catch(e){if(e?.name==="AbortError")throw e;if(e instanceof TypeError)return{ok:!1,status:0,body:null,contentType:null};throw e;}finally{u&&window.uauth.resourceRequests.delete(u)}};window.uauth.resourceRequests=new Map;window.uauth.cancelResourceRequest=function(n){const t=window.uauth.resourceRequests.get(n);return t?(t.abort(),!0):!1};window.uauth.validateAuthUrl=function(n,t=null){if(!n||typeof n!="string")throw new Error("Authentication URL is required.");const r=t?new URL(t,window.location.origin):new URL(window.location.origin),i=new URL(n,document.baseURI);if(!["http:","https:"].includes(r.protocol))throw new Error("Unsupported trusted origin protocol.");if(!["http:","https:"].includes(i.protocol))throw new Error("Unsupported authentication URL protocol.");if(r.username||r.password)throw new Error("Trusted origin cannot contain credentials.");if(i.username||i.password)throw new Error("Authentication URL cannot contain credentials.");if(i.origin!==r.origin)throw new Error("Authentication request target differs from the trusted UAuthHub origin.");return i.href};window.uauth.antiforgery={tokenUrl:null,configure:function(n){if(!n?.tokenUrl)throw new Error("UAuth antiforgery token URL is required.");this.tokenUrl=window.uauth.validateAuthUrl(n.tokenUrl,n.trustedOrigin)},getToken:async function(n){if(!this.tokenUrl)throw new Error("UAuth antiforgery is not configured.");const r=window.uauth.validateAuthUrl(this.tokenUrl,n),i=await fetch(r,{method:"GET",credentials:"include",cache:"no-store",redirect:"error",headers:{"X-UDID":window.uauth.deviceId}});if(!i.ok)throw new Error(`Unable to obtain UAuth antiforgery token: HTTP ${i.status}.`);const t=await i.json();if(!t?.requestToken||!t?.headerName||!t?.formFieldName)throw new Error("Invalid UAuth antiforgery response.");return t},appendToForm:async function(n,t){const r=await this.getToken(t);let i=Array.from(n.elements).find(n=>n.name===r.formFieldName);i||(i=document.createElement("input"),i.type="hidden",i.name=r.formFieldName,n.appendChild(i));i.value=r.requestToken}};window.uauth.submitLoginForm=async function(n,t){if(!(n instanceof HTMLFormElement))throw new Error("A native HTML form is required.");const{mode:o,tryUrl:p,commitUrl:w,applicationProfile:b,trustedOrigin:e,isPkce:s}=t;if(!["TryOnly","TryAndCommit","DirectCommit"].includes(o))throw new Error("Unsupported UAuth submit mode.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const l=window.uauth.validateAuthUrl(w,e),k=o==="DirectCommit"?null:window.uauth.validateAuthUrl(p,e),r=new FormData(n),a=r.getAll("Identifier"),v=r.getAll("Secret");if(a.length!==1||v.length!==1)throw new Error("Login form requires exactly one Identifier and one Secret.");const h=a[0],c=v[0];if(typeof h!="string"||typeof c!="string"||!h.trim()||!c.trim())throw new Error("Identifier and Secret are required.");if(s)for(const n of["authorization_code","code_verifier"]){const t=r.getAll(n);if(t.length!==1||typeof t[0]!="string"||!t[0])throw new Error(`Missing or duplicate PKCE field: ${n}`);}if(s){const t=r.get("hub_session_id");if(typeof t!="string"||!t)throw new Error("Missing PKCE Hub session ID.");const i=new URL(l);i.searchParams.set("uauth_hub",t);n.action=i.href}else n.action=l;if(o==="DirectCommit")return await window.uauth.submitForm(n,e),null;const f={Identifier:h,Secret:c};s?(f.authorization_code=r.get("authorization_code"),f.code_verifier=r.get("code_verifier"),f.__uauth_return_url=r.get("__uauth_return_url")??"",f.hub_session_id=r.get("hub_session_id")??""):f.ReturnUrl=r.get("__uauth_return_url")??"";const i=await window.uauth.postJson({url:k,payload:f,applicationProfile:b,trustedOrigin:e});if(!i||!Number.isInteger(i.status))throw new Error("Invalid UAuth transport response.");if(i.status===429)return{isSuccess:!1,status:429,errorCode:"rate_limited",retryAfter:i.retryAfter??null};const d=i.status>=200&&i.status<300,y=i.status>=400&&i.status<500;if(!d&&!y)throw new Error(`Unexpected UAuth try response: HTTP ${i.status}.`);const u=i.body;if(!u||typeof u!="object"||Array.isArray(u)||typeof u.isSuccess!="boolean")throw new Error("Invalid UAuth try response body.");if(y&&u.isSuccess)throw new Error("Successful authentication result returned with HTTP error.");if(o==="TryAndCommit"&&u.isSuccess){if(u.previewReceipt){let t=Array.from(n.elements).find(n=>n.name==="PreviewReceipt");t||(t=document.createElement("input"),t.type="hidden",t.name="PreviewReceipt",n.appendChild(t));t.value=u.previewReceipt}await window.uauth.submitForm(n,e)}return u};window.uauth.setDeviceId=function(n){window.uauth.deviceId=n};window.uauth.getDeviceInfo=function(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language}} \ No newline at end of file +window.uauth=window.uauth||{};window.uauth.storage={set:function(n,t,i){const r=n==="local"?window.localStorage:window.sessionStorage;r.setItem(t,i)},get:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;return i.getItem(t)},remove:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;i.removeItem(t)},exists:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;return i.getItem(t)!==null}};window.uauth.submitForm=async function(n,t=null){if(!n)return;if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const r=window.uauth.validateAuthUrl(n.action,t);n.action=r;let i=n.querySelector("input[name='__uauth_device']");i||(i=document.createElement("input"),i.type="hidden",i.name="__uauth_device",n.appendChild(i));i.value=window.uauth.deviceId;await window.uauth.antiforgery.appendToForm(n,t);n.submit()};window.uauth.tryAndCommit=async function(n){const{tryUrl:c,commitUrl:l,data:e,applicationProfile:o,trustedOrigin:u}=n,a=window.uauth.validateAuthUrl(c,u),v=window.uauth.validateAuthUrl(l,u),s=window.uauth.deviceId;if(!s)throw new Error("UAuth deviceId is not initialized.");const r=await window.uauth.postJson({url:a,payload:e,applicationProfile:o,trustedOrigin:u});if(!r||!Number.isInteger(r.status))throw new Error("Invalid UAuth transport response.");const i=r.status;if(i===429)return{isSuccess:!1,status:429,errorCode:"rate_limited",retryAfter:r.retryAfter??null};const y=i>=200&&i<300,h=i>=400&&i<500;if(!y&&!h)throw new Error(`Unexpected UAuth try response: HTTP ${i}.`);const t=r.body;if(!t||typeof t!="object"||Array.isArray(t)||typeof t.isSuccess!="boolean")throw new Error("Invalid UAuth try response body.");if(h&&t.isSuccess)throw new Error("Successful authentication result returned with HTTP error.");const f={isSuccess:t.isSuccess,reason:t.reason??null,remainingAttempts:t.remainingAttempts??null,lockoutUntilUtc:t.lockoutUntilUtc??null,requiresMfa:t.requiresMfa??!1,retryWithNewPkce:t.retryWithNewPkce??!1,previewReceipt:t.previewReceipt??null};if(f.isSuccess){const n=document.createElement("form");n.method="POST";n.action=v;for(const t of Object.keys(e)){const i=document.createElement("input");i.type="hidden";i.name=t;i.value=e[t]??"";n.appendChild(i)}if(f.previewReceipt){const t=document.createElement("input");t.type="hidden";t.name="PreviewReceipt";t.value=f.previewReceipt;n.appendChild(t)}const t=document.createElement("input");t.type="hidden";t.name="__uauth_application_profile";t.value=o??"";n.appendChild(t);const i=document.createElement("input");i.type="hidden";i.name="__uauth_device";i.value=s;n.appendChild(i);document.body.appendChild(n);try{await window.uauth.submitForm(n,u)}catch(r){n.remove();throw r;}}return f};window.uauth.post=async function(n){const{url:e,mode:t,data:i,applicationProfile:u,trustedOrigin:r}=n,f=window.uauth.validateAuthUrl(e,r);if(t==="navigate"){const n=document.createElement("form");n.method="POST";n.action=f;const t=document.createElement("input");t.type="hidden";t.name="__uauth_application_profile";t.value=u??"";n.appendChild(t);const e=document.createElement("input");if(e.type="hidden",e.name="__uauth_device",e.value=window.uauth.deviceId,n.appendChild(e),i)for(const t in i){const r=document.createElement("input");r.type="hidden";r.name=t;r.value=i[t];n.appendChild(r)}document.body.appendChild(n);try{await window.uauth.submitForm(n,r)}catch(o){n.remove();throw o;}return null}const o=t==="logout"||t==="logout-observe";return window.uauth.request({url:f,method:"POST",payload:i,applicationProfile:u,contentType:"form",credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!0,trustedOrigin:r,navigateOnSuccess:t==="logout",headers:o?{"X-UAuth-Logout-Mode":"observe"}:{}})};window.uauth.postJson=function(n){const t=window.uauth.validateAuthUrl(n.url,n.trustedOrigin);return window.uauth.request({url:t,method:"POST",payload:n.payload,applicationProfile:n.applicationProfile,contentType:"json",credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!0,trustedOrigin:n.trustedOrigin})};window.uauth.request=async function(n){const{followRedirects:b=!1,navigateOnSuccess:k=!1,url:c,method:d="GET",payload:r=null,applicationProfile:g="",contentType:l="json",credentials:s="same-origin",headers:nt={}}=n;if(!c)throw new Error("Request URL is required.");const u=new URL(c,document.baseURI);if(!["http:","https:"].includes(u.protocol))throw new Error("Unsupported request URL protocol.");const i=d.toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE"].includes(i))throw new Error(`Unsupported HTTP method: ${i}`);if(!["same-origin","include","omit"].includes(s))throw new Error("Invalid credentials policy.");if(s==="include"&&u.origin!==window.location.origin&&!n.allowCrossOriginCredentials)throw new Error("Cross-origin credentials require explicit authorization.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const f={...nt,"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":g,"X-Requested-With":"UAuth"};let e=null;if(r!==null&&r!==undefined){if(i==="GET")throw new Error("GET requests cannot contain a body.");if(l==="json")f["Content-Type"]="application/json",e=JSON.stringify(r);else if(l==="form"){f["Content-Type"]="application/x-www-form-urlencoded";e=new URLSearchParams;for(const[n,t]of Object.entries(r))e.append(n,t??"")}else throw new Error("Unsupported content type.");}if(i!=="GET"&&n.antiforgery===!0){const i=window.uauth.validateAuthUrl(window.uauth.antiforgery.tokenUrl,n.trustedOrigin);if(new URL(i).origin!==u.origin)throw new Error("UAuth antiforgery token origin differs from request origin.");const t=await window.uauth.antiforgery.getToken(n.trustedOrigin);f[t.headerName]=t.requestToken}let t;try{t=await fetch(u.href,{method:i,credentials:s,redirect:b?"follow":"error",headers:f,body:e})}catch(a){if(a instanceof TypeError)return{ok:!1,status:0,refreshOutcome:null,body:null};throw a;}let o=null;if(t.status!==204&&t.status!==205){const n=await t.text();if(n)try{o=JSON.parse(n)}catch{o=n}}if(k&&t.ok){const n=o?.redirectUrl;if(typeof n=="string"&&n.length>0){const t=new URL(n,window.location.origin);if(!["http:","https:"].includes(t.protocol))throw new Error("Invalid logout redirect protocol.");window.location.assign(t.href)}}const h=t.headers.get("X-UAuth-Access-Header");let v=null,y=null,p=null,w=null;if(t.ok&&h){if(!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(h))throw new Error("Invalid access token header name.");v=t.headers.get(h);y=t.headers.get("X-UAuth-Access-Expires");p=t.headers.get("X-UAuth-Access-Format");w=t.headers.get("X-UAuth-Access-HeaderFormat")}return{retryAfter:t.headers.get("Retry-After"),ok:t.ok,status:t.status,refreshOutcome:t.headers.get("X-UAuth-Refresh"),accessToken:v,accessTokenExpiresAt:y,accessTokenFormat:p,accessTokenHeaderFormat:w,body:o}};window.uauth.resourceRequest=async function(n){const{url:s,baseAddress:l,method:y="GET",payload:e=null,applicationProfile:p="",credentials:w="Auto",accessToken:u=null,requestId:f}=n;if(!s||typeof s!="string")throw new Error("Resource request URL is required.");const i=l?new URL(l):new URL(window.location.origin+"/");if(!["http:","https:"].includes(i.protocol))throw new Error("Invalid Resource API protocol.");if(i.username||i.password||i.search||i.hash)throw new Error("Invalid Resource API base address.");const t=new URL(s,i);if(t.origin!==i.origin)throw new Error("Resource request target differs from configured API origin.");if(t.username||t.password)throw new Error("Resource URL cannot contain credentials.");if(!["http:","https:"].includes(t.protocol))throw new Error("Unsupported Resource API protocol.");const h=y.toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE"].includes(h))throw new Error("Unsupported Resource API method.");if(h==="GET"&&e!==null)throw new Error("GET requests cannot contain a body.");let r;switch(w.toLowerCase()){case"auto":r=t.origin===window.location.origin?"same-origin":"include";break;case"sameorigin":r="same-origin";break;case"include":r="include";break;case"omit":r="omit";break;default:throw new Error("Invalid Resource credentials mode.");}if(r==="include"&&t.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(t.hostname))throw new Error("Cross-origin credential requests require HTTPS.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const c={"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":p,"X-Requested-With":"UAuth"};if(u!==null){if(typeof u!="string"||u.length===0||/[\r\n]/.test(u))throw new Error("Invalid Resource API access token.");if(t.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(t.hostname))throw new Error("Bearer access token requests require HTTPS.");c.Authorization=`Bearer ${u}`}let a=null;e!==null&&e!==undefined&&(c["Content-Type"]="application/json",a=JSON.stringify(e));const v=new AbortController;if(f){if(window.uauth.resourceRequests.has(f))throw new Error("Duplicate Resource request ID.");window.uauth.resourceRequests.set(f,v)}try{const n=await fetch(t.href,{method:h,credentials:r,redirect:"error",headers:c,body:a,signal:v.signal});let i=null;if(n.status!==204&&n.status!==205){const t=await n.text();t.length>0&&(i=t)}return{retryAfter:n.headers.get("Retry-After"),ok:n.ok,status:n.status,body:i,contentType:n.headers.get("Content-Type")}}catch(o){if(o?.name==="AbortError")throw o;if(o instanceof TypeError)return{ok:!1,status:0,body:null,contentType:null};throw o;}finally{f&&window.uauth.resourceRequests.delete(f)}};window.uauth.resourceRequests=new Map;window.uauth.cancelResourceRequest=function(n){const t=window.uauth.resourceRequests.get(n);return t?(t.abort(),!0):!1};window.uauth.validateAuthUrl=function(n,t=null){if(!n||typeof n!="string")throw new Error("Authentication URL is required.");const r=t?new URL(t,window.location.origin):new URL(window.location.origin),i=new URL(n,document.baseURI);if(!["http:","https:"].includes(r.protocol))throw new Error("Unsupported trusted origin protocol.");if(!["http:","https:"].includes(i.protocol))throw new Error("Unsupported authentication URL protocol.");if(r.username||r.password)throw new Error("Trusted origin cannot contain credentials.");if(i.username||i.password)throw new Error("Authentication URL cannot contain credentials.");if(i.origin!==r.origin)throw new Error("Authentication request target differs from the trusted UAuthHub origin.");return i.href};window.uauth.antiforgery={tokenUrl:null,configure:function(n){if(!n?.tokenUrl)throw new Error("UAuth antiforgery token URL is required.");this.tokenUrl=window.uauth.validateAuthUrl(n.tokenUrl,n.trustedOrigin)},getToken:async function(n){if(!this.tokenUrl)throw new Error("UAuth antiforgery is not configured.");const r=window.uauth.validateAuthUrl(this.tokenUrl,n),i=await fetch(r,{method:"GET",credentials:"include",cache:"no-store",redirect:"error",headers:{"X-UDID":window.uauth.deviceId}});if(!i.ok)throw new Error(`Unable to obtain UAuth antiforgery token: HTTP ${i.status}.`);const t=await i.json();if(!t?.requestToken||!t?.headerName||!t?.formFieldName)throw new Error("Invalid UAuth antiforgery response.");return t},appendToForm:async function(n,t){const r=await this.getToken(t);let i=Array.from(n.elements).find(n=>n.name===r.formFieldName);i||(i=document.createElement("input"),i.type="hidden",i.name=r.formFieldName,n.appendChild(i));i.value=r.requestToken}};window.uauth.submitLoginForm=async function(n,t){if(!(n instanceof HTMLFormElement))throw new Error("A native HTML form is required.");const{mode:o,tryUrl:p,commitUrl:w,applicationProfile:b,trustedOrigin:e,isPkce:s}=t;if(!["TryOnly","TryAndCommit","DirectCommit"].includes(o))throw new Error("Unsupported UAuth submit mode.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const l=window.uauth.validateAuthUrl(w,e),k=o==="DirectCommit"?null:window.uauth.validateAuthUrl(p,e),r=new FormData(n),a=r.getAll("Identifier"),v=r.getAll("Secret");if(a.length!==1||v.length!==1)throw new Error("Login form requires exactly one Identifier and one Secret.");const h=a[0],c=v[0];if(typeof h!="string"||typeof c!="string"||!h.trim()||!c.trim())throw new Error("Identifier and Secret are required.");if(s)for(const n of["authorization_code","code_verifier"]){const t=r.getAll(n);if(t.length!==1||typeof t[0]!="string"||!t[0])throw new Error(`Missing or duplicate PKCE field: ${n}`);}if(s){const t=r.get("hub_session_id");if(typeof t!="string"||!t)throw new Error("Missing PKCE Hub session ID.");const i=new URL(l);i.searchParams.set("uauth_hub",t);n.action=i.href}else n.action=l;if(o==="DirectCommit")return await window.uauth.submitForm(n,e),null;const f={Identifier:h,Secret:c};s?(f.authorization_code=r.get("authorization_code"),f.code_verifier=r.get("code_verifier"),f.__uauth_return_url=r.get("__uauth_return_url")??"",f.hub_session_id=r.get("hub_session_id")??""):f.ReturnUrl=r.get("__uauth_return_url")??"";const i=await window.uauth.postJson({url:k,payload:f,applicationProfile:b,trustedOrigin:e});if(!i||!Number.isInteger(i.status))throw new Error("Invalid UAuth transport response.");if(i.status===429)return{isSuccess:!1,status:429,errorCode:"rate_limited",retryAfter:i.retryAfter??null};const d=i.status>=200&&i.status<300,y=i.status>=400&&i.status<500;if(!d&&!y)throw new Error(`Unexpected UAuth try response: HTTP ${i.status}.`);const u=i.body;if(!u||typeof u!="object"||Array.isArray(u)||typeof u.isSuccess!="boolean")throw new Error("Invalid UAuth try response body.");if(y&&u.isSuccess)throw new Error("Successful authentication result returned with HTTP error.");if(o==="TryAndCommit"&&u.isSuccess){if(u.previewReceipt){let t=Array.from(n.elements).find(n=>n.name==="PreviewReceipt");t||(t=document.createElement("input"),t.type="hidden",t.name="PreviewReceipt",n.appendChild(t));t.value=u.previewReceipt}await window.uauth.submitForm(n,e)}return u};window.uauth.setDeviceId=function(n){window.uauth.deviceId=n};window.uauth.getDeviceInfo=function(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language}} \ No newline at end of file diff --git a/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthTokenStore.cs b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthTokenStore.cs new file mode 100644 index 00000000..e8ca48b2 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthTokenStore.cs @@ -0,0 +1,28 @@ +using CodeBeam.UltimateAuth.Core.Contracts; + +namespace CodeBeam.UltimateAuth.Client.Abstractions; + +/// +/// Stores the access credential associated with the current client scope. +/// +/// +/// The store does not determine the authentication mode, application profile, +/// grant delivery mechanism, or transport. +/// +public interface IUAuthTokenStore +{ + /// + /// Returns the currently stored access token, if any. + /// + AccessToken? Read(); + + /// + /// Atomically replaces the current access token. + /// + void Replace(AccessToken token); + + /// + /// Removes the current access token. + /// + void Clear(); +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTransportResult.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTransportResult.cs index 4381fd98..f00034de 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTransportResult.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTransportResult.cs @@ -34,6 +34,24 @@ public sealed class UAuthTransportResult [JsonPropertyName("refreshOutcome")] public string? RefreshOutcome { get; init; } + /// + /// Raw access credential returned by the transport, when the configured delivery mechanism exposes it. + /// + [JsonPropertyName("accessToken")] + public string? AccessToken { get; init; } + + /// + /// Access token expiration metadata supplied by the issuer. + /// + [JsonPropertyName("accessTokenExpiresAt")] + public string? AccessTokenExpiresAt { get; init; } + + [JsonPropertyName("accessTokenFormat")] + public string? AccessTokenFormat { get; init; } + + [JsonPropertyName("accessTokenHeaderFormat")] + public string? AccessTokenHeaderFormat { get; init; } + /// /// Gets the response body as JSON, when a body is available. /// diff --git a/src/client/CodeBeam.UltimateAuth.Client/Extensions/ServiceCollectionExtensions.cs b/src/client/CodeBeam.UltimateAuth.Client/Extensions/ServiceCollectionExtensions.cs index 906be2aa..fede44f7 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Extensions/ServiceCollectionExtensions.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Extensions/ServiceCollectionExtensions.cs @@ -1,4 +1,5 @@ -using CodeBeam.UltimateAuth.Client.Authentication; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Authentication; using CodeBeam.UltimateAuth.Client.Device; using CodeBeam.UltimateAuth.Client.Devices; using CodeBeam.UltimateAuth.Client.Events; @@ -122,6 +123,8 @@ private static IServiceCollection AddUltimateAuthClientInternal(this IServiceCol services.TryAddScoped(); services.TryAddScoped(); + services.TryAddScoped(); + return services; } } diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/InMemoryUAuthTokenStore.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/InMemoryUAuthTokenStore.cs new file mode 100644 index 00000000..2c168c02 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/InMemoryUAuthTokenStore.cs @@ -0,0 +1,29 @@ +using System.Threading; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Core.Contracts; + +namespace CodeBeam.UltimateAuth.Client.Infrastructure; + +/// +/// Stores a single access token in managed memory. +/// +/// +/// The instance must be scoped to the current client or user. +/// It does not persist credentials across application restarts. +/// +internal sealed class InMemoryUAuthTokenStore : IUAuthTokenStore +{ + private AccessToken? _token; + + public AccessToken? Read() + => Volatile.Read(ref _token); + + public void Replace(AccessToken token) + { + ArgumentNullException.ThrowIfNull(token); + Volatile.Write(ref _token, token); + } + + public void Clear() + => Volatile.Write(ref _token, null); +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthFlowClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthFlowClient.cs index 7f6f21c6..7a970ca4 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthFlowClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthFlowClient.cs @@ -12,6 +12,7 @@ using CodeBeam.UltimateAuth.Core.Infrastructure; using CodeBeam.UltimateAuth.Users.Contracts; using Microsoft.Extensions.Options; +using System.Globalization; using System.Net; using System.Security.Cryptography; using System.Text; @@ -27,10 +28,12 @@ internal class UAuthFlowClient : IFlowClient private readonly IReturnUrlProvider _returnUrlProvider; private readonly UAuthClientOptions _options; private readonly UAuthClientDiagnostics _diagnostics; + private readonly IUAuthTokenStore _tokenStore; + private DateTimeOffset _refreshNotBefore; private RefreshResult? _refreshThrottle; - public UAuthFlowClient(IUAuthRequestClient post, IUAuthClientEvents events, IClientDeviceProvider clientDeviceProvider, IReturnUrlProvider returnUrlProvider, IOptions options, UAuthClientDiagnostics diagnostics) + public UAuthFlowClient(IUAuthRequestClient post, IUAuthClientEvents events, IClientDeviceProvider clientDeviceProvider, IReturnUrlProvider returnUrlProvider, IOptions options, UAuthClientDiagnostics diagnostics, IUAuthTokenStore tokenStore) { _post = post; _events = events; @@ -38,6 +41,7 @@ public UAuthFlowClient(IUAuthRequestClient post, IUAuthClientEvents events, ICli _returnUrlProvider = returnUrlProvider; _options = options.Value; _diagnostics = diagnostics; + _tokenStore = tokenStore; } private string Url(string path) => UAuthUrlBuilder.Build(_options.Endpoints.BasePath, path, _options.MultiTenant); @@ -128,6 +132,7 @@ public async Task LogoutAsync(bool navigate = true) if (raw.Status is < 200 or >= 300) throw new UAuthTransportException("Server logout did not succeed.", (HttpStatusCode)raw.Status); + _tokenStore.Clear(); await _events.PublishAsync(new UAuthStateEventArgsEmpty(UAuthStateEvent.LogoutVariant, _options.StateEvents.HandlingMode)); } @@ -160,6 +165,7 @@ public async Task RefreshAsync(bool isAuto = false) // 401 is a normal authentication outcome for refresh. if (raw.Status == 401) { + _tokenStore.Clear(); _diagnostics.MarkRefreshReauthRequired(); return new RefreshResult @@ -175,6 +181,23 @@ public async Task RefreshAsync(bool isAuto = false) var outcome = RefreshOutcomeParser.Parse(raw.RefreshOutcome); var isSuccess = raw.Status is >= 200 and < 300 && raw.Ok; + if (isSuccess) + { + var accessToken = ReadAccessToken(raw); + + if (accessToken is not null) + { + if (accessToken.IsExpired(DateTimeOffset.UtcNow)) + { + _tokenStore.Clear(); + + throw new UAuthProtocolException("Server returned an expired access token."); + } + + _tokenStore.Replace(accessToken); + } + } + // Never record a successful refresh outcome // for a failed HTTP response. if (isSuccess) @@ -498,6 +521,61 @@ public async Task LogoutAllUserDevicesAsync(UserKey userKey) } + private static AccessToken? ReadAccessToken(UAuthTransportResult raw) + { + if (string.IsNullOrWhiteSpace(raw.AccessToken)) + return null; + + if (string.IsNullOrWhiteSpace(raw.AccessTokenExpiresAt) || + !DateTimeOffset.TryParse( + raw.AccessTokenExpiresAt, + CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, + out var expiresAt)) + { + throw new UAuthProtocolException("Access token expiration metadata is invalid."); + } + + var format = raw.AccessTokenFormat?.ToLowerInvariant() switch + { + "jwt" => TokenFormat.Jwt, + "opaque" => TokenFormat.Opaque, + _ => throw new UAuthProtocolException("Access token format metadata is invalid.") + }; + + var token = raw.AccessToken; + + switch (raw.AccessTokenHeaderFormat?.ToLowerInvariant()) + { + case "bearer": + if (!token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + { + throw new UAuthProtocolException("Invalid Bearer access token header."); + } + + token = token["Bearer ".Length..]; + break; + + case "raw": + break; + + default: + throw new UAuthProtocolException("Access token header format metadata is invalid."); + } + + if (string.IsNullOrWhiteSpace(token) || token.Contains('\r') || token.Contains('\n')) + { + throw new UAuthProtocolException("Invalid access token value."); + } + + return new AccessToken + { + Token = token, + Format = format, + ExpiresAt = expiresAt + }; + } + private void EnsureCanPost() { var canPost = ClientLoginCapabilities.CanPostCredentials(_options.ApplicationProfile); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthTokenStoreTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthTokenStoreTests.cs new file mode 100644 index 00000000..6725b8ed --- /dev/null +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthTokenStoreTests.cs @@ -0,0 +1,81 @@ +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Core.Contracts; + +namespace CodeBeam.UltimateAuth.Tests.Unit; + +public sealed class UAuthTokenStoreTests +{ + [Fact] + public void New_store_has_no_token() + { + var store = new InMemoryUAuthTokenStore(); + + Assert.Null(store.Read()); + } + + [Fact] + public void Replace_stores_access_token() + { + var store = new InMemoryUAuthTokenStore(); + var token = CreateToken("first"); + + store.Replace(token); + + Assert.Same(token, store.Read()); + } + + [Fact] + public void Replace_overwrites_previous_token() + { + var store = new InMemoryUAuthTokenStore(); + var first = CreateToken("first"); + var second = CreateToken("second"); + + store.Replace(first); + store.Replace(second); + + Assert.Same(second, store.Read()); + } + + [Fact] + public void Clear_removes_token() + { + var store = new InMemoryUAuthTokenStore(); + + store.Replace(CreateToken("first")); + store.Clear(); + + Assert.Null(store.Read()); + } + + [Fact] + public void Stores_are_isolated() + { + var first = new InMemoryUAuthTokenStore(); + var second = new InMemoryUAuthTokenStore(); + + first.Replace(CreateToken("first")); + + Assert.NotNull(first.Read()); + Assert.Null(second.Read()); + } + + [Fact] + public void Expiration_uses_issuer_metadata() + { + var now = DateTimeOffset.UtcNow; + var token = CreateToken("opaque-access-value"); + + Assert.False(token.IsExpired(now)); + Assert.True(token.IsExpired(now.AddSeconds(601))); + } + + private static AccessToken CreateToken(string value) + => new() + { + Token = value, + Format = TokenFormat.Jwt, + ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5) + }; +} From f6b164245fe76d18ab1750ba9401cea395f45bc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Sun, 22 Nov 2026 22:57:48 +0300 Subject: [PATCH 02/17] Add Transport Protocol for Bearer Token --- .../Components/Custom/NotAuthorized.razor | 23 +++++++ .../Components/Custom/NotAuthorized.razor.cs | 61 ++++++++++++++++++- .../Components/Page/SampleLogin.razor.cs | 3 +- .../Endpoints/LoginEndpointHandler.cs | 12 ++++ .../AspNetCore/TransportCredentialResolver.cs | 43 ++++++++++--- .../Infrastructure/UAuthRequestClient.cs | 30 +++++---- .../TScripts/uauth.js | 36 +++++++++-- .../wwwroot/uauth.min.js | 2 +- .../Infrastructure/IUAuthRequestClient.cs | 2 + .../Services/Abstractions/IFlowClient.cs | 2 + .../Services/UAuthFlowClient.cs | 56 ++++++++++++++++- 11 files changed, 239 insertions(+), 31 deletions(-) diff --git a/samples/CodeBeam.UltimateAuth.Sample.Shared/Components/Custom/NotAuthorized.razor b/samples/CodeBeam.UltimateAuth.Sample.Shared/Components/Custom/NotAuthorized.razor index d999bf2f..5d289bf7 100644 --- a/samples/CodeBeam.UltimateAuth.Sample.Shared/Components/Custom/NotAuthorized.razor +++ b/samples/CodeBeam.UltimateAuth.Sample.Shared/Components/Custom/NotAuthorized.razor @@ -54,6 +54,29 @@ + + + Validate + + + + Refresh + + + + @if (!string.IsNullOrWhiteSpace(_diagnostic)) + { + + @_diagnostic + + } + - - - Validate - - - - Refresh - - - - @if (!string.IsNullOrWhiteSpace(_diagnostic)) - { - - @_diagnostic - - } -