Skip to content

Instantly share code, notes, and snippets.

@scriptam
Last active January 25, 2017 00:49
Show Gist options
  • Save scriptam/67398de600b5ce1dfde5f0ba4e52642a to your computer and use it in GitHub Desktop.
Save scriptam/67398de600b5ce1dfde5f0ba4e52642a to your computer and use it in GitHub Desktop.
Updated iOSClient ViewController to work with IdentityServer4 demo for IdentityModel.OidcClient.Samples
using System;
using System.Text;
using IdentityModel.OidcClient;
using UIKit;
using Foundation;
using System.Net.Http;
using Newtonsoft.Json.Linq;
namespace iOSClient
{
public partial class ViewController : UIViewController
{
SafariServices.SFSafariViewController safari;
OidcClient _client;
AuthorizeState _state;
HttpClient _apiClient;
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
CallApiButton.Enabled = false;
LoginButton.TouchUpInside += LoginButton_TouchUpInside;
CallApiButton.TouchUpInside += CallApiButton_TouchUpInside;
}
async void LoginButton_TouchUpInside (object sender, EventArgs e)
{
var authority = "https://demo.identityserver.io";
var options = new OidcClientOptions (
authority,
"native.hybrid",
"secret",
"openid profile email api",
"io.identitymodel.native://callback");
_client = new OidcClient (options);
_state = await _client.PrepareLoginAsync ();
AppDelegate.CallbackHandler = HandleCallback;
safari = new SafariServices.SFSafariViewController (new NSUrl (_state.StartUrl));
this.PresentViewController (safari, true, null);
}
async void CallApiButton_TouchUpInside (object sender, EventArgs e)
{
if (_apiClient == null) {
return;
}
var result = await _apiClient.GetAsync ("identity");
var content = await result.Content.ReadAsStringAsync ();
if (!result.IsSuccessStatusCode) {
OutputTextView.Text = result.ReasonPhrase + "\n\n" + content;
return;
}
OutputTextView.Text = JArray.Parse (content).ToString ();
}
async void HandleCallback (string url)
{
await safari.DismissViewControllerAsync (true);
var result = await _client.ValidateResponseAsync (url, _state);
var sb = new StringBuilder (128);
foreach (var claim in result.Claims) {
sb.AppendFormat ("{0}: {1}\n", claim.Type, claim.Value);
}
sb.AppendFormat ("\n{0}: {1}\n", "refresh token", result.RefreshToken);
sb.AppendFormat ("\n{0}: {1}\n", "access token", result.AccessToken);
OutputTextView.Text = sb.ToString ();
_apiClient = new HttpClient ();
_apiClient.SetBearerToken (result.AccessToken);
_apiClient.BaseAddress = new Uri ("https://api.identityserver.io");
CallApiButton.Enabled = true;
}
public override void DidReceiveMemoryWarning ()
{
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment