I have been trying to authenticate via Google OAuth 2.0. Following this link.
Have been able to open the Google Auth page and login successfully.
The problem is after logging in i am redirected to the google search page.
If i close the application then in the OnAuthCompleted method of the OAuth2Authenticator i get the e.IsAuthenticated to false and not able to get any information of the user.
Xamarin Share Library code:
var authenticator = new OAuth2Authenticator(
"somekey-somekey1.apps.googleusercontent.com",
null,
"email",
new Uri("https://accounts.google.com/o/oauth2/v2/auth"),
new Uri("com.companyname.somenameofapp:/oauth2redirect"),
new Uri("https://www.googleapis.com/oauth2/v4/"),
null,
true);
var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(authenticator);
authenticator.Completed += OnAuthCompleted;
AuthenticationState.Authenticator = authenticator;
AuthenticationState Class
public class AuthenticationState
{
public static OAuth2Authenticator Authenticator;
}
The OnAuthCompleted method
private async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
if (e.IsAuthenticated)
{
await Navigation.PushAsync(new GoogleLoginSuccess());
}
}
Main Activity Code
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, savedInstanceState);
LoadApplication(new App());
}
CustomUrlSchemeInterceptorActivity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace XamAppGoogleAuth.Droid
{
[Activity(Label = "CustomUrlSchemeInterceptorActivity")]
[IntentFilter(
new[] { Intent.ActionView },
Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
DataSchemes = new[] { "com.companyname.somenameofapp" },
DataPath = ":/oauth2redirect",
DataHost = "com.companyname.somenameofapp")]
public class CustomUrlSchemeInterceptorActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
global::Android.Net.Uri uri_android = Intent.Data;
Uri uri_netfx = new Uri(uri_android.ToString());
// load redirect_url Page
AuthenticationState.Authenticator.OnPageLoading(uri_netfx);
var intent = new Intent(this, typeof(MainActivity));
intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
StartActivity(intent);
this.Finish();
return;
}
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.somenameofapp">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="27" />
<application android:label="somenameofapp.Android"></application>
<activity android:name="somenameofapp.Android.MainActivity" android:label="MainActivity">
<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="com.companyname.somenameofapp" android:host="com.companyname.somenameofapp" />
</intent-filter>
</activity>
</manifest>
When i close the Custom Tab explicitly i am navigated back to the application with the below toast message.
What i would want is after the user authenticates with Google OAuth, they are redirected back to the application and I can get the access token and other information as needed. I have been to a lot of links regarding this but havent been able to find a solution. Kindly help
#kinder-cappy
I noticed you have the URL scheme interceptor activity in your application manifest as well as an activity class. You will have to choose one or else you will have multiple intent on trigger.
To remove the "customtabs login screen ...." message add this to your MainActivity (not interceptor class) after Xamarin.Auth initialization:
global::Xamarin.Auth.CustomTabsConfiguration.CustomTabsClosingMessage = null;
Also use Xamarin.Auth version 1.5.0.3 for now in android. It works.
If the current redirect URL scheme you specified does not works, try to get the correct redirect URL from your provider documentations. In my case, I used Google so I am using the inverted URL (client id).
If the current redirect URL scheme you specified does not work, try to get the correct redirect URL from your provider documentation. In my case, I used Google so I am using the inverted URL (client id).
In your CustomUrlSchemeInterceptorActivity DataSchemes and in Redirect URI you need to put inverted URL (ie. client ID) which you can get from the developer console.
client-id : "somekey-somekey1.apps.googleusercontent.com"
Redirect URI looks like : com.googleusercontent.apps.somekey-somekey1:/oauth2redirect
DataSchemes = new[] { "com.googleusercontent.apps.somekey-somekey1" } at your CustomUrlSchemeInterceptorActivity
Related
I'm aware this question has been asked already - but none provided a resolution.
I have read these links:
Xamarin Forum, Stack Overflow Q and some others.
I have a relatively simple project at the moment and I keep getting the error "The name 'Resource' does not exist in the current context"
I can restart the project & it will work and "resource" is underlined in red and I can still debug the project.
Then after a few tries it goes and complains that it's not in the current context.
I did not make any changes to the project - I have come back to it now from a while ago.
So I'm going to guess that updates to VS 2015 have broken it.
My Code example:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Views.InputMethods;
using Android.Graphics.Drawables;
using Android.Graphics;
namespace Designer
{
[Activity(Label = "Designer", MainLauncher = true)]
public class MainActivity : Activity
{
// Global Varialble
Button butSignIn;
EditText tbxUsername;
TextView txtErrorMsg;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
butSignIn = FindViewById<Button>(Resource.Id.butSignIn);
butSignIn.Click += ButSignIn_Click;
tbxUsername = FindViewById<EditText>(Resource.Id.txtUsername);
txtErrorMsg = FindViewById<TextView>(Resource.Id.txtErrorMessage);
ActionBar.SetDisplayShowTitleEnabled(false);
ColorDrawable colorDrawable = new ColorDrawable(Color.ParseColor("#ff70bc1e"));
ActionBar.SetBackgroundDrawable(colorDrawable);
}
private void ButSignIn_Click(object sender, System.EventArgs e)
{
if (tbxUsername.Text == "Azmodan")
{
Intent intent = new Intent(this, typeof(MenuActivity));
this.StartActivity(intent);
this.Finish(); // this will close the activity and will close app if we try go back
}
else
{
txtErrorMsg.Visibility = ViewStates.Visible;
txtErrorMsg.Text = "inccorect login details, please try again";
}
}
}
}
Any help would be appreciated.
I am using Xamarin.Auth for login with facebook in my app(android/iOS) and all is going well but when successfully loged in, facebook profile is opening and not going back to my application. i want to redirect to my app's home page without showing facebook profile. i am following this tutorial and not get any success. i think i am not giving proper Urls of my app. Please give me suggestions.
your help will be appreciated thanks in advance.
here is my code of loginPageRenderer:
[assembly: ExportRenderer (typeof (FBLoginPage), typeof (LoginPageRendrerr))]
namespace FFirst_app.Droid
{
public class LoginPageRendrerr : PageRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged(e);
// this is a ViewGroup - so should be able to load an AXML file and FindView<>
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator (
clientId: "7b745e26dbb64e1a3a3bf6bfd33165bc", // your OAuth2 client id
scope: "basic", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri("https://apps.facebook.com/myappppppp"),//("https://api.instagram.com/oauth/authorize/"), // the auth URL for the service
redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html")); // the redirect URL for the service
auth.Completed += (sender, eventArgs) => {
if (eventArgs.IsAuthenticated)
{
App.SuccessfulLoginAction.Invoke();
// Use eventArgs.Account to do wonderful things
App.SaveToken(eventArgs.Account.Properties["access_token"]);
string sessionToken = App.Token; // /* Authenticate the user with Facebook and fetch a session token */;
DateTime expiration = DateTime.Today; ///* The expiration time for the session token */;
string facebookId = Constants.FBAppId;
ParseFacebookUtils.LogInAsync (facebookId, sessionToken, expiration);
} else {
// The user cancelled
}
};
activity.StartActivity (auth.GetUI(activity));
}
}
}
I have found answer that i was wrong with URL's and now its working after when i changed 'authorizeUrl:' to "http://www.facebook.com/connect/login_success.html" and this URl also set on FB App as it is.So now my code is working properly.
On the Xamarin.Auth Getting Started page, it is mentioned that it is up to you to dismiss the UI on iOS:
auth.Completed += (sender, eventArgs) => {
// We presented the UI, so it's up to us to dimiss it on iOS.
**> DismissViewController (true, null); <**
if (eventArgs.IsAuthenticated) {
// Use eventArgs.Account to do wonderful things
} else {
// The user cancelled
}
};
I am trying to connect the in-app-billing but the OnConnected event not being hit.
my Android Manifest code is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="alphaTestApp.alphaTestApp" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="21" />
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="alphaTestApp" android:icon="#drawable/Icon"></application>
</manifest>
And the Main Activity file code is.
[Activity(Label = "alphaTestApp", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
private InAppBillingServiceConnection _serviceConnection;
string publicKey = "REDACTED";
private IList<Product> _products;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_serviceConnection = new InAppBillingServiceConnection(this, publicKey);
if (_serviceConnection == null)
{
Toast t = Toast.MakeText(this, "Error while connecting", ToastLength.Long);
t.Show();
}
_serviceConnection.Connect();
Toast t1 = Toast.MakeText(this, "Connected app", ToastLength.Long);
t1.Show();
_serviceConnection.OnConnected += () =>
{
Toast t2 = Toast.MakeText(this, "Retrieving Items", ToastLength.Long);
t2.Show();
_products = _serviceConnection.BillingHandler.QueryInventoryAsync(new List<string> {
"goldcoin100"
}, ItemType.Product) as IList<Product>;
if (_products == null)
return;
_serviceConnection.BillingHandler.BuyProduct(_products[0]);
};
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate
{
Toast t3 = Toast.MakeText(this, "Retrieving Items", ToastLength.Long);
t3.Show();
_products = _serviceConnection.BillingHandler.QueryInventoryAsync(new List<string> {
"goldcoin100"
}, ItemType.Product) as IList<Product>;
if (_products == null)
return;
_serviceConnection.BillingHandler.BuyProduct(_products[0]);
};
}
}
It's probably not the reason, but it would be best to set your OnConnected handler before you call Connect just in case it connects in less time than it takes for the Toast code to run.
Also, you should make the OnConnected handler async and then await on the call to QueryInventoryAsync (in a Lambda the async keyword goes before the brackets, e.g. OnConnected += async () => ...). As it is, QueryInventoryAsync will return a Task<IList<Product>> so trying to convert it using as IList<Product> will fail and _products will always be null.
If you're running on an emulator, make sure that you've got Google Play Services installed and up-to-date. There's an article on doing this for the Xamarin Android Player here: Installing Google Play Services in XAP. Although note that BuyProduct shouldn't work on an emulator using real products, you'll need to use the test product IDs (e.g. ReservedTestProductIDs.Purchased, and note that once you've purchased this one you'll need to call ConsumePurchase on it before you can purchase it again).
Also, don't post your API key on an open forum.
I would like my app to have only one view.
I need this view to be an external URL.
I tried to use the webBrowser Task following the example on microsoft.
I put on my constractor :
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://msdn.microsoft.com", UriKind.Absolute);
webBrowserTask.Show();
However when i press the back button instead of navigating outside the app , i am navigating to the first page which is empty...
My code looks like this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
//added this for push
using Microsoft.Phone.Notification;
using System.Text;
//added this to open an external URL using the WebBrowser Task
using Microsoft.Phone.Tasks;
namespace WindowsPush
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
// The name of our push channel.
string channelName = "ToastSampleChannel";
InitializeComponent();
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
//pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast events.
pushChannel.BindToShellToast();
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
//pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
// MessageBox.Show(String.Format("Channel Uri is {0}", pushChannel.ChannelUri.ToString()));
}
object uniqueID;
if (Microsoft.Phone.Info.DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueID) == true)
{
byte[] bID = (byte[])uniqueID;
string deviceID = Convert.ToBase64String(bID); // There you go
System.Diagnostics.Debug.WriteLine("Device Unique Id is: {0}", deviceID);
}
//opening the external URL using webBrowserTask
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://msdn.microsoft.com", UriKind.Absolute);
webBrowserTask.Show();
}
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));
});
}
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
// Error handling logic for your particular application would be here.
Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));
}
}
}
What i need is just load an external URL on the first and only view of my app.
How could i do that?
You're looking for the WebBrowser control. Add it to the main application page and handle it like you would a WebBrowserTask.
If you're going to use the WebBrowserTask then you could close the app on returning to it by throwing an unhandled exception:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.Back)
{
throw new Exception("deliberately doing this to force the app to close");
}
}
If/when you do this in Windows Phone 8 you can call Application.Current.Terminate(); instead of throwing the exception.
Be sure to check the marketplace certification requirements for apps that just launch an external website before submitting though.
I'm experimenting with "configuration-less WIF", where I want to accept a SAML2 token that is generated by Windows Azure's AppFabric STS.
What I'm doing is parsing checking the current request for token information, like so:
if (Request.Form.Get(WSFederationConstants.Parameters.Result) != null)
{
SignInResponseMessage message =
WSFederationMessage.CreateFromFormPost(System.Web.HttpContext.Current.Request) as SignInResponseMessage;
var securityTokenHandlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
XmlTextReader xmlReader = new XmlTextReader(
new StringReader(message.Result));
SecurityToken token = securityTokenHandlers.ReadToken(xmlReader);
if (token != null)
{
ClaimsIdentityCollection claims = securityTokenHandlers.ValidateToken(token);
IPrincipal principal = new ClaimsPrincipal(claims);
}
}
The code above uses the SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); colection to verify and handle the SAML token. However: this does not work because obviously the application has not bee nconfigured correctly. How would I specify the follwing configuration from XML programmaticaly on my securityTokenHandlers collection?
<microsoft.identityModel>
<service>
<audienceUris>
<add value="http://www.someapp.net/" />
</audienceUris>
<federatedAuthentication>
<wsFederation passiveRedirectEnabled="true" issuer="https://rd-test.accesscontrol.appfabriclabs.com/v2/wsfederation" realm="http://www.thisapp.net" requireHttps="false" />
<cookieHandler requireSsl="false" />
</federatedAuthentication>
<applicationService>
<claimTypeRequired>
<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" optional="true" />
<claimType type="http://schemas.microsoft.com/ws/2008/06/identity/claims/role" optional="true" />
</claimTypeRequired>
</applicationService>
<issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<trustedIssuers>
<add thumbprint="XYZ123" name="https://somenamespace.accesscontrol.appfabriclabs.com/" />
</trustedIssuers>
</issuerNameRegistry>
</service>
I was struggling with the same and found a working solution in WIF 3.5/4.0. Since maartenba's link seems to be dead, I wanted to post my solution here.
Our requirements were:
Configuration fully in code (as we ship a default web.config with the app)
Maximum allowed .Net version 4.0 (hence I am using WIF 3.5/4.0)
What I used to arrive at the solution:
Information about dynamic WIF configuration provided by Daniel Wu
here.
This
method
to register HTTP modules at runtime, explained by David Ebbo. I
also tried the more elegant method explained by Rick
Strahl,
but that unfortunately did not do the trick for me.
Edit 2016/09/02: instead of adding a separate "pre application start
code" class as in David Ebbo's example, the WIF-related HTTP modules
can also be registered in the static constructor of the
`HttpApplication' class. I have adapted the code to this somewhat
cleaner solution.
My solution needs nothing in web.config. The bulk of the code is in global.asax.cs. Configuration is hard-coded in this sample:
using System;
using System.IdentityModel.Selectors;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Web;
namespace TestADFS
{
public class SessionAuthenticationModule : Microsoft.IdentityModel.Web.SessionAuthenticationModule
{
protected override void InitializePropertiesFromConfiguration(string serviceName)
{
}
}
public class WSFederationAuthenticationModule : Microsoft.IdentityModel.Web.WSFederationAuthenticationModule
{
protected override void InitializePropertiesFromConfiguration(string serviceName)
{
ServiceConfiguration = FederatedAuthentication.ServiceConfiguration;
PassiveRedirectEnabled = true;
RequireHttps = true;
Issuer = "https://nl-joinadfstest.joinadfstest.local/adfs/ls/";
Realm = "https://67px95j.decos.com/testadfs";
}
}
public class Global : HttpApplication
{
static Global()
{
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(SessionAuthenticationModule));
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(WSFederationAuthenticationModule));
}
protected void Application_Start(object sender, EventArgs e)
{
FederatedAuthentication.ServiceConfigurationCreated += FederatedAuthentication_ServiceConfigurationCreated;
}
internal void FederatedAuthentication_ServiceConfigurationCreated(object sender, Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs e)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection coll = store.Certificates.Find(X509FindType.FindByThumbprint, "245537E9BB2C086D3C880982FA86267FBD66B9A3", false);
if (coll.Count > 0)
e.ServiceConfiguration.ServiceCertificate = coll[0];
store.Close();
AudienceRestriction ar = new AudienceRestriction(AudienceUriMode.Always);
ar.AllowedAudienceUris.Add(new Uri("https://67px95j.decos.com/testadfs"));
e.ServiceConfiguration.AudienceRestriction = ar;
ConfigurationBasedIssuerNameRegistry inr = new ConfigurationBasedIssuerNameRegistry();
inr.AddTrustedIssuer("6C9B96D90257B65B6F181C2478D869473DC359EA", "http://NL-JOINADFSTEST.joinadfstest.local/adfs/services/trust");
e.ServiceConfiguration.IssuerNameRegistry = inr;
e.ServiceConfiguration.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
FederatedAuthentication.WSFederationAuthenticationModule.ServiceConfiguration = FederatedAuthentication.ServiceConfiguration;
}
}
}
Usage
My app is asp.net WebForms, running in classic pipeline mode and supports forms authentication as well as ADFS login. Because of that, authentication is handled in a common base class shared by all .aspx pages:
protected override void OnInit(EventArgs e)
{
if (NeedsAuthentication && !User.Identity.IsAuthenticated)
{
SignInRequestMessage sirm = new SignInRequestMessage(
new Uri("https://nl-joinadfstest.joinadfstest.local/adfs/ls/"),
ApplicationRootUrl)
{
Context = ApplicationRootUrl,
HomeRealm = ApplicationRootUrl
};
Response.Redirect(sirm.WriteQueryString());
}
base.OnInit(e);
}
In this code, ApplicationRootUrl is the application path ending in "/" (the "/" is important in Classic pipeline mode).
As a stable implementation for logout in mixed mode was not so easy, I want to show the code for that as well. Technically it works, but I still have an issue with IE immediately logging in again after logging out an ADFS account:
if (User.Identity.IsAuthenticated)
{
if (User.Identity.AuthenticationType == "Forms")
{
FormsAuthentication.SignOut();
Session.Clear();
Session.Abandon();
ResetCookie(FormsAuthentication.FormsCookieName);
ResetCookie("ASP.NET_SessionId");
Response.Redirect(ApplicationRootUrl + "Default.aspx");
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
else
{
FederatedAuthentication.SessionAuthenticationModule.SignOut();
FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie();
Uri uri = new Uri(ApplicationRootUrl + "Default.aspx");
WSFederationAuthenticationModule.FederatedSignOut(
new Uri("https://nl-joinadfstest.joinadfstest.local/adfs/ls/"),
uri); // 1st url is single logout service binding from adfs metadata
}
}
(ResetCookie is a helper function that clears a response cookie and sets its expiration in the past)
Just a thought, no idea whether this works: Isn't there a way to get at the actual XML (which is empty in your case) and modify it at runtime through the classes in Microsoft.IdentityModel.Configuration?
Alternatively, some of the things in the XML you can modify at the time the sign-in request is sent out, in the RedirectingToIdentityProvider event by modifying the SignInRequestMessage
FYI: found a solution and implemented it in a module described (and linked) here: http://blog.maartenballiauw.be/post/2011/02/14/Authenticate-Orchard-users-with-AppFabric-Access-Control-Service.aspx