Get Azure Active Directory Token with username and password - azure

I'm trying to authenticate my client using AAD and automate this using a Windows Service. In AAD .NET SDK, There's two methods, AcquireTokenAsync and AcquireToken, but i can't use either of these methods, the await call will stay forever with no response, and when i do something like this:
result = authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword)).Result;
The object returns a status of Waiting for Activation & Code 31..
Now, Is there anyway to acquire the token using hardcoded username and password?
My full code:
string hardcodedUsername = "username";
string hardcodedPassword = "password";
string tenant = "tenantId#onmicrosoft.com";
string clientId = "clientId";
string resourceHostUri = "https://management.azure.com/";
string aadInstance = "https://login.microsoftonline.com/{0}";
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
authContext = new AuthenticationContext(authority);
AuthenticationResult result = null;
try
{
result = authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword)).Result;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return result;
I'm trying to get access to Azure API.
UPDATE 1:
I got this in the output when i tried to await the call, i think this might help:
Microsoft.IdentityModel.Clients.ActiveDirectory TokenCache: Looking up cache for a token...
Microsoft.IdentityModel.Clients.ActiveDirectory TokenCache: No matching token was found in the cache
Microsoft.IdentityModel.Clients.ActiveDirectory d__0: Sending user realm discovery request to 'https://login.microsoftonline.com/common/UserRealm/username?api-version=1.0'
Microsoft.IdentityModel.Clients.ActiveDirectory d__4: User with hash '***' detected as 'Federated'

try below link code
https://msdn.microsoft.com/en-in/library/partnercenter/dn974935.aspx
how to get access token after windows azure active directory authentication
How to get current token from Azure ActiveDirectory application
// Get OAuth token using client credentials
string tenantName = "GraphDir1.OnMicrosoft.com";
string authString = "https://login.microsoftonline.com/" + tenantName;
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
// Config for OAuth client credentials
string clientId = "118473c2-7619-46e3-a8e4-6da8d5f56e12";
string key = "hOrJ0r0TZ4GQ3obp+vk3FZ7JBVP+TX353kNo6QwNq7Q=";
ClientCredential clientCred = new ClientCredential(clientId, key);
string resource = "https://graph.windows.net";
string token;
try
{
AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resource, clientCred);
token = authenticationResult.AccessToken;
}
catch (AuthenticationException ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
if (ex.InnerException != null)
{
// You should implement retry and back-off logic according to
// http://msdn.microsoft.com/en-us/library/dn168916.aspx . This topic also
// explains the HTTP error status code in the InnerException message.
Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
}
}

Please try the following:
static void Main(string[] args)
{
Task<AuthenticationResult> t = getAccessToken();
t.Wait();
var result = t.Result;
Console.WriteLine(result.AccessToken);
Console.WriteLine("Please any key to terminate the program");
Console.ReadKey();
}
public static async Task<AuthenticationResult> getAccessToken()
{
string hardcodedUsername = "username";
string hardcodedPassword = "password";
string tenant = "tenant.onmicrosoft.com";
string clientId = "clientId";
string resourceHostUri = "https://management.azure.com/";
string aadInstance = "https://login.microsoftonline.com/{0}";
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
var authContext = new AuthenticationContext(authority);
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync(resourceHostUri, clientId, new UserCredential(hardcodedUsername, hardcodedPassword));
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return result;
}
What I have done is made getAccessToken() method async and inside that the code is made to wait to get the token when you call authContext.AcquireTokenAsync.

Related

Azure AD B2C Custom User Attributes

