You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Auth][OAuth2] Add oAuth2 as official Authentication option? #2870
Make public accessable, so we could add Properties/Funktionallity by inheritance?
the WebAuthenticationOptions / CustomAuthenticationOptions ...
Some WebAuthProvider (base?) class, not just the Interface or the BaseAuthenticationProvider, which does not already implement this Web specifics we would need for e.g. this szenario. By this, we would not have to care about how you call the Web Browser for example or other platform specifics
Why is this needed:
I am looking for any way to implement oAuth2 into my Uno Applications.
changed the title [-][Auth] Add OpenIdDict as Authentication option?[/-][+][Auth] Add oAuth2 as official Authentication option? E.g. possible with OpenIdDict[/+]on Jul 31, 2025
changed the title [-][Auth] Add oAuth2 as official Authentication option? E.g. possible with OpenIdDict[/-][+][Auth] Add oAuth2 as official Authentication option?[/+]on Aug 9, 2025
added the delegates I used to put in my own project repo into a own service
uno seems to expect us to do it the messy way with delegates so put it in the app.xaml.cs there, they are not connect able to the web auth builder as e.g. the Refresh would from the intellisense only provide 2 dictionarys but nothing else that would be needed!
we do not have a Interface to fullfill with TService on the WebAuthenticationProvider we are configuring in the hostbuilder, which seems to optionally take a Generic brackets to put that also in the delegates but that still not changes that that are delegates...
same with the oAuth2 standard defined constant namings in "Defaults" folder.
No idea why uno themselfs using non json compartible key namings for the AccessToken and RefreshToken in the TokenCacheExtensions, but that is making it non usable for me so I defined my own ones and I think I will be needed to not use the "SaveTokensAsync" extension just because of this.
as you can see, that is not resolving at all, we have to duplicate code since the WebConfiguration is not public accessable so we can not source even IOptions<WebConfiguration> we do define in appsettings.
and yes, on my side the browser does not open on desktop as its not implemented somehow... but yes of course just disabling web auth on desktop will defintly fix that (not!) but... yes... authorization code flow with pkce and uno seems to be not friends from user side...
of course its my problem that I want to connect to that api there which not allows protocol callback, but all platform seem to not mean auth extensions. just not working right now.
after long investigation, I now came up with this app.xaml.cs content.
and as you can see, using delegates like that is adding very much content to that one file, which is why I would really like to have the option to move it to its own service!
I think now the last missing part for my app (its again building!) would be that the WebAuthenticationBrokerProvider would be implemented for Desktop target 🚀
usingSystem.Text.RegularExpressions;usingSystem.Web;namespaceDevTKSS.MyManufacturerERP;publicpartialclassApp:Application{/// <summary>/// Initializes the singleton application object. This is the first line of authored code/// executed, and as such is the logical equivalent of main() or WinMain()./// </summary>publicApp(){this.InitializeComponent();}protectedWindow?MainWindow{get;privateset;}protectedIHost?Host{get;privateset;}protectedasyncoverridevoidOnLaunched(LaunchActivatedEventArgsargs){varbuilder=this.CreateBuilder(args)// Add navigation support for toolkit controls such as TabBar and NavigationView.UseToolkitNavigation().Configure(host => host
#if DEBUG// Switch to Development environment when running in DEBUG.UseEnvironment(Environments.Development)
#endif
.UseLogging(configure:(context,logBuilder)=>{// Configure log levels for different categories of logginglogBuilder.SetMinimumLevel(context.HostingEnvironment.IsDevelopment()?LogLevel.Information:LogLevel.Warning)// Default filters for core Uno Platform namespaces.CoreLogLevel(LogLevel.Warning);// Uno Platform namespace filter groups// Uncomment individual methods to see more detailed logging//// Generic Xaml events//logBuilder.XamlLogLevel(LogLevel.Debug);//// Layout specific messages//logBuilder.XamlLayoutLogLevel(LogLevel.Debug);//// Storage messages//logBuilder.StorageLogLevel(LogLevel.Debug);//// Binding related messages//logBuilder.XamlBindingLogLevel(LogLevel.Debug);//// Binder memory references tracking//logBuilder.BinderMemoryReferenceLogLevel(LogLevel.Debug);//// DevServer and HotReload related//logBuilder.HotReloadCoreLogLevel(LogLevel.Information);//// Debug JS interop//logBuilder.WebAssemblyLogLevel(LogLevel.Debug);},enableUnoLogging:true).UseSerilog(consoleLoggingEnabled:true,fileLoggingEnabled:true).UseConfiguration(configure: unoConfigBuilder =>unoConfigBuilder.EmbeddedSource<App>().Section<AppConfig>().Section<OAuthOptions>("EtsyOAuthOptions").Section<ApiKeyOptions>("SevdeskApiKeyClient"))// Enable localization (see appsettings.json for supported languages).UseLocalization()// Register Json serializers (ISerializer and ISerializer).UseSerialization((context,services)=>services// Adding String TypeInfo <see href="https://github.com/unoplatform/uno/issues/20546"/>.AddContentSerializer(context).AddJsonTypeInfo(OAuthFlowContext.Default.AccessGrantResponse).AddJsonTypeInfo(OAuthFlowContext.Default.TokenResponse).AddJsonTypeInfo(EtsyJsonContext.Default.OAuthOptions).AddJsonTypeInfo(EtsyJsonContext.Default.UserDetailsResponse).AddJsonTypeInfo(EtsyJsonContext.Default.UserMeResponse).AddJsonTypeInfo(EtsyJsonContext.Default.PingResponse)).UseHttp((context,services)=>{
#if DEBUG// DelegatingHandler will be automatically injectedservices.AddTransient<DelegatingHandler,DebugHttpHandler>();
#endif
services.AddRefitClientWithEndpoint<IEtsyOAuthEndpoints,OAuthOptions>(context:context,options:context.Configuration.GetSection("EtsyOAuthOptions").Get<OAuthOptions>(),name:"EtsyClient",configure:(clientBuilder,options)=>clientBuilder.ConfigureHttpClient(httpClient =>{httpClient.BaseAddress=newUri("https://openapi.etsy.com");if(options?.ClientIDisnull){thrownewArgumentNullException(options?.ClientID,nameof(options.ClientID));}httpClient.DefaultRequestHeaders.Add("x-api-key",options.ClientID);})).AddRefitClient<IEtsyUserEndpoints>(context);}).UseAuthentication(authBuilder =>// reference used: https://github.com/unoplatform/uno.extensions/blob/main/testing/TestHarness/TestHarness/Ext/Authentication/Web/WebAuthenticationHostInit.csauthBuilder.AddWeb<IEtsyOAuthEndpoints>(configureWeb =>configureWeb.LoginStartUri("https://openapi.etsy.com/v3/public/oauth/connect").AccessTokenKey(OAuthTokenRefreshDefaults.AccessTokenKey).RefreshTokenKey(OAuthTokenRefreshDefaults.RefreshToken).PrefersEphemeralWebBrowserSession(true).LoginCallbackUri("https://localhost:5001/etsy-auth-callback").PrepareLoginCallbackUri(async(service,serviceProvider,tokencache,loginCallbackUri,ct)=>loginCallbackUri!).PrepareLoginStartUri(async(sp,tokens,credentials,loginStartUri,ct)=>awaitCreateLoginStartUri(sp,tokens,credentials,loginStartUri,ct)).PostLogin(async(authService,serviceProvider,tokenCache,credentials,redirectUri,tokens,cancellationToken)=>awaitProcessPostLoginAsync(authService,serviceProvider,tokenCache,credentials,redirectUri,tokens,cancellationToken)).Refresh(async(authService,serviceProvider,tokenCache,tokens,cancellationToken)=>awaitRefreshTokensAsync(authService,serviceProvider,tokenCache,tokens,cancellationToken)),name:"EtsyOAuth"),configureAuthorization: builder =>{builder.AuthorizationHeader(scheme:"Bearer");}).ConfigureServices((context,services)=>{// TODO: Register your sp//#if !WINDOWS// services.AddSingleton<IWebAuthenticationBrokerProvider, SystemBrowserAuthBroker>();//#endifservices.AddSingleton<IHelpers,Helpers>();services.AddSingleton<ITasksManager,TasksManager>();services.AddSingleton<EtsyOAuthAuthenticationDelegate>();}).UseNavigation(ReactiveViewModelMappings.ViewModelMappings,RegisterRoutes));MainWindow=builder.Window;
#if DEBUGMainWindow.UseStudio();
#endif
MainWindow.SetWindowIcon();Host=awaitbuilder.NavigateAsync<Shell>(initialNavigate:async(services,navigator)=>{varauth=services.GetRequiredService<IAuthenticationService>();varauthenticated=awaitauth.RefreshAsync();if(authenticated){awaitnavigator.NavigateViewModelAsync<MainModel>(this,qualifier:Qualifiers.Nested);}else{awaitnavigator.NavigateViewModelAsync<AuthModel>(this,qualifier:Qualifiers.Nested);}});}
#region Authentication Handlers
privatestring?_stateBackingField;privatestring?_codeVerifierBackingField;internalasyncValueTask<string>CreateLoginStartUri(IServiceProviderservices,ITokenCachetokens,IDictionary<string,string>?credentials,// if this is null, can we use it for storing state and code verifier?string?loginStartUri,CancellationTokencancellationToken){varoptions=services.GetRequiredService<IOptions<OAuthOptions>>().Value;credentials??=newDictionary<string,string>();if(string.IsNullOrWhiteSpace(loginStartUri))loginStartUri=options.AuthorizationEndpoint!;varscope=string.Join(' ',options.Scopes);varstate=OAuth2Utilitys.GenerateState();varcodeVerifier=OAuth2Utilitys.GenerateCodeVerifier();varcodeChallenge=OAuth2Utilitys.GenerateCodeChallenge(codeVerifier);varurl=newUriBuilder(loginStartUri);varsb=newStringBuilder();voidadd(stringk,string?v){if(sb.Length>0)sb.Append('&');sb.Append(Uri.EscapeDataString(k)).Append('=').Append(Uri.EscapeDataString(v??string.Empty));}add(OAuthAuthRequestDefaults.ResponseTypeKey,OAuthAuthRequestDefaults.CodeKey);add(OAuthAuthRequestDefaults.ClientIdKey,options.ClientID);add(OAuthAuthRequestDefaults.RedirectUriKey,options.RedirectUri);add(OAuthAuthRequestDefaults.ScopeKey,scope);add(OAuthAuthRequestDefaults.StateKey,state);add(OAuthPkceDefaults.CodeChallengeKey,codeChallenge);add(OAuthPkceDefaults.CodeChallengeMethodKey,OAuthPkceDefaults.CodeChallengeMethodS256);url.Query=sb.ToString();credentials.AddOrReplace(OAuthAuthRequestDefaults.StateKey,state);credentials.AddOrReplace(OAuthPkceDefaults.CodeVerifierKey,codeVerifier);// in case the credentials is null better use backing fields_stateBackingField=state;_codeVerifierBackingField=codeVerifier;returnurl.Uri.ToString();}// No idea how to instead integrate this to a seperate service but even then no idea how to open that damn browserprivateasyncValueTask<IDictionary<string,string>?>ProcessPostLoginAsync(IEtsyOAuthEndpointsauthEndpoints,IServiceProviderserviceProvider,ITokenCachetokenCache,IDictionary<string,string>?credentials,stringredirectUri,IDictionary<string,string>tokens,CancellationTokenct=default){varoptions=serviceProvider.GetRequiredService<IOptions<OAuthOptions>>().Value;if(credentialsisnull){Log.Error("Credentials are null, cannot process post login. Will try to use backing fields.");}// Try to get state and codeVerifier from credentials, otherwise use backing fieldsstring?state=null;string?codeVerifyer=null;if(credentials!=null){credentials.TryGetState(outstate);credentials.TryGetCodeVerifier(outcodeVerifyer);}if(string.IsNullOrEmpty(state))state=_stateBackingField;if(string.IsNullOrEmpty(codeVerifyer))codeVerifyer=_codeVerifierBackingField;// TODO: Write code to process credentials that are passed into the LoginAsync methodif(!string.IsNullOrEmpty(state)&&!string.IsNullOrEmpty(codeVerifyer)){// Copyed from Uno.Extensions.Web.WebAuthenticationProvidervarquery=redirectUri.StartsWith(options.RedirectUri!)?AuthHttpUtility.ExtractArguments(redirectUri)// authData is a fully qualified url, so need to extract query or fragment:AuthHttpUtility.ParseQueryString(redirectUri.TrimStart('#').TrimStart('?'));// authData isn't full url, so just process as query or fragment// The redirectUri does hold the full response of the AuthorizationBrokerProvider// so its including all eventual query parameters that are not covered by the AccessToken or RefreshToken keys// if https://github.com/unoplatform/uno.extensions/pull/2893 gets merged, you could also provide additional query keys via 'OtherTokenKeys' in the appsettings section for WebAuthenticationProvider 'WebConfiguration' normally aliased with 'Web'varreturnedState=query?.Get(OAuthAuthResponseDefaults.StateKey);// why is the Get not working while the uno extensions is using it the same?varauthorizationCode=query?.Get(OAuthAuthResponseDefaults.CodeKey);varerror=query?.Get(OAuthErrorResponseDefaults.ErrorKey);varerrorDescription=query?.Get(OAuthErrorResponseDefaults.ErrorDescriptionKey);varerrorUri=query?.Get(OAuthErrorResponseDefaults.ErrorUriKey);// Validate state and codeif(string.IsNullOrWhiteSpace(state)||returnedState!=state||string.IsNullOrWhiteSpace(authorizationCode)){Log.Error("Invalid state or code. State: '{state}', Old State: '{oldState}', Code: '{authCode}', Code Verifyer: {codeVerifier}",returnedState,state,authorizationCode,codeVerifyer);returndefault;}TokenResponsetokenExchangeResult=awaitauthEndpoints.ExchangeCodeAsync(newAccessTokenRequest{GrantType=OAuthTokenRefreshDefaults.AuthorizationCode,ClientId=options.ClientID!,RedirectUri=options.RedirectUri!,Code=authorizationCode,CodeVerifier=codeVerifyer!});if(!(string.IsNullOrWhiteSpace(tokenExchangeResult.AccessToken)||string.IsNullOrWhiteSpace(tokenExchangeResult.RefreshToken))){Log.Error("Failed to exchange code for access token!");returndefault;}// extract userId from refreshToken you may need it latervarmatch=DoesContainUserId().Match(tokenExchangeResult.AccessToken!);if(match.Success){stringuserId=match.Groups[1].Value;}varexpirationTimeStamp=DateTime.Now.AddSeconds(tokenExchangeResult.ExpiresIn).ToString("g");// Save additional tokens if neededtokens.AddOrReplace(OAuthTokenRefreshDefaults.AccessTokenKey,tokenExchangeResult.AccessToken!);tokens.AddOrReplace(OAuthTokenRefreshDefaults.RefreshToken,tokenExchangeResult.RefreshToken!);tokens.AddOrReplace(OAuthTokenRefreshExtendedDefaults.ExpirationDateKey,expirationTimeStamp);// remove the state and code verifier from credentials as they are no longer neededif(!credentials.TryRemoveKeys([OAuthAuthRequestDefaults.StateKey,OAuthPkceDefaults.CodeVerifierKey])){Log.Warning("Failed to remove state and code verifier from credentials. Credentials was null? {Credentials}",credentials==null);}returntokens;}// Return null/default to fail the LoginAsync methodreturndefault;}privateasyncValueTask<IDictionary<string,string>?>RefreshTokensAsync(IEtsyOAuthEndpointsauthEndpoints,IServiceProviderserviceProvider,ITokenCachetokenCache,IDictionary<string,string>?tokens,CancellationTokenct=default){varoptions=serviceProvider.GetRequiredService<IOptions<OAuthOptions>>().Value;if(tokensisnull){Log.Error("Tokens are null, cannot refresh tokens.");returndefault;}// TODO: Write code to refresh tokens using the currently stored tokensif((tokens?.TryGetRefreshToken(outvarrefreshToken)??false)&&!refreshToken.IsNullOrWhiteSpace()&&(tokens?.TryGetExpirationDate(outvartokenExpiry)??false)&&tokenExpiry>DateTime.Now){vartokenResponse=awaitauthEndpoints.RefreshTokenAsync(newRefreshTokenRequest{GrantType=OAuthTokenRefreshDefaults.RefreshToken,ClientId=options.ClientID!,RefreshToken=refreshToken!});if(string.IsNullOrEmpty(tokenResponse.AccessToken)||string.IsNullOrEmpty(tokenResponse.RefreshToken)){Log.Error("Refresh response missing access_token or refresh_token.");returndefault;}// Return IDictionary containing any tokens used by service calls or in the apptokens.AddOrReplace(OAuthTokenRefreshDefaults.AccessTokenKey,tokenResponse.AccessToken);tokens.AddOrReplace(OAuthTokenRefreshDefaults.RefreshToken,tokenResponse.RefreshToken);tokens.AddOrReplace(OAuthTokenRefreshDefaults.ExpiresInKey,DateTime.Now.AddMinutes(5).ToString("g"));returntokens;}// Return null/default to fail the Refresh methodreturndefault;}
#endregion
privatestaticvoidRegisterRoutes(IViewRegistryviews,IRouteRegistryroutes){views.Register(newViewMap(ViewModel:typeof(ShellModel)),newViewMap<AuthPage,AuthModel>(),newViewMap<MainPage,MainModel>(),newDataViewMap<SecondPage,SecondModel,Entity>());routes.Register(newRouteMap("",View:views.FindByViewModel<ShellModel>(),Nested:[new("Main",View:views.FindByViewModel<MainModel>(),IsDefault:true),new("Second",View:views.FindByViewModel<SecondModel>()),new("Auth",View:views.FindByViewModel<AuthModel>()),]));}[GeneratedRegex(@"^(\d+)\.")]privatestaticpartialRegexDoesContainUserId();}
reworking, updating and improving this approach with a IAuthenticationBuilder Extension currently on my Repo but to workaround all of the internal definitions, I now resigned to "just" copy most of the Uno.Extensions.Authentication (+ WinUI aka Web) files at state of:
over to there, so I can workaround the me not beeing able to build and validate changes to Uno.Extensions also on my other PR's of this repo, as you can find on the currently latest commit on my mentioned Repo: DevTKSS/DevTKSS.MyManufacturerERP@48d06be
will just drop this sh... Authentication Extension now, sorry Uno but that code piece doesnt work.
even making it an own Interface without the ApiExtensin doesnt work. failing on #2895 just like CustomAuth.
just uncomment the api extension and remove the TokenCache registration from the HostBuilderExtensions from OAuthServices folder and you can check it out yourself 😒 look how gracefully the OAuthService is registred the line before it calls the AddWeb and on Button clicking its just failing. hopeless. DevTKSS/DevTKSS.MyManufacturerERP@3c84453
Also was considering to implement it through OpenIdDict, but thats not even possible with the current Xamarin package versions uno makes us use, even not when I set the version explicitly in the Directory.Package.props file, so I could try to use their SystemIntegration package. Additionaly problematic on this would be for me that the provider I need is not supported by them so far, but that would be my smallest problem if it would generally be possible with that package version...
changed the title [-][Auth] Add oAuth2 as official Authentication option?[/-][+][Auth][OAuth2] Add oAuth2 as official Authentication option?[/+]on Nov 25, 2025
Activity
DevTKSS commentedon Jul 28, 2025
@jeromelaban dont know if Uno has this WinAppSdk issue on tracker list, but if not, would you consider adding it?
[-][Auth] Add OpenIdDict as Authentication option?[/-][+][Auth] Add oAuth2 as official Authentication option? E.g. possible with OpenIdDict[/+][-][Auth] Add oAuth2 as official Authentication option? E.g. possible with OpenIdDict[/-][+][Auth] Add oAuth2 as official Authentication option?[/+]DevTKSS commentedon Aug 15, 2025
sample repro with web auth for a non protocol allowing api, using desktop target
UnoWebAuthCodeFlowRepro.zip
added the delegates I used to put in my own project repo into a own service
TServiceon theWebAuthenticationProviderwe are configuring in the hostbuilder, which seems to optionally take a Generic brackets to put that also in the delegates but that still not changes that that are delegates...and the responses I would read from that to be needed
WebConfigurationis not public accessable so we can not source evenIOptions<WebConfiguration>we do define in appsettings.you can find my Service definition for that right here: https://github.com/DevTKSS/DevTKSS.MyManufacturerERP/blob/master/src/DevTKSS.MyManufacturerERP/Infrastructure/Services/EtsyOAuthAuthenticationDelegate.cs
to compare it and maybe find a way we could implement oauth2?
not sure if extensions of auth itself would be allowed to use refit instead of httpClient? would be way cleaner maybe than that whole bunch of dictionarys...
and yes, on my side the browser does not open on desktop as its not implemented somehow... but yes of course just disabling web auth on desktop will defintly fix that (not!) but... yes... authorization code flow with pkce and uno seems to be not friends from user side...
of course its my problem that I want to connect to that api there which not allows protocol callback, but all platform seem to not mean auth extensions. just not working right now.
DevTKSS commentedon Aug 16, 2025
@MartinZikmund I found this sample (6 years old, so maybe not longer applying) for uwp and the WebAuthenticationBroker:
https://github.com/microsoft/Windows-universal-samples/blob/main/Samples/WebAuthenticationBroker/cs/Scenario1_Facebook.xaml.cs
and will try it out. Maybe that could be reused for the oAuth2 Auth Code flow in Uno too even if its not longer UWP Based, the Desktop target is at least very similar if it runs on Windows.
DevTKSS commentedon Aug 17, 2025
after long investigation, I now came up with this app.xaml.cs content.
and as you can see, using delegates like that is adding very much content to that one file, which is why I would really like to have the option to move it to its own service!
I think now the last missing part for my app (its again building!) would be that the WebAuthenticationBrokerProvider would be implemented for Desktop target 🚀
AddOrReplacewould join the extensions with BREAKING CHANGE: TokenCacheExtensions: Match the used key namings to the TokenCache defaults and standarized official namings #2893DevTKSS commentedon Sep 7, 2025
reworking, updating and improving this approach with a IAuthenticationBuilder Extension currently on my Repo but to workaround all of the internal definitions, I now resigned to "just" copy most of the Uno.Extensions.Authentication (+ WinUI aka Web) files at state of:
over to there, so I can workaround the me not beeing able to build and validate changes to Uno.Extensions also on my other PR's of this repo, as you can find on the currently latest commit on my mentioned Repo:
DevTKSS/DevTKSS.MyManufacturerERP@48d06be
DevTKSS commentedon Sep 15, 2025
will just drop this sh... Authentication Extension now, sorry Uno but that code piece doesnt work.
even making it an own Interface without the ApiExtensin doesnt work. failing on #2895 just like CustomAuth.
just uncomment the api extension and remove the TokenCache registration from the HostBuilderExtensions from OAuthServices folder and you can check it out yourself 😒 look how gracefully the OAuthService is registred the line before it calls the AddWeb and on Button clicking its just failing. hopeless.
DevTKSS/DevTKSS.MyManufacturerERP@3c84453
Also was considering to implement it through OpenIdDict, but thats not even possible with the current Xamarin package versions uno makes us use, even not when I set the version explicitly in the Directory.Package.props file, so I could try to use their SystemIntegration package. Additionaly problematic on this would be for me that the provider I need is not supported by them so far, but that would be my smallest problem if it would generally be possible with that package version...
DevTKSS commentedon Sep 20, 2025
not working with non-typed settings either:
DevTKSS/DevTKSS.MyManufacturerERP@e88f22d
[-][Auth] Add oAuth2 as official Authentication option?[/-][+][Auth][OAuth2] Add oAuth2 as official Authentication option?[/+]