I have a c# console application that references the ADAL.net library (Microsoft.IdentityModel.Clients.ActiveDirectory version 2.19.208020213)
The purpose of the console app is to consume a HTTP endpoint which is protected with ADFS.
The implementation of the ADFS auth is as follows....
var uc = new UserCredential("user", "password");
var ctx = new AuthenticationContext("https://sts.example.com/adfs", false);
var token = ctx.AcquireToken(ClientResourceUri, ClientId, uc);
The call to AcquireToken throws an exception...
This method overload is not supported by
'https://sts.example.com/adfs/'
Calling AcquireToken without the UserCredential object, and instead providing a redirectUri works, but throws up a dialog prompting for username and password, which is unsuitable as the console app will be executed in a non user environment...
var redirect = new Uri("https://example.com/arbitaryRedirect");
var token = ctx.AcquireToken(ClientResourceUri, ClientId, redirect);
//dialog is shown
If i switch to the latest alpha release of the adal.net library (3.6.212041202-alpha)
the error is more revealing...
MSIS9611: The authorization server does not support the requested
'grant_type'. The authorization server only supports
'authorization_code' or 'refresh_token' as the grant type.
However, mining google yields very little.
Is it actually possible to authenticate silently against ADFS?
Would i be correct in assuming (based upon answers in other posts) that the correct approach is to use WsTrustChannelFactory instead?
If not, what is the best approach?
It is possible using ADAL 3.x and ADFS in Windows Server 2016, with pretty much the same code you posted. Combinations of older versions of either ADAL or ADFS won't work.
Alternatively, you can use WS-Trust - which is significantly harder to handle, but can get the job done.
Related
Is there an example of how to authenticate azure resource using User Managed Identity using c#? I am using the following code to authenticate using system managed identity and it works fine. but not sure about how to pass the user managed identity resource in the following example.
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var secret = await keyVaultClient.GetSecretAsync("https://mykeyvaultname.vault.azure.net/secrets/test")
.ConfigureAwait(false);
return new string[] { secret.Value };
Please see the documentation here. This feature is in the 1.2.0-preview version of the library. It only works on Azure VMs and VMSS as of now. You need to set the client id in a connection string, which can either be specified in the constructor or in the env variable (documentation of other connection string options here). In this scenario, the constructor is recommended, so you can use developer identity/ cert for local and switch to the user-assigned identity on Azure.
Update: The library has been updated to support user assigned identity in App Services as well as part of 1.2.0-preview2.
We are currently writing a Xamarin Forms Azure Mobile application, using client flow, AAD authentication, refresh tokens etc.
Most of this is working as expected. However, logging out of the application does not work properly. It completes the logout process for both Android and iOS - but upon redirection to the login screen, hitting sign in will never prompt the user with the Microsoft login as expected, it will sign them straight back into the app.
To add a little bit of background, this app has been implemented as per Adrian Hall's book,
current link: https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/
with the above described options and configurations.
I have also read through the 30 days of Zumo (also by Adrian Hall) blog on this, and every single post I can find on here relating to this.
My current logout code is as follows:
public async Task LogoutAsync()
{
var loginProvider = DependencyService.Get<ILoginProvider>();
client.CurrentUser = loginProvider.RetrieveTokenFromSecureStore();
var authUri = new Uri($"{client.MobileAppUri}/.auth/logout");
using (var httpClient = new HttpClient())
{
if (IsTokenExpired(client.CurrentUser.MobileServiceAuthenticationToken))
{
var refreshed = await client.RefreshUserAsync();
}
httpClient.DefaultRequestHeaders.Add("X-ZUMO-AUTH", client.CurrentUser.MobileServiceAuthenticationToken);
await httpClient.GetAsync(authUri);
}
// Remove the token from the cache
loginProvider.RemoveTokenFromSecureStore();
//Remove the cookies from the device - so that the webview does not hold on to the originals
DependencyService.Get<ICookieService>().ClearCookies();
// Remove the token from the MobileServiceClient
await client.LogoutAsync();
}
As far as I can tell, this includes everything I have found so far - i.e. calling the /.auth/logout endpoint, removing the token locally, clearing the cookies from the device (as we log in inside a webview) and lastly calling the LogoutAsync() method from the MobileServiceClient.
Am I missing anything? Or is there a way we can force log out from this environment? As I know you can't "invalidate" an OAuth token, you have to wait until it expires - but to my mind, the /.auth/logout endpoint is supposed to handle this within the Azure environment? Though I'm just not sure to what extent.
Any help is appreciated.
We are currently writing a Xamarin Forms Azure Mobile application, using client flow, AAD authentication, refresh tokens etc. Most of this is working as expected. However, logging out of the application does not work properly.
I assumed that if you use the server flow for logging with AAD, the logout processing may works as expected. As you described that you used client flow, since you have clear the client cache for token, I assumed that the issue may caused by the LoginAsync related (ADAL part) logic code, you need to check your code, or you could provide the logging related code for us to narrow this issue.
I have a test console app which I'm pointing at a local instance of Identity Server 3 to request an access token. The following code does this and returns my token fine (passing a single scope "scope.test.client").
static TokenResponse GetClientToken(string clientId, string clientSecret, string[] scopes)
{
var uri = new Uri(string.Concat(ID_BASE_URI, ID_URL_TOKEN));
var client = new TokenClient(
uri.AbsoluteUri,
clientId,
clientSecret);
return client.RequestClientCredentialsAsync(string.Join(" ", scopes)).Result;
I then use this token to call an API also running locally. This takes the TokenResponse obtained above and passed it to this method:
static void CallApi(string url, TokenResponse response)
{
try
{
using (var client = new HttpClient())
{
client.SetBearerToken(response.AccessToken);
Console.WriteLine(client.GetStringAsync(url).Result);
}
}
catch (Exception x)
{
Console.WriteLine(string.Format("Exception: {0}", x.Message));
}
}
The API (an ASP.NET WebApi project) uses an Owin Startup class to enforce bearer token authentication for all requests:
appBuilder.Map(baseApiUrl, inner =>
{
inner.UseWebApi(GlobalConfiguration.Configuration);
// Enforce bearer token authentication for all API requests
inner.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://identityserver/core",
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { "scope.test.client" }
});
});
It also ensures all API requests are handled by a custom authorize attribute:
GlobalConfiguration.Configuration.Filters.Add(new DefaultApiAuthorizeAttribute());
Debugging this API, the first line in my overridden OnAuthorize method (in DefaultApiAuthorizeAttribute) is this:
var caller = actionContext.RequestContext.Principal as System.Security.Claims.ClaimsPrincipal;
If I break on this line I can see that actionContext.RequestContext.Principal is always null. However, I can see that ((System.Web.Http.Owin.OwinHttpRequestContext)actionContext.RequestContext).Request.Headers contains an Authorization header with the bearer token passed from my console app.
So it would seem that the API project is not authenticating the bearer token. Certainly the Identity Server logs suggest it isn't being hit at all after issuing the initial access token. So I'd appreciate your expert advice about why this might not be happening, or at least some pointers about where to look.
I suspect it might have something to do with SSL. Both sites are hosted locally under self-signed SSL certs, although Identity Server is configured to not require SSL and uses the idsrv3test.pfx development certificate for signing. I do have another test MVC web app which delegates authentication to the same IS3 instance which works fine locally, so I believe my IS3 instance is configured correctly.
You need to call UseIdentityServerBearerTokenAuthentication before you call UseWebApi. When you set up an OWIN Middleware Pipeline, the order is important.
In your case, Web API will be handling your requests before they get sent onto Identity Server (if they get sent on at all).
I imagine a range of possible issues could have the impact I described, but in my case I was able to find the cause by adding a diagnostics log to my consuming API. This led me to discover that the problem was an assembly conflict. The Owin middleware was looking for a Newtonsoft.JSON assembly with version 8.0.0.0 but my consuming API (actually running on top of a CMS intance) was using 7.0.0.0.
For anyone else who wants to find the answer fast, rather than spend hours tweaking configurations, here's the documentation that describes how to add this logging: https://identityserver.github.io/Documentation/docsv2/consuming/diagnostics.html
I've successfully created a new Application Group with a Server Application as well as a Web API and the OpenID Connect protocol is working w/out any issues until I try and make a call to UserInfo. The Relying Party identifier is the same GUID as Client ID of the Server Application (per the examples I have read online). I get the error below when trying to call UserInfo:
WWW-Authenticate: Bearer error="invalid_token", error_description="MSIS9921: Received invalid UserInfo request. Audience 'microsoft:identityserver:21660d0d-93e8-45db-b770-45db974d432d' in the access token is not same as the identifier of the UserInfo relying party trust 'urn:microsoft:userinfo'."
Any help would be greatly appreciated.
I also recently got this error using ADFS with the ASP.NET Core OpenIDConnect providers. In my case, disabling the UserInfo request altogether resolved the issue:
var openIdOptions = new OpenIdConnectOptions
{
...
GetClaimsFromUserInfoEndpoint = false
};
After doing this, I still had the claims that I needed for my app - email, SID, name, etc. I'm sure there are scenarios where this would not work, but it's good to know you might not need /userinfo at all. I would still be interested in knowing why the token returned from ADFS can't be used to call /userinfo, and how to fix it in ASP.NET OpenIDConnect providers.
Just set the resource accordingly:
options.Resource = "urn:microsoft:userinfo";
I'm working on a SaaS application built around ASP.net MVC & WebAPI and want to make it easy for enterprises to use my service. Example would be Office 365 Basic Authentication (Active Profile) where the user enters his username/password on microsoft's site (or desktop app) and he is authenticated against his employer's Active Directory. My understanding so far is that I would need to create a RP-STS which will accept credentials and then forward those to AD FS Proxy running on the client company's AD server. Is this correct?
If yes, then how do I implement this? Setting up AD server adding a Relying Party and AD FS Proxy Role is easy, so that's really not an issue. I just need to figure out how to create/setup RP-STS service and any other steps involved in this process. There just isn't an example/tutorial of this in .net
I believe this msdn blog post describes exactly what you're asking for. It has a complete walkthrough of the entire process, including creating an RP by creating a normal WCF service, and then use the provided utility to configure the service to trust your ADFS.
http://blogs.msdn.com/b/mcsuksoldev/archive/2011/08/17/federated-security-how-to-setup-and-call-a-wcf-service-secured-by-adfs-2-0.aspx
Edit:
This code, taken from the linked article (comments are mine), is a demonstration of active federation. The client application is manually retrieving a security token from the ADFS. Passive Federation would involve forwarding the user to a secure web page in which they could send their credentials directly to the ADFS. The major benefit of Passive Federation is that the end user's secret credentials are provided directly to the ADFS, and the RP's client side code never has access to it.
var requestTokenResponse = new RequestSecurityTokenResponse();
//The line below is the 'Active' federation
var token = Token.GetToken(#"mydomain\testuser", "p#ssw0rd", "http://services.testdomain.dev/wcfservice/Service.svc", out requestTokenResponse);
var wcfClient = new FederatedWCFClient<MyTestService.IService>(token, "WS2007FederationHttpBinding_IService"); // This must match the app.config
var client = wcfClient.Client as MyTestService.IService;
var result = client.GetData();
Console.WriteLine(result);
wcfClient.Close();
Take a look at these links:
https://github.com/OfficeDev/O365-WebApp-SingleTenant
https://github.com/OfficeDev/O365-WebApp-MultiTenant
It shows how to make an application using the office 365 api to authenticate and authorize the users.
Be aware about Single Tenant and Mult Tentant application, and choose the right one.
It's really easy to do that, I've done it couple months ago.
I found the answer on the blog: http://leandrob.com/2012/04/requesting-a-token-from-adfs-2-0-using-ws-trust-with-username-and-password/
What this code essentially does is that it directly authenticates with the tenant's ADFS endpoint and gets a token as well. That's what I was looking for.
var stsEndpoint = "https://[server]/adfs/services/trust/13/UsernameMixed";
var relayPartyUri = "https://localhost:8080/WebApp";
var factory = new WSTrustChannelFactory(
new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
new EndpointAddress(stsEndpoint));
factory.TrustVersion = TrustVersion.WSTrust13;
// Username and Password here...
factory.Credentials.UserName.UserName = user;
factory.Credentials.UserName.Password = password;
var rst = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
AppliesTo = new EndpointAddress(relayPartyUri),
KeyType = KeyTypes.Bearer,
};
var channel = factory.CreateChannel();
SecurityToken token = channel.Issue(rst);
Another good article on that blog is: http://leandrob.com/2012/02/request-a-token-from-adfs-using-ws-trust-from-ios-objective-c-iphone-ipad-android-java-node-js-or-any-platform-or-language/ - which covers other similar scenarios.