I'm new to the Azure B2C world. I'm attempting to create a Custom User attribute to store data for our application. I've created it in the Azure portal and assigned it to my Signup/SignIn policy. However, I want to be able to update/read this value programtically. I've been going down the route of using Graph API and registering Extensions. So two questions:
1) Are extensions/custom attributes the same thing?
2) I've tried this code and the returned extensions are always empty:
public void RegisterExtension()
{
string myRegisteredAppObjectId = "<>";
string json = #"{
""name"": ""My Custom Attribute"",
""dataType"": ""String"",
""targetObjects"": [
""User""
]
}";
B2CGraphClient b2CGraphClient = new B2CGraphClient();
b2CGraphClient.RegisterExtension(myRegisteredAppObjectId, json);
var extensions = JsonConvert.DeserializeObject(b2CGraphClient.GetExtensions(myRegisteredAppObjectId).Result);
}
B2CGraphClient.cs
public class B2CGraphClient
{
private string clientId { get; set; }
private string clientSecret { get; set; }
private string tenant { get; set; }
private AuthenticationContext authContext;
private ClientCredential credential;
public B2CGraphClient(string clientId, string clientSecret, string tenant)
{
// The client_id, client_secret, and tenant are pulled in from the App.config file
this.clientId = clientId;
this.clientSecret = clientSecret;
this.tenant = tenant;
// The AuthenticationContext is ADAL's primary class, in which you indicate the direcotry to use.
this.authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);
// The ClientCredential is where you pass in your client_id and client_secret, which are
// provided to Azure AD in order to receive an access_token using the app's identity.
this.credential = new ClientCredential(clientId, clientSecret);
}
public async Task<string> DeleteUser(string objectId)
{
return await SendGraphDeleteRequest("/users/" + objectId);
}
public async Task<string> RegisterExtension(string objectId, string body)
{
return await SendGraphPostRequest("/applications/" + objectId + "/extensionProperties", body);
}
public async Task<string> GetExtensions(string appObjectId)
{
return await SendGraphGetRequest("/applications/" + appObjectId + "/extensionProperties", null);
}
private async Task<string> SendGraphPostRequest(string api, string json)
{
// NOTE: This client uses ADAL v2, not ADAL v4
AuthenticationResult result = authContext.AcquireToken(Globals.aadGraphResourceId, credential);
HttpClient http = new HttpClient();
string url = Globals.aadGraphEndpoint + tenant + api + "?" + Globals.aadGraphVersion;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("POST " + url);
Console.WriteLine("Authorization: Bearer " + result.AccessToken.Substring(0, 80) + "...");
Console.WriteLine("Content-Type: application/json");
Console.WriteLine("");
Console.WriteLine(json);
Console.WriteLine("");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await http.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
string error = await response.Content.ReadAsStringAsync();
object formatted = JsonConvert.DeserializeObject(error);
throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase);
Console.WriteLine("");
return await response.Content.ReadAsStringAsync();
}
public async Task<string> SendGraphGetRequest(string api, string query)
{
// First, use ADAL to acquire a token using the app's identity (the credential)
// The first parameter is the resource we want an access_token for; in this case, the Graph API.
AuthenticationResult result = authContext.AcquireToken("https://graph.windows.net", credential);
// For B2C user managment, be sure to use the 1.6 Graph API version.
HttpClient http = new HttpClient();
string url = "https://graph.windows.net/" + tenant + api + "?" + Globals.aadGraphVersion;
if (!string.IsNullOrEmpty(query))
{
url += "&" + query;
}
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("GET " + url);
Console.WriteLine("Authorization: Bearer " + result.AccessToken.Substring(0, 80) + "...");
Console.WriteLine("");
// Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await http.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
string error = await response.Content.ReadAsStringAsync();
object formatted = JsonConvert.DeserializeObject(error);
throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase);
Console.WriteLine("");
return await response.Content.ReadAsStringAsync();
}
}
Of course, myRegisteredAppObjectId has a valid GUID in it.
Thanks
Are extensions/custom attributes the same thing?
Based on my test, extensions is the same thing as custom attributes.
I've tried this code and the returned extensions are always empty:
I add the custom propery MyCustomAttribute following this tutorial and use a custom attribute in my policy. You could refer to my test steps.
I download the B2C-GraphAPI-DotNet project from Github. Using following code to the custom attribute
var applications = client.GetApplications("$filter=startswith(displayName, 'b2c-extensions-app')").Result
var extension = client.GetExtensions(objectId).Result //objectId from the applications result.
Then we could get the custom properties from the extension.
Then you can then treat that attribute the same way you treat any other property on a user object
Such as create a user:
var jsonObject = new JObject
{
{"accountEnabled", true},
{"country", "US"},
{"creationType", "LocalAccount"},
{"displayName", "Tomsun"},
{"passwordPolicies", "DisablePasswordExpiration,DisableStrongPassword"},
{ "extension_42ba0de8530a4b5bbe6dad21fe6ef092_MyCustomAttribute","test2"}, //custom propery
{"passwordProfile", new JObject
{
{"password", "!QAZ1234wer"},
{"forceChangePasswordNextLogin", true}
} },
{"signInNames", new JArray
{
new JObject
{
{"value","tom1#example.com"},
{"type", "emailAddress"}
}
}
}
};
string user = client.CreateUser(jsonObject.ToString()).Result;
Query a user
var user = client.GetUserByObjectId(objectId).Result; //user objectId
Update a user
var jsonUpdate = new JObject
{
{ "extension_42ba0de8530a4b5bbe6dad21fe6ef092_MyCustomAttribute","testx"}
};
var updateuser = client.UpdateUser("objectId", jsonObject2.ToString()).Result; //UserObject Id

Azure Ad authentication by passing username and password to get the jwt token

