在Xamarin Forms应用程序中实现Salesforce身份验证(OAuth)



本文解释了如果有人想将移动应用程序与Salesforce应用程序集成,并要求使用Salesforce OAuth 对应用程序进行身份验证

iOS实现-

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

步骤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-一旦您收到访问toekn,然后保存访问令牌,使用"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-现在重定向用户到登录页

相关内容

  • 没有找到相关文章

最新更新