Skip to main content
 首页 » 编程设计

C#之Xamarin.iOs之添加随机数到 xamarin.auth 请求

2024年01月22日47youxin

我找不到将随机数添加到我的 Xamarin.Auth 请求以连接到我的 okta 登录名的方法。我是 xamarin 和 nugets 包的新手,我不知道如何修改 1.3.0 版 OAuth2Authenticator 的实现。

我正在尝试将请求参数用作:

auth.RequestParameters.Add("nonce", Guid.NewGuid().ToString("N"));

但我一直在运行来自 okta 的 nonce 无效错误。

如果你们中有人知道如何修复它。

这里是完整的请求:

   //start login flow seting our openId flow 
    public void StartFlow(string responseType, string scope) 
    { 
 
        //webViewLogin.Hidden = false; 
        var auth = new OAuth2Authenticator( 
            clientId: OAuthClientId, 
            scope: scope, 
            authorizeUrl: new Uri(oktaTenantUrl), 
            redirectUrl: new Uri(OAuthRedirectUrl) 
            ); 
        auth.RequestParameters.Add("nonce", Guid.NewGuid().ToString("N")); 
        auth.Completed += (sender, eventArgs) => 
        { 
            DismissViewController(true, null); 
            if (eventArgs.IsAuthenticated) 
            { 
                    // Use eventArgs.Account to do wonderful things 
                } 
        }; 
        PresentViewController(auth.GetUI(), true, null); 
    } 

请您参考如下方法:

有一种更简单的方法可以实现这一点。这似乎是一个错误/没有很好记录的过程。这issue解释要做什么:

You could probably override OnCreatingInitialUrl: https://github.com/xamarin/Xamarin.Auth/blob/ad7f6d6453506ced0ab3af499a7492f13973e3a3/source/Xamarin.Auth.LinkSource/OAuth2Authenticator.cs#L322

The RequestParameters property doesn't look to be used from what I can see, or at least not in that version.

因此解决方案是创建另一个继承 OAuth2Authenticator 的类并覆盖 OnCreatingInitialUrl:

using System; 
using System.Collections.Generic; 
using Xamarin.Auth; 
 
namespace Alerte.Health.App.Droid.Classes 
{ 
    public class MyOAuth2Authenticator : OAuth2Authenticator 
    { 
        public MyOAuth2Authenticator(string clientId, string scope, Uri authorizeUrl, Uri redirectUrl, GetUsernameAsyncFunc getUsernameAsync = null, bool isUsingNativeUI = false) : base(clientId, scope, authorizeUrl, redirectUrl, getUsernameAsync, isUsingNativeUI) 
        { 
        } 
 
        public MyOAuth2Authenticator(string clientId, string clientSecret, string scope, Uri authorizeUrl, Uri redirectUrl, Uri accessTokenUrl, GetUsernameAsyncFunc getUsernameAsync = null, bool isUsingNativeUI = false) : base(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, getUsernameAsync, isUsingNativeUI) 
        { 
        } 
 
        protected override void OnCreatingInitialUrl(IDictionary<string, string> query) 
        { 
            query.Add("nonce",Guid.NewGuid().ToString("N")); 
        } 
    } 
} 

然后用这个代替OAuth2Authenticator,继续正常流程:

var auth = new MyOAuth2Authenticator( 
    clientId, 
    scope, 
    new Uri(authorizeUrl), 
    new Uri(redirectUrl)); 

等等等等