在Xamarin Forms App中实施Salesforce身份验证(OAuth)

本文介绍了是否有人希望将移动应用程序与Salesforce App集成,并要求使用Salesforce OAuth对应用程序进行身份验证

qhzy1 回答:在Xamarin Forms App中实施Salesforce身份验证(OAuth)

iOS实现-

第1步:要实现深度链接,请根据连接的应用在info.plist中定义URL方案:回调URL Defining URL Schemes

第2步-在AppDelegate中实现“ OpenUrl”方法以在您的应用中接收深层链接调用

public override bool OpenUrl(UIApplication app,NSUrl url,NSDictionary options)
    {
        var deepLinkURL = url;
        url = null;
        App myApp = App.Current as myApp.App;
        if (myApp != null && deepLinkURL != null)
        {
            LandingPage.DeepLinkURL = deepLinkURL;
        }

        return true;
    }

第3步,现在您必须检查用户是第一次来还是已经通过身份验证:

public async static Task HandleDeepLink()
    {
        //await SecureStorage.SetAsync(AppConstant.userId,"");
        /* Deep Link 
         * Check if user is same 
         * user is already loggedIn
         * Token expired
         */
        try
        {
            string data = DeepLinkURL.ToString();
            if (data.Contains("userId"))
            {
                // extract and save all the parameters
                userId = HttpUtility.ParseQueryString(DeepLinkURL.Query).Get("userId");

                // if user not authenticated OR if different user
                isSameAsLastUser = await oAuth.ValidateUser(userId);
                if (isSameAsLastUser)
                {
                    // is already logged in
                    var isUserLoggedIn = await oAuth.IsUserLoggedIn();
                    if (isUserLoggedIn)
                    {
                        // navigate to scan
                        await SecureStorage.SetAsync(AppConstant.uniqueId,uniqueId);
                        Application.Current.MainPage = new NavigationPage(new MainPage());
                    }
                    else
                    {
                        Application.Current.MainPage = new NavigationPage(new Authentication());
                    }
                }
                else
                {
                    // clear previous values in secure storage
                    AppConfig.SaveSFParameters("false");
                    Application.Current.MainPage = new NavigationPage(new Authentication());
                }
            }
            // Handle oAuth
            //Extract the Code
            else if (data.Contains("code"))
            {
                var code = HttpUtility.ParseQueryString(DeepLinkURL.Query).Get("code");
                /*Exchange the code for an access token
                 * Save token 
                 * LoggedInTrue
                 */
                if (CrossConnectivity.Current.IsConnected)
                {
                    var authInfo = await oAuth.GetAccessToken(code);
                    Console.WriteLine("auth token - " + authInfo.AccessToken);
                    oAuth.SaveAuthInfo(authInfo);
                    // save user info | set user logged in to true 
                    AppConfig.SaveSFParameters(userId,"true");
                    // retrieve all the parameters and pass here
                    Application.Current.MainPage = new NavigationPage(new MainPage(userId));
                }
                else
                {
                    Device.BeginInvokeOnMainThread(async () =>
                    {
                        await Application.Current.MainPage.DisplayAlert(AppConstant.Alert,Resource.Resources.AlertMissingConnectivity,AppConstant.Ok);
                    });
                }
            }
            else if (data.Contains("error"))
            {
                var error = HttpUtility.ParseQueryString(DeepLinkURL.Query).Get("error");

                //TODO: where the user should be redirected in case of OAuth error
            }
        }
        catch(Exception ex)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                Application.Current.MainPage.DisplayAlert("Alert","There is some error while redirecting user to scan app,Please contact administrator","Ok");
            });
        }
    }
}

public partial class Authentication : ContentPage
{

    protected override void OnAppearing()
    {
        base.OnAppearing();

        if (CrossConnectivity.Current.IsConnected)
        {
            var authUrl = Common.FormatAuthUrl(AppConfiguration.authEndPointURL,ResponseTypes.Code,AppConfiguration.clientId,HttpUtility.UrlEncode(AppConfiguration.redirectUri));

            Browser.OpenAsync(new Uri(authUrl),BrowserLaunchMode.SystemPreferred);
        }
}
}

步骤4-成功验证用户身份后,salesforce将返回授权码

第5步,现在您必须进行Salesforce API调用,以通过提供授权码来检索访问令牌

步骤6-收到访问令牌后,保存访问令牌,请使用“ Xamarin SecureStorage”在应用中刷新令牌

async public static void SaveAuthInfo(AuthToken authInfo)
    {
        try
        {
            await SecureStorage.SetAsync("oauth_token",authInfo.AccessToken);
            await SecureStorage.SetAsync("oauth_Id",authInfo.Id);
            await SecureStorage.SetAsync("oauth_InstanceUrl",authInfo.InstanceUrl);
            await SecureStorage.SetAsync("oauth_RefreshToken",authInfo.RefreshToken);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            // Possible that device doesn't support secure storage on device.
        }
    }

第7步-现在将用户重定向到登录页面

本文链接:https://www.f2er.com/3162344.html

大家都在问