Currently i am trying to implement the azure active directory authentication by passing user name and password. So for this i have trying to get the access toke but facing issue to get the same. If i use the client id and client secret then i am able to get the token but when i try to by passing username and password then its not giving the result and throwing the exception :
"error":"invalid_client","error_description":"AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion'
Below the code which i am using for this:
/// <summary>
/// Working with client id and client secret
/// </summary>
/// <returns></returns>
public async Task<string> GetTokenUsingClientSecret()
{
//authentication parameters
string clientID = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
string clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXX";
string directoryName = "xxx.onmicrosoft.com";
var credential = new ClientCredential(clientID, clientSecret);
var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/" + directoryName, false);
var result = await authenticationContext.AcquireTokenAsync("https://management.core.windows.net/", clientCredential: credential);
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
/// <summary>
/// Not Working with username and password.
/// </summary>
public async Task<string> GetTokenUsingUserNamePassword()
{
try
{
string user = "username.onmicrosoft.com";
string pass = "yourpassword";
string directoryName = "XXXX.onmicrosoft.com";
string authority = "https://login.microsoftonline.com";
string resource = "https://management.core.windows.net/";
string clientId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var credentials = new UserPasswordCredential(user, pass);
var authenticationContext = new AuthenticationContext($"{authority}/{directoryName}");
var result = authenticationContext.AcquireTokenAsync(resource: resource, clientId: clientId, userCredential: credentials);
return result.Result.AccessToken;
}
catch (Exception ex)
{
throw ex;
}
}
AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion'.
According to your mentioned exception, I assume that you registry an Azure AD Web app/API application. Please have a try to use an Azure AD native appilcation then it should work. More details you could refer to this document -Constraints & Limitations section.
No web sites/confidential clients
This is not an ADAL limitation, but an AAD setting. You can only use those flows from a native client. A confidential client, such as a web site, cannot use direct user credentials.
How to reigstry Azure AD native Application.

AcquireToken async returning same token before expiry time

I have registered my application with Azure AD App registration.
In my scenario i am using Azure Adal AquireTokenAsync method with client credentials which is always returning same token.
i need a new token for every user session.
for testing purpose i have created console application to test the behaviour.
string authority = String.Format(CultureInfo.InvariantCulture,
ConfigurationManager.AppSettings["ida:AADInstance"],
ConfigurationManager.AppSettings["ida:Tenant"]);
AuthenticationContext authContext = new AuthenticationContext(authority, false);
ClientCredential clientCredential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientId"], ConfigurationManager.AppSettings["ida:AppKey"]);
AuthenticationResult result = null;
int retryCount = 0;
bool retry = false;
retry = false;
try
{
result = await authContext.AcquireTokenAsync(ConfigurationManager.AppSettings["ida:ResourceId"], clientCredential);
result = await authContext.AcquireTokenAsync(ConfigurationManager.AppSettings["ida:ResourceId"], clientCredential);
}
catch (AdalException ex)
{
}
finally
{
authContext = null;
}
In both the calls it is returning the same token.
however for every fresh execution it is returning new token.
ADAL context cache keep token.If you need to get it refreshed please clear the cache using
authContext.TokenCache.Clear();
it will clear the cache.
It's because inside AuthenticationContext, there is TokenCache to cache the id_token. So, if you would like to have new token every time calling AcquireTokenAsync, set TokenCache is null when creating AuthenticationContext object:
AuthenticationContext authContext = new AuthenticationContext(authority, false, null);
Please prefer the link

Extend MSAL to support multiple Web APIs

Hi I started with the sample here
https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi
And manqaged to get the TaskWebApp talking to the TaskService.
I now want to extend the solution to have a 3rd service
Im not sure if the problem is within the ConfidentialClientApplication as when it fails to get my tokens i get no exception.
I think the issue is the COnfigureApp method in my TaskWebApp is only expecting to manage tokens from the single TokenService.
Here is my web App Starttup.Auth ConfigureAuth method, this is unchanged from the sample app
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// Generate the metadata address using the tenant and policy information
MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy),
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = ClientId,
RedirectUri = RedirectUri,
PostLogoutRedirectUri = RedirectUri,
// Specify the callbacks for each type of notifications
Notifications = new OpenIdConnectAuthenticationNotifications
{
RedirectToIdentityProvider = OnRedirectToIdentityProvider,
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
AuthenticationFailed = OnAuthenticationFailed,
},
// Specify the claims to validate
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
},
// Specify the scope by appending all of the scopes requested into one string (seperated by a blank space)
Scope = $"{OpenIdConnectScopes.OpenId} {ReadTasksScope} {WriteTasksScope}"
}
);
}
Here is my OnAuthorizationCodeReceived method, again unchanged
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
// Extract the code from the response notification
var code = notification.Code;
var userObjectId = notification.AuthenticationTicket.Identity.FindFirst(ObjectIdElement).Value;
var authority = String.Format(
AadInstance,
Tenant,
DefaultPolicy);
var httpContext = notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase;
// Exchange the code for a token. Make sure to specify the necessary scopes
ClientCredential cred = new ClientCredential(ClientSecret);
ConfidentialClientApplication app = new ConfidentialClientApplication(
authority,
Startup.ClientId,
RedirectUri,
cred,
new NaiveSessionCache(userObjectId, httpContext));
var authResult = await app.AcquireTokenByAuthorizationCodeAsync(new string[]
{
ReadTasksScope,
WriteTasksScope
},
code,
DefaultPolicy);
}
The problem seems to be that my Readand write scope are referencing the TaskService directly and when i try to ask for appropriate scopes from other apps it complains.
in my controller
private async Task<String> acquireToken(String[] scope)
{
try
{
string userObjectID = ClaimsPrincipal.Current.FindFirst(Startup.ObjectIdElement).Value;
string authority = String.Format(Startup.AadInstance, Startup.Tenant, Startup.DefaultPolicy);
ClientCredential credential = new ClientCredential(Startup.ClientSecret);
// Retrieve the token using the provided scopes
ConfidentialClientApplication app = new ConfidentialClientApplication(authority, Startup.ClientId,
Startup.RedirectUri, credential,
new NaiveSessionCache(userObjectID, this.HttpContext));
AuthenticationResult result = await app.AcquireTokenSilentAsync(scope);
return result.Token;
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
throw e;
}
This method is used but My AuthorisationResult fails with the message couldnt get token silently with no inner exception.
So far I have tried removing the NaiveSessionCache as its optional and it still fails
To get past this I have registered a 4th service and then made my webapis use that single client id and secret to control access to their resources but this feels like it is not the correct way forward.
Any help would be great thanks

Using App Model V2 to get access to calendar

We have a webapplication on ASP.NET in Azure and we want to get access to the current user to his calendar to show the events for today and the number of unread emails. We have application that used graph.microsoft.com with default "Work or School Account"authentication that is created with Visual Studio, but this does not work with App Model V2.
How can build an applicaiton that is able to authenticate using App Model V2 and get access to graph.microsoft.com?
You need to use Microsoft.IdentityModel.Clients.ActiveDirectory;
A good samples is given in
https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview/
The step that you need to take for a App Model V2 application are:
Register your application using the application registration portal on https://apps.dev.microsoft.com. Remember the clientID and clientsecret that is registered for you.
Create an asp.net in VS2015 without authentication (anonymous)
Add the Nuget Package Microsoft.IdentityModel.Clients.ActiveDirectory
Add using Microsoft.IdentityModel.Clients.ActiveDirectory to the controller
You need to add scope to your code as private member
private static string[] scopes = {
"https://graph.microsoft.com/calendars.readwrite" };
Add add the following settings to web.config
<add key="ida:ClientID" value="..." />
<add key="ida:ClientSecret" value="..." />
You have to create 2 extra methods. One for the signin and one for the authorize:
Signin:
public async Task<ActionResult> SignIn()
{
string authority = "https://login.microsoftonline.com/common/v2.0";
string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"];
AuthenticationContext authContext = new AuthenticationContext(authority);
// The url in our app that Azure should redirect to after successful signin
Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
// Generate the parameterized URL for Azure signin
Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, additionalScopes, clientId,
redirectUri, UserIdentifier.AnyUser, null);
// Redirect the browser to the Azure signin page
return Redirect(authUri.ToString());
}
Authorize:
public async Task<ActionResult> Authorize()
{
// Get the 'code' parameter from the Azure redirect
string authCode = Request.Params["code"];
string authority = "https://login.microsoftonline.com/common/v2.0";
string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"];
string clientSecret = System.Configuration.ConfigurationManager.AppSettings["ida:ClientSecret"];
AuthenticationContext authContext = new AuthenticationContext(authority);
// The same url we specified in the auth code request
Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
// Use client ID and secret to establish app identity
ClientCredential credential = new ClientCredential(clientId, clientSecret);
try
{
// Get the token
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
authCode, redirectUri, credential, scopes);
// Save the token in the session
Session["access_token"] = authResult.Token;
return Redirect(Url.Action("Tasks", "Home", null, Request.Url.Scheme));
}
catch (AdalException ex)
{
return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
}
}
The accestoken is in a session state.
Now you can call graph.microsoft.com with the correct accesstoken and get the data:
private async Task<List<DisplayEvent>> GetEvents()
{
List<DisplayEvent> tasks = new List<DisplayEvent>();
HttpClient httpClient = new HttpClient();
var accessToken = (string)Session["access_token"];
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await httpClient.GetAsync("https://graph.microsoft.com/beta/users/me/events");
if (response.IsSuccessStatusCode)
{
string s = await response.Content.ReadAsStringAsync();
JavaScriptSerializer serializer = new JavaScriptSerializer();
EventModels eventList = serializer.Deserialize<EventModels>(s);
foreach (EventModel v in eventList.value)
{
//Fill tasks will events
}
}
return tasks;
}

Resources