Every API needs authentication, yet no developer wants to deal with authentication. Simple Auth embeds authentication into the API so you dont need to deal with it. Most importantly it works great with traditional Xamarin and Xamarin.Forms
- Azure Active Directory
- Amazon
- Dropbox
- Github
- Linked In
- Microsoft Live Connect
Simple auth ships with some built in providers so you just need to add your keys and scopes.
varscopes=new[]{"https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"};varapi=newGoogleApi("google","clientid","clientsecret"){Scopes=scopes,};varaccount=awaitapi.Authenticate();Restful Api Requests couldnt be simpler
varsong=awaitapi.Get<Song>("http://myapi/Song/",songId);Paramaters can be added as part of the path
vartodoItem=awaitapi.Get<TodoItem>("http://myapi/user/{UserId}/TodoItem",newDictionary<string,string>{["UserId"]="1",["itemID"]="22"});Generates the following Url:
http://myapi/user/1/TodoItem?itemID=22[Path("/pet")][ContentType("application/json")][Accepts("application/json")]publicvirtualTaskAddPet(Petbody){returnPost(body);}One password support is for iOS Only.
Simply add the project or the Nuget
Clancey.SimpleAuth.OnePassword
Then call the following line in your iOS project prior to calling api.Authenticate();
SimpleAuth.OnePassword.Activate();You can use the Twitter app to authenticate with SimpleAuth on iOS.
Add the following to your Info.Plist
// Info.plist
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>twitterkit-<consumerKey></string>
</array>
</dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>twitter</string>
<string>twitterauth</string>
</array>
Then call the following line in your iOS AppDelegate FinishedLaunching method;
SimpleAuth.Providers.Twitter.Init();Also add the following override in your AppDelegate
publicoverrideboolOpenUrl(UIApplicationapp,NSUrlurl,NSDictionaryoptions){if(SimpleAuth.Native.OpenUrl(app,url,options))returntrue;returnbase.OpenUrl(app,url,options);}Simply add the project or the Nuget
Clancey.SimpleAuth.Facebook.iOS
The Facebook SDK requires you modify your info.plist : https://components.xamarin.com/gettingstarted/facebookios
Then call the following line in your iOS AppDelegate FinishedLaunching method;
SimpleAuth.Providers.Facebook.Init(app,options);Also add the following override in your AppDelegate
publicoverrideboolOpenUrl(UIApplicationapp,NSUrlurl,NSDictionaryoptions){if(SimpleAuth.Native.OpenUrl(app,url,options))returntrue;returnbase.OpenUrl(app,url,options);}The Google SDK can do Cross-Client Login. This allows you to get tokens for the server, with one login.
To use Cross-client you need to set the ServerClientId on the GoogleApi.
Call the following in your FinishedLaunching Method;
SimpleAuth.Providers.Google.Init()Also add the following to your AppDelegate
publicoverrideboolOpenUrl(UIApplicationapp,NSUrlurl,NSDictionaryoptions){if(SimpleAuth.Native.OpenUrl(app,url,options))returntrue;returnbase.OpenUrl(app,url,options);}If you need Cross-client authentication
varapi=newGoogleApi("google","client_id"){ServerClientId="server_client_id""
};varaccount=awaitapi.Authenticate();varserverToken=account.UserData["ServerToken"];System.Exception: Error Domain=com.google.GIDSignIn Code=-2 "keychain error" UserInfo={NSLocalizedDescription=keychain error}
Under the iOS Build Signing, Custom Entitlements: make sure an entitlement.plist is set
SFSafariViewController Allows users to use Safari to login, instead of embedded webviews.
Google now requires this mode and is enabled by default for Google Authentication on iOS/MacOS.
To use the Native Safari Authenticator, you are required to add the following snippet in your AppDelegate (iOS Only)
publicoverrideboolOpenUrl(UIApplicationapp,NSUrlurl,NSDictionaryoptions){if(SimpleAuth.Native.OpenUrl(app,url,options))returntrue;returnbase.OpenUrl(app,url,options);}You are also required to add the following to add a CFBundleURLSchemes to your info.plist
For Google: com.googleusercontent.apps.YOUR_CLIENT_ID
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.YOURCLIENTID</string>
</array>
<key>CFBundleURLName</key>
<string>googleLogin</string>
</dict>
</array>
Simple Auth supports the native Google Sign-in for Android.
Add the nuget Clancey.SimpleAuth.Google.Droid
Create OAuth Client Id (Web Application): Link
Create and OAuth Android app: Link
- Sign your app using the same Keystore
Use both the Web Application ClientID. ClientSecret is not required but reccomended.
Add the following code to your Main Activity
protectedoverridevoidOnCreate(Bundlebundle){base.OnCreate(bundle);SimpleAuth.Providers.Google.Init(this.Application);//The rest of your initialize code}protectedoverridevoidOnActivityResult(intrequestCode,ResultresultCode,Intentdata){base.OnActivityResult(requestCode,resultCode,data);SimpleAuth.Native.OnActivityResult(requestCode,resultCode,data);}
If you need Cross-Client authentication pass your ServerClientId into the google api
varapi=newGoogleApi("google","client_id"){ServerClientId="server_client_id""
};varaccount=awaitapi.Authenticate();varserverToken=account.UserData["ServerToken"];If you get:
Unable to find explicit activity class {com.google.android.gms.auth.api.signin.internal.SignInHubActivity}; have you declared this activity in your AndroidManifest.xml?
Add the following to your AndroidManifest.xml
<activity android:name="com.google.android.gms.auth.api.signin.internal.SignInHubActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
</application>
- Check your app is signed with the same KeyStore noted in for your android app Link
- Regenerate new OAuth 2 Client id, create the WebApplication kind.
Simple Auth supports the native Facebook SDK for Android.
Add the nuget Clancey.SimpleAuth.Facebook.Droid
Create an Android App: Link
Add the following to your String.xml in Resources/values. If your appId was 1066763793431980
<string name="facebook_app_id">1066763793431980</string> <string name="fb_login_protocol_scheme">fb1066763793431980</string>Add a meta-data element to the application element:
[assembly: MetaData("com.facebook.sdk.ApplicationId", Value = "@string/facebook_app_id")]Add FacebookActivity to your AndroidManifest.xml:
<activity android:name="com.facebook.FacebookActivity" android:configChanges= "keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/app_name" /> <activity android:name="com.facebook.CustomTabActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="@string/fb_login_protocol_scheme" /> </intent-filter> </activity>Add the following code to your Main Activity
protectedoverridevoidOnCreate(Bundlebundle){base.OnCreate(bundle);SimpleAuth.Providers.Google.Init(this.Application);//The rest of your initialize code}protectedoverridevoidOnActivityResult(intrequestCode,ResultresultCode,Intentdata){base.OnActivityResult(requestCode,resultCode,data);Native.OnActivityResult(requestCode,resultCode,data);}
SimpleAuth supports using Custom Tabs for authorization.
Add the nuget Clancey.SimpleAuth.Droid.CustomTabs
In your Droid project, create a subclass of SimpleAuthCallbackActivity to handle your url scheme, replacing the value of DataScheme with the scheme you used for the redirectUrl parameter of the Api constructor
[Activity(NoHistory=true,LaunchMode=Android.Content.PM.LaunchMode.SingleTop)][IntentFilter(new[]{Intent.ActionView},Categories=new[]{Intent.CategoryDefault,Intent.CategoryBrowsable},DataScheme="YOUR CUSTOM SCHEME")]publicclassMyCallbackActivity:SimpleAuthCallbackActivity{}
You will need to implement an AuthStorage
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Linq;namespaceSimpleAuth{publicclassAuthStorage:IAuthStorage{privateconstintKeysize=128;privateconstintDerivationIterations=1000;publicstaticstringEncryptString(stringplainText,stringpassPhrase){varsaltStringBytes=Generate256BitsOfRandomEntropy();varivStringBytes=Generate256BitsOfRandomEntropy();varplainTextBytes=Encoding.UTF8.GetBytes(plainText);using(varpassword=newRfc2898DeriveBytes(passPhrase,saltStringBytes,DerivationIterations)){varkeyBytes=password.GetBytes(Keysize/8);using(varsymmetricKey=newRijndaelManaged()){symmetricKey.BlockSize=Keysize;symmetricKey.Mode=CipherMode.CBC;symmetricKey.Padding=PaddingMode.PKCS7;using(varencryptor=symmetricKey.CreateEncryptor(keyBytes,ivStringBytes)){using(varmemoryStream=newMemoryStream()){using(varcryptoStream=newCryptoStream(memoryStream,encryptor,CryptoStreamMode.Write)){cryptoStream.Write(plainTextBytes,0,plainTextBytes.Length);cryptoStream.FlushFinalBlock();// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.varcipherTextBytes=saltStringBytes;cipherTextBytes=cipherTextBytes.Concat(ivStringBytes).ToArray();cipherTextBytes=cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();memoryStream.Close();cryptoStream.Close();returnConvert.ToBase64String(cipherTextBytes);}}}}}}publicstaticstringDecryptString(stringcipherText,stringpassPhrase){varcipherTextBytesWithSaltAndIv=Convert.FromBase64String(cipherText);varsaltStringBytes=cipherTextBytesWithSaltAndIv.Take(Keysize/8).ToArray();varivStringBytes=cipherTextBytesWithSaltAndIv.Skip(Keysize/8).Take(Keysize/8).ToArray();varcipherTextBytes=cipherTextBytesWithSaltAndIv.Skip((Keysize/8)*2).Take(cipherTextBytesWithSaltAndIv.Length-((Keysize/8)*2)).ToArray();using(varpassword=newRfc2898DeriveBytes(passPhrase,saltStringBytes,DerivationIterations)){varkeyBytes=password.GetBytes(Keysize/8);using(varsymmetricKey=newRijndaelManaged()){symmetricKey.BlockSize=Keysize;symmetricKey.Mode=CipherMode.CBC;symmetricKey.Padding=PaddingMode.PKCS7;using(vardecryptor=symmetricKey.CreateDecryptor(keyBytes,ivStringBytes)){using(varmemoryStream=newMemoryStream(cipherTextBytes)){using(varcryptoStream=newCryptoStream(memoryStream,decryptor,CryptoStreamMode.Read)){varplainTextBytes=newbyte[cipherTextBytes.Length];vardecryptedByteCount=cryptoStream.Read(plainTextBytes,0,plainTextBytes.Length);memoryStream.Close();cryptoStream.Close();returnEncoding.UTF8.GetString(plainTextBytes,0,decryptedByteCount);}}}}}}privatestaticbyte[]Generate256BitsOfRandomEntropy(){varrandomBytes=newbyte[16];using(varrngCsp=newRNGCryptoServiceProvider()){rngCsp.GetBytes(randomBytes);}returnrandomBytes;}staticstringCalculateMD5Hash(stringinput){varmd5=MD5.Create();varinputBytes=Encoding.ASCII.GetBytes(input);varhash=md5.ComputeHash(inputBytes);varsb=newStringBuilder();for(inti=0;i<hash.Length;i++){sb.Append(hash[i].ToString("X2"));}returnsb.ToString();}publicvoidSetSecured(stringidentifier,stringvalue,stringclientId,stringclientSecret,stringsharedGroup){varkey=$"{clientId}-{identifier}-{clientId}-{sharedGroup}";varnewKey=CalculateMD5Hash(key);varencrypted=EncryptString(value,clientSecret);Plugin.Settings.CrossSettings.Current.AddOrUpdateValue(newKey,encrypted);}publicstringGetSecured(stringidentifier,stringclientId,stringclientSecret,stringsharedGroup){try{varkey=$"{clientId}-{identifier}-{clientId}-{sharedGroup}";varnewKey=CalculateMD5Hash(key);varcryptText=Plugin.Settings.CrossSettings.Current.GetValueOrDefault(newKey,"");returnDecryptString(cryptText,clientSecret);}catch(Exceptionex){//Console.WriteLine(ex);}returnnull;}}}For console apps, you will also need to implement the Authenticators:
Basic Auth
usingSystem;usingSystem.Security;usingSystem.Threading.Tasks;namespaceSimpleAuth{publicclassBasicAuthController{readonlyIBasicAuthenicatorauthenticator;publicBasicAuthController(IBasicAuthenicatorauthenticator){this.authenticator=authenticator;}publicasyncTask<Tuple<string,string>>GetCredentials(stringtitle,stringdetails=""){try{Console.WriteLine("******************");Console.WriteLine(title);Console.WriteLine(details);Console.WriteLine("******************");Console.WriteLine("Enter Username:");varusername=Console.ReadLine();Console.WriteLine("Enter Password:");varpassword=GetPassword();varresult=newTuple<string,string>(username,password);try{boolsuccess=false;varbasic=authenticator;if(basic!=null){success=awaitbasic.VerifyCredentials(result.Item1,result.Item2);}if(!success)thrownewException("Invalid Credentials");}catch(Exceptionex){result=awaitGetCredentials(title,$"Error: {ex.Message}");}returnresult;}catch(TaskCanceledException){authenticator.OnCancelled();returnnull;}}publicstringGetPassword(){varpwd="";while(true){ConsoleKeyInfoi=Console.ReadKey(true);if(i.Key==ConsoleKey.Enter){break;}elseif(i.Key==ConsoleKey.Backspace){if(pwd.Length>0){pwd.Remove(pwd.Length-1);Console.Write("\b\b");}}else{pwd+=(i.KeyChar);Console.Write("*");}}returnpwd;}}}Web Authenticator
usingSystem;usingSystem.Threading.Tasks;usingSystem.Diagnostics;usingSystem.Runtime.InteropServices;namespaceSimpleAuth{publicclassWebAuthenticatorController{readonlyWebAuthenticatorauthenticator;publicWebAuthenticatorController(WebAuthenticatorauthenticator){this.authenticator=authenticator;}publicasyncTaskGetCredentials(stringtitle,stringdetails=""){try{varurl=awaitauthenticator.GetInitialUrl();Console.WriteLine("******************");Console.WriteLine(title);Console.WriteLine(details);Console.WriteLine($"Launching Url: \"{url}\"");Console.WriteLine("******************");Console.WriteLine("Paste the Redirected URL Here:");OpenBrowser(url);varusername=Console.ReadLine();try{boolsuccess=false;varbasic=authenticator;if(basic!=null){success=basic.CheckUrl(newUri(username),null);}if(!success)thrownewException("Invalid Credentials");}catch(Exceptionex){awaitGetCredentials(title,$"Error: {ex.Message}");}}catch(TaskCanceledException){authenticator.OnCancelled();}}publicstaticvoidOpenBrowser(Uriuri){OpenBrowser(uri.AbsoluteUri);}publicstaticvoidOpenBrowser(stringurl){try{Process.Start(url);}catch{// hack because of this: https://github.com/dotnet/corefx/issues/10361if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)){url=url.Replace("&","^&");Process.Start(newProcessStartInfo("cmd",$"/c start {url}"){CreateNoWindow=true});}elseif(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)){Process.Start("xdg-open",url);}elseif(RuntimeInformation.IsOSPlatform(OSPlatform.OSX)){Process.Start("open",url);}else{throw;}}}}}