In the Azure B2C, I used to be able to get a "groups" claim in my JWT tokens by following Retrieving Azure AD Group information with JWT:
Open the old-school Azure manager (https://manage.windowsazure.com)
Register my application with B2C
Download the B2C manifest for the application
In the manifest, change the "groupMembershipClaims" entry to
"groupMembershipClaims": "SecurityGroup",
Upload the changed B2C manifest again
The problem
This has worked well in the past (about a month ago, I believe...) but it doesn't anymore. See below for details...
What I've tried sofar
Plan A: Use Azure Manager
Follow the known-good recipe above.
Unfortunately that doesn't work anymore - I get the following error when this client tries to authenticate me with B2C:
AADB2C90068: The provided application with ID '032fe196-e17d-4287-9cfd-25386d49c0d5' is not valid against this service. Please use an application created via the B2C portal and try again"
OK, fair enough - they're moving us to the new Portal.
Plan B: Use Azure Portal
Follow the good old recipe, using the new Portal.
But that doesn't work either - when I get to the "download manifest" part, I cannot find any way to access the manifest (and Googling tells me it's probably gone for good...).
Plan C: Mix Azure Portal and manager
Getting a little desperate, I tried mixing plans A and B: register the app using the new Portal, then change the manifest using the old Azure Manager.
But no luck - when I try to upload the manifest, it fails with the message
ParameterValidationException=Invalid parameters provided; BadRequestException=Updates to converged applications are not allowed in this version.
Plan Z: Use the Graph API to retrieve group membership data
Just give up the "group" claim - instead, whenever I need group info, just query the B2C server using the Graph API.
I really, really don't want to do this - it would ruin the self-contained-ness of the access token, and make the system very "chatty".
But I've included it as a plan Z here, just to say: yes, I know the option exists, no I haven't tried it - and I'd prefer not to.
The question:
How do I get the "group" claim in my JWT token these days?
Plan Z it is I'm afraid. I don't know why they don't return it, but it's currently marked as planned on their Feedback Portal (it's the highest rated item).
This is how I'm doing it. Querying the groups when the user is authenticated, you can do it your way as well - just query as and when you need to. Depends on your use case.
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseKentorOwinCookieSaver();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = new PathString("/account/unauthorised"),
CookieSecure = CookieSecureOption.Always,
ExpireTimeSpan = TimeSpan.FromMinutes(20),
SlidingExpiration = true,
CookieHttpOnly = true
});
// Configure OpenID Connect middleware for each policy
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(Globals.SignInPolicyId));
}
private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
{
return new OpenIdConnectAuthenticationOptions
{
// For each policy, give OWIN the policy-specific metadata address, and
// set the authentication type to the id of the policy
MetadataAddress = string.Format(Globals.AadInstance, Globals.TenantName, policy),
AuthenticationType = policy,
AuthenticationMode = AuthenticationMode.Active,
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = Globals.ClientIdForLogin,
RedirectUri = Globals.RedirectUri,
PostLogoutRedirectUri = Globals.RedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = AuthenticationFailed,
SecurityTokenValidated = SecurityTokenValidated
},
Scope = "openid",
ResponseType = "id_token",
// This piece is optional - it is used for displaying the user's name in the navigation bar.
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
}
};
}
private async Task SecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> token)
{
var groups = await _metaDataService.GetGroups(token.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value);
if (groups?.Value != null && groups.Value.Any())
{
foreach (IGroup group in groups.Value.ToList())
{
token.AuthenticationTicket.Identity.AddClaim(
new Claim(ClaimTypes.Role, group.DisplayName, ClaimValueTypes.String, "GRAPH"));
}
}
}
// Used for avoiding yellow-screen-of-death
private Task AuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
notification.HandleResponse();
if (notification.Exception.Message == "access_denied")
{
notification.Response.Redirect("/");
}
else
{
notification.Response.Redirect("/error?message=" + notification.Exception.Message);
}
return Task.FromResult(0);
}
}
My GetGroups method just queries the getMemberGroups method on the Users API
Then I have a simple helper method to determine whether the user is in a role:
public static bool UserIsInRole(IPrincipal user, string roleName)
{
var claims = user.Identity as ClaimsIdentity;
if (claims == null) return false;
return claims.FindAll(x => x.Type == ClaimTypes.Role).Any(x => x.Value == roleName);
}
Related
I have a requirement where I want to fetch the Authorization Code for Azure login for each request in web API. As of now once the user signs in to Azure, after that I am not getting the authorization code as the user is already signed in.
How can I force the user to sign in again? This is the code I have been using as of now in the owin_startup file in web API?
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieSecure = (CookieSecureOption)Convert.ToInt32(cookieSecure), // CookieSecureOption.NeverAlways
CookieManager = new SystemWebCookieManager(),
CookieHttpOnly = false,
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
RedirectUri = RedirectUri,
});
According to the code and the cases you post before, I think it it not about Azure ad b2c, so here I will give a reply for azure ad.
When you request an authorization code, there is a prompt=login property which is indicate the user should be prompted to reauthenticate.
Also here is an article about Forcing reauthentication with Azure AD which suggest use Token Max Age to achieve it.
You can append max_age= to the authorization URL (or just put 0 to force password authentication at all times). So once user gets redirected to the URL, they will be presented with an information to login again.
public class RequireReauthenticationAttribute : Attribute, IAsyncResourceFilter
{
private int _timeElapsedSinceLast;
public RequireReauthenticationAttribute(int timeElapsedSinceLast)
{
_timeElapsedSinceLast = timeElapsedSinceLast;
}
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
var foundAuthTime = int.TryParse(context.HttpContext.User.FindFirst(AppClaimTypes.AuthTime)?.Value, out int authTime);
if (foundAuthTime && DateTime.UtcNow.ToUnixTimestamp() - authTime < _timeElapsedSinceLast)
{
await next();
}
else
{
var state = new Dictionary<string, string> { { "reauthenticate", "true" } };
await context.HttpContext.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties(state)
{
RedirectUri = context.HttpContext.Request.Path
}, ChallengeBehavior.Unauthorized);
}
}
}
It appears that the reason you wish to re-authenticate the user is to get/refresh the token in memory even when the auth cookie is present. Simplest way to achieve this would be decorate your controller with the AuthorizeForScopes attribute. You can check the sample project on Github here
I have a default ASP.NET Core website created within Visual Studio 2017. I have chosen to authenticate using an Azure Active Directory.
I run the site and can successfully login using an account in the Active Directory.
I can retrieve Claim information provided by Active Directory, e.g. by calling the following line I get the 'name'.
User.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
I want to add a custom claim - CompanyId = 123456 for the logged in user.
I'm able to add a custom claim however it is only available on the page where the claim is set.
Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
((ClaimsIdentity)User.Identity).AddClaim(claim);
My understanding is that I somehow need to update the token that has been issued by Active Directory or set the claim before the token is issued. I'm unsure how to do this.
I suspect this needs to be done in the AccountController at SignIn()
// GET: /Account/SignIn
[HttpGet]
public IActionResult SignIn()
{
return Challenge(
new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);
}
I've read numerous articles and samples about this scenario (including https://github.com/ahelland/AADGuide-CodeSamples/tree/master/ClaimsWebApp) however have not managed to solve how to persist the Claim across requests.
I have successfully managed to persist custom Claims using ASP.NET Identity as the Authentication Provider, but this appears to be because the custom Claim is saved to the database..
OnTokenValidated offers you the chance to modify the ClaimsIdentity obtained from the incoming token , code below is for your reference :
private Task TokenValidated(TokenValidatedContext context)
{
Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
(context.Ticket.Principal.Identity as ClaimsIdentity).AddClaim(claim);
return Task.FromResult(0);
}
Setting the OpenIdConnectEvents:
Events = new OpenIdConnectEvents
{
OnRemoteFailure = OnAuthenticationFailed,
OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
OnTokenValidated = TokenValidated
}
Then in controller using :
var companyId= User.Claims.FirstOrDefault(c => c.Type == "CompanyId")?.Value;
For those who would like more detail, the code provided is placed in Startup.cs
In the Configure method add/edit:
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = Configuration["Authentication:AzureAd:ClientId"],
Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
Events = new OpenIdConnectEvents
{
OnTokenValidated = TokenValidated
}
});
The private Task TokenValidated method is in the body of Startup.cs
The following sample is a good reference.
https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect-aspnetcore-v2/blob/master/WebApp-OpenIDConnect-DotNet/Startup.cs
I have created one b2c-dotnet-webapp-and-webapi type application. But After 20 min or after sometime(nearly 30 min not sure) My WebApp is throwing exception during the Ajax call saying 401(Unauthorized). This exception is coming when ajax call hitting the WebApp controller So this error is coming from OWIN middleware not sure why.
My Startup.cs settings are
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(_aadB2CPasswordResetPolicy));
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(_aadB2CSignInPolicy));
}
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
context.HandleResponse();
if (context.Exception is OpenIdConnectProtocolInvalidNonceException &&
context.Exception.Message.Contains("IDX10316"))
{
// Redirect to the originally requested URL
context.Response.Redirect(context.Request.Uri.PathAndQuery);
}
else
{
var trackingId = Guid.NewGuid().ToString("N");
_telemetry.TrackException(
context.Exception,
new Dictionary<string, string> {{"SignInErrorTrackingId", trackingId}});
context.Response.Redirect($"/Home/SignInError?trackingId={trackingId}");
}
return Task.FromResult(0);
}
private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
{
return new OpenIdConnectAuthenticationOptions
{
// For each policy, give OWIN the policy-specific metadata address, and
// set the authentication type to the id of the policy
MetadataAddress = string.Format(_aadInstance, _tenant, policy),
AuthenticationType = policy,
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = _clientId,
RedirectUri = _redirectUri,
PostLogoutRedirectUri = _redirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed,
},
Scope = "openid",
ResponseType = "id_token",
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
SaveSigninToken = true,
},
};
}
}
If I am modifying the code
app.UseCookieAuthentication(new CookieAuthenticationOptions { SlidingExpiration = true, ExpireTimeSpan = TimeSpan.FromMinutes(60) });,
And adding the below setting in OpenIdConnectAuthenticationOptions
UseTokenLifetime = false,
Then My WebApp is working for 1 hour and after that again I am facing the 401 Unauthorized. This time my WEAPI giving this error because by default token is valid for 1 hour I guess.
Question : How can I manage the token issues if the token is expired after 1 hour during ajax call ? and What is best setting that I should have So that my middleware will not give me 401 after 20 min or some random time ?
Kindly Ignore if something I am doing terribly wrong. I am very new to this and don't have much idea.
You're on the right track! There are a couple things that you need to be aware of:
All tokens returned by Azure AD B2C have an expiration time. After x minutes, your id token expired. You need to get a new id token again by going through the sign-in process again.
Because it is annoying to sign in every x minutes, you can request a refresh token when a user logs in for the first time. When the id token expires, you can send the refresh token to Azure AD B2C to get a new id token.
Part of the refresh token implementation is automated by the library, but this is what you need to implement:
Request a code in addition to an id token by adding 'code' in the responseType variable, and adding 'offline_access' in the scope variable.
Exchange the code for a refresh token and store the token inside a cache.
Get the token from the cache before making a call to the web api. If the token is expired, the library will automatically renew it for you before pulling it out of the cache.
All of this is done in this example. You just need to update the scope (the default responseType when you don't specify it is "code id_token").
Note: We enabled the use of access tokens and updated the sample with it. Please use this updated sample. Your code reflects the old sample. I also recommend using access tokens instead of id tokens when calling the web API.
Im trying Azure AD B2C and I've added Google and Microsoft Identity Providers through Azure Portal.
When i try to login with Microsoft OR Google IP, i always receive following error message in the OnAuthenticationFailed-Handler:
AADB2C99002: User does not exist. Please sign up before you can sign in.
But when i'm using the "Local Account SignIn" Provided by Azure B2C everything is working fine. Do i missing something in my configuration ?
The following code snippet shows my OWIN Configuration.
private void ConfigureAuthentication(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions
{
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = clientId,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed,
RedirectToIdentityProvider = OnRedirectToIdentityProvider,
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
SecurityTokenValidated = context => {
return null;
}
},
Scope = "openid offline_access",
// The PolicyConfigurationManager takes care of getting the correct Azure AD authentication
// endpoints from the OpenID Connect metadata endpoint. It is included in the PolicyAuthHelpers folder.
ConfigurationManager = new PolicyConfigurationManager(
String.Format(CultureInfo.InvariantCulture, aadInstance, tenant, "/v2.0", OIDCMetadataSuffix),
new string[] { SignUpPolicyId, SignInPolicyId, ProfilePolicyId }),
// This piece is optional - it is used for displaying the user's name in the navigation bar.
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
NameClaimType = "name",
},
};
app.UseOpenIdConnectAuthentication(options);
}
// This notification can be used to manipulate the OIDC request before it is sent. Here we use it to send the correct policy.
private async Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
PolicyConfigurationManager mgr = notification.Options.ConfigurationManager as PolicyConfigurationManager;
if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
{
OpenIdConnectConfiguration config = await mgr.GetConfigurationByPolicyAsync(CancellationToken.None, notification.OwinContext.Authentication.AuthenticationResponseRevoke.Properties.Dictionary[AzureB2C.PolicyKey]);
notification.ProtocolMessage.IssuerAddress = config.EndSessionEndpoint;
}
else
{
OpenIdConnectConfiguration config = await mgr.GetConfigurationByPolicyAsync(CancellationToken.None, notification.OwinContext.Authentication.AuthenticationResponseChallenge.Properties.Dictionary[AzureB2C.PolicyKey]);
notification.ProtocolMessage.IssuerAddress = config.AuthorizationEndpoint;
}
}
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
// The user's objectId is extracted from the claims provided in the id_token, and used to cache tokens in ADAL
// The authority is constructed by appending your B2C directory's name to "https://login.microsoftonline.com/"
// The client credential is where you provide your application secret, and is used to authenticate the application to Azure AD
string userObjectID = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant, string.Empty, string.Empty);
ClientCredential credential = new ClientCredential(clientId, clientSecret);
// We don't care which policy is used to access the TaskService, so let's use the most recent policy
string mostRecentPolicy = notification.AuthenticationTicket.Identity.FindFirst(AzureB2C.AcrClaimType).Value;
// The Authentication Context is ADAL's primary class, which represents your connection to your B2C directory
// ADAL uses an in-memory token cache by default. In this case, we've extended the default cache to use a simple per-user session cache
AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectID));
// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
// The token will be stored in the ADAL token cache, for use in our controllers
AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(redirectUri), credential, new string[] { clientId }, mostRecentPolicy);
}
// Used for avoiding yellow-screen-of-death
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
_log.Error("AuthenticationFailed!\r\nError={0}\r\nErrorDescription={1}\r\n{0}",
notification.ProtocolMessage.Error,
notification.ProtocolMessage.ErrorDescription,
notification.Exception.ToString());
notification.HandleResponse();
notification.Response.Redirect("/Home/OpenIdError?message=" + notification.ProtocolMessage.ErrorDescription);
return Task.FromResult(0);
}
}
External identities first need to 'sign up' as well before signing in. During sign up the external identity is linked to B2C.
In the sign up page you can ask additional attributes for your users, like a customer number. You need this for external identies and for the Local Account users in B2C, no difference between the two.
This is different behaviour compared to adding an identity provider without B2C, where every login just works.
Edit: Like Konstantin mentioned, the new combined sign-up or sign-in policy solves this problem:
https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-reference-policies/#create-a-sign-up-or-sign-in-policy
I was running into the same issue, but was able to circumvent the user "Sign-Up" after user insertion. The issue turned out to be, that to have proper federation occur, the proper values need to be in place.
"identities": [
{
"signInType": "federated",
"issuer": "https://login.microsoftonline.com/XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX/v2.0",
"issuerAssignedId": "YYYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY"
What was happening was that I was using "issuer": "myDomain.com" which was not resolving correctly to do a login; to which the user then had to "SignUp" via the federated IP.
By changing that from DNS readable name, to the MS login with my AD directories ID (the number provided when switching domain in Azure, XXXX-XXX ...) and the proper issuerAssignedId, from the originating AD issuer, it worked and the user was added.
My ASP.Net app uses OWIN/Katana/Claims, and allows login using:
Traditional username/password (exists for all users)
Google
Azure AD
It works perfectly, and all the necessary redirects/claims transfers work well (the user NameIdentifier/Provider(/tenant) details are passed back to my app so the unique id values can be linked up). Note that users do not sign up/register for the app - access is provisioned by their organisation's super-user, and a username/password sent to them which they can then hook up with Google/Azure.
However, I now need to extend this functionality to allow users to hook up to their organisation's ADFS provider. The only working example for this that's remotely close is here (tutorial/code), but it is strictly based on ADFS-only. When I adapt this into my project, it doesn't work.
My entire StartupAuth file is shown below. I appreciate that there may be configuration errors, but based on the scraps of samples I've found over the last six weeks, this is the best I've had.
public void Configuration(IAppBuilder app)
{
// STANDARD CODE FOR APP COOKIE AND GOOGLE - WORKS PERFECTLY
CookieAuthenticationOptions coa = new CookieAuthenticationOptions {
AuthenticationMode = AuthenticationMode.Active,
CookieName = "MyAppName",
ExpireTimeSpan = TimeSpan.FromMinutes(60),
SlidingExpiration = true,
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/login.aspx"),
CookieHttpOnly = true,
CookieSecure = CookieSecureOption.SameAsRequest,
Provider = new CookieAuthenticationProvider { OnValidateIdentity = context =>
{
dynamic ret = Task.Run(() =>
{
// Verify that "userId" and "customerId" claims exist, and that each has a valid value (greater than zero) - removed for brevity
return Task.FromResult(0);
});
return ret;
} }
};
app.SetDefaultSignInAsAuthenticationType(coa.AuthenticationType);
app.UseCookieAuthentication(coa);
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions {
ClientId = "84***********************k3.apps.googleusercontent.com",
ClientSecret = "jue*****************Ppi"
});
// NEW CODE THAT FAILS TO WORK - SPECIFYING EACH CUSTOMER'S ADFS AS A NEW WSFED AUTH OPTION
WsFederation.WsFederationAuthenticationOptions Adfs_CompanyA = new WsFederation.WsFederationAuthenticationOptions {
AuthenticationMode = AuthenticationMode.Passive,
MetadataAddress = "https://CompanyA.net/FederationMetadata/2007-06/FederationMetadata.xml",
AuthenticationType = AdfsAuthenticationTypes.CompanyA,
Wtrealm = "https://www.CompanyA.co.uk/MyAppName"
};
WsFederation.WsFederationAuthenticationOptions Adfs_CompanyB = new WsFederation.WsFederationAuthenticationOptions {
AuthenticationMode = AuthenticationMode.Passive,
MetadataAddress = "https://CompanyB.net/federationmetadata/2007-06/federationmetadata.xml",
AuthenticationType = AdfsAuthenticationTypes.CompanyB,
Wtrealm = "http://www.CompanyB.co.uk/azure/MyAppName"
};
// User (who is logged in), route for hyperlink "Link my account with ADFS"
app.Map("/SSO/LinkUserAccount/ADFS/process", configuration => { configuration.UseWsFederationAuthentication(Adfs_CompanyA); });
// CompanyA ADFS - single sign-on route
app.Map("/SSO/Login/CompanyA/ADFS/Go", configuration => { configuration.UseWsFederationAuthentication(Adfs_CompanyA); });
// CompanyB ADFS - single sign-on route
app.Map("/SSO/Login/CompanyB/ADFS/Go", configuration => { configuration.UseWsFederationAuthentication(Adfs_CompanyB); });
}
}
Here is the code I use to issue an OWIN Challenge:
string provider = MyApp.SingleSignOn.GetCustomerAdfsAuthenticationType(customerName);
string redirectUrl = string.Format("{0}/SSO/Login/{1}/ADFS/Go", Request.Url.GetLeftPart(UriPartial.Authority), provider); // creates https://myapp.com/SSO/Login/CompanyA/ADFS/Go for CompanyA users
Context.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = redirectUrl }, provider);
Response.StatusCode = 401;
Response.End();
This is webforms, but please don't let that stop MVC pro's from contributing. The code is virtually identical anyway and I'm using routes.
The problem I have is that when the user clicks on the "sign-on with ADFS" link, e.g. URL becomes https://myapp.com/SSO/Login/CompanyA/ADFS
I get an 401 Unauthorized error, instead of the user being redirected to the ADFS login page.
In web.config, I allow unauthorized access to path "SSO". For some reason the Challenge() method never redirects the user, it simply gets ignored and the code reaches the point where it returns a 401. The value of string provider exactly matches the WsFederationAuthenticationOptions.AuthenticationType value defined in Startup.Auth.
I've been sturggling with this now for six weeks, so this is getting a bounty at the first opportunity, and a crate of beer delivered to your chosen address when it is solved.
I solved the problem. Amazingly, it was as simple as me missing this from the end of StartupAuth:
app.UseStageMarker(PipelineStage.Authenticate);
Have you set up OWIN logging? Any clues there?
Also Test driving the WS-Federation Authentication Middleware for Katana.
Have a look at the code in IdentityServer 3. There's a WS-Fed plugin there and the documentation is here (at the bottom).