AcquireTokenAsync gets Response status code does not indicate success: 401 (Unauthorized) - azure-active-directory

As part of ECR, I'm changing our code to get token by using subject name instead of the thumbprint of our aad 1st party application.
I made a few changes:
1. I added the subject name to the "subject name + issuer" in the aad portal.
2. added the "sendX5c: true" parameter to the AcquireTokenAsync function call.
I'm getting the certificate from my machine but when trying to acquire the token I'm getting this exception: AADSTS7000213: Invalid certificate chain. with the inner exception of "Response status code does not indicate success: 401 (Unauthorized)".
Any idea what am I doing wrong or what is missing?
I followed this link: https://aadwiki.windows-int.net/index.php?title=Subject_Name_and_Issuer_Authentication

If you want to request Azure AD access token with client certificate, please refer to the following steps
Upload the information of the cert to Azure
a. get the information
$Thumbprint="930CFA423637129DB45921320B0BB451BD58A813"
$cert=Get-ChildItem -Path Cert:\LocalMachine\My\$Thumbprint
$rawCert = $cert.GetRawCertData()
$base64Cert = [System.Convert]::ToBase64String($rawCert)
$rawCertHash = $cert.GetCertHash()
$base64CertHash = [System.Convert]::ToBase64String($rawCertHash)
$KeyId = [System.Guid]::NewGuid().ToString()
b. upload the above information to Azure
Connect-AzureAD
$clientAadApplication=Get-AzureADApplication -Filter "AppId eq '<you client id>'"
New-AzureADApplicationKeyCredential -ObjectId $clientAadApplication.ObjectId -CustomKeyIdentifier "$base64CertHash" -Type AsymmetricX509Cert -Usage Verify -Value $base64Cert
Get access token(I use the sdk Microsoft.Identity.Client)
String subjectname="";
X509Store store = new X509Store(StoreName.My,StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = store.Certificates;
X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectName, subjectname, false);
X509Certificate2 cer = signingCert.OfType<X509Certificate2>().OrderByDescending(c => c.NotBefore).FirstOrDefault();
var app = ConfidentialClientApplicationBuilder.Create("<client id>")
.WithAuthority(AzureCloudInstance.AzurePublic, "<tenant id>")
.WithCertificate(cer)
.Build();
var result = await app.AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" }).ExecuteAsync();
Console.WriteLine(result.AccessToken);
Console.Read();
For more details, please refer to the document and the sample

Related

Is there a way to validate azure app credentials?

Given I have the following info from Azure app registration:
Application (client) ID,
Client secret,
Directory (tenant) ID,
Object ID
Is there a way to check it's a valid credential programmatically (like using curl etc but not powershell)?
If you meant to check client secret validity or even the properties of that app ,then please check if the below c# code can be worked around .We can try to query the application and see expiry date of secret. Please grant the app with Directory.Read.All ,Application.Read.All permission to this API for using client credentials flow.
var graphResourceId = "https://graph.microsoft.com";
var applicationId= "";
var ObjectId = "";
var clientsecret = "";
var clientCredential = new ClientCredential(applicationId,secret);
var tenantId = "xxx.onmicrosoft.com";
AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}");
//get accesstoken
var accessToken = authContext.AcquireTokenAsync(graphResourceId, clientCredential).Result.AccessToken;
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));
var app = activeDirectoryClient.Applications.GetByObjectId(appObjectId).ExecuteAsync().Result;
foreach (var passwordCredential in app.PasswordCredentials)
{
Console.WriteLine($"KeyID:{passwordCredential.KeyId}\r\nEndDate:{passwordCredential.EndDate}\r\n");
}
If you want , you can even request token using curl this way and validate using post man or by checking token in https://jwt.io .
Reference: check client secret expiry using C#

How to retrieve the userid from userprincipalname in azure active directory?

My client has synchronization set up between an on-premises Active Directory (AD) and Azure Active Directory (AAD).
I am able to retrieve user information from AAD using Microsoft Graph without a problem but, I specifically need to get the AD UserID, ie ({domain}/{userid}).
I tried calling https://graph.microsoft.com/v1.0/users/firstname.lastname#domain.com/$select=userId but it did not work.
My questions are, is it possible? And in that case what is the actual attribute name? I have been looking around but haven´t been able to find a complete list of attributes.
EDIT:
After receiving one answer from Marilee I am including the C# code I have been using, ish. Both the calls do work for receiving user information from AAD, but not the AD UserID, ie ({domain}/{userid}) that I am looking for.
Attempt no 1
var requestUri = GraphBaseUri + $"/v1.0/users/{upn}?$select=userId";
var response = await _httpClient.GetAsync(new AuthenticationHeaderValue("Bearer", accessToken), requestUri).ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
dynamic responseObj = JsonConvert.DeserializeObject(content) as JObject;
return responseObj.UserId; //NOT WORKING
Attempt no 2
var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return Task.FromResult(0);
}));
// Retrieve a user by userPrincipalName
var user = await graphClient
.Users[upn]
.Request()
.GetAsync();
return user.ObjectId; //NOT WORKING
The attribute you're referring to is the objectID. From Graph API you can use UPN like you said:
GET /users/{id | userPrincipalName}
You can look up the user in a few different ways. From the /users endpoint you can either use their id (the GUID assigned to each account) or their userPrincipalName (their email alias for the default domain):
// Retrieve a user by id
var user = await graphClient
.Users["00000000-0000-0000-0000-000000000000"]
.Request()
.GetAsync();
// Retrieve a user by userPrincipalName
var user = await graphClient
.Users["user#tenant.onmicrosoft.com"]
.Request()
.GetAsync();
If you're using either the Authorization Code or Implicit OAuth grants, you can also look up the user who authenticated via the /me endpoint:
var user = await graphClient
.Me
.Request()
.GetAsync();
From Powershell you can query Object IDs:
$(Get-AzureADUser -Filter "UserPrincipalName eq 'myuser#consoso.com'").ObjectId
The way to do this is;
var requestUri = GraphBaseUri + $"/v1.0/users/{upn}?$select=onPremisesSamAccountName";
var response = await _httpClient.GetAsync(new AuthenticationHeaderValue("Bearer", accessToken), requestUri).ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var responseObj = JsonConvert.DeserializeObject<ResponseObj>(content);
return responseObj.OnPremisesSamAccountName;
Notice the select where we collect the onPremisesSamAccountName. Though, I haven´t found a comprehensive list of all attributes possible to retrieve which would have been nice.

Google Classroom Pub/Sub registration returning 403 authentication error

I'm developing a php application using Google Classroom, and keep getting a "code": 403, "message": "Request had insufficient authentication scopes." error.
Here's what I've done so far, any help would be tremendous!
I've set up my app oauth permissions to use auth/classroom.push-notifications
I've set 'classroom-notifications#system.gserviceaccount.com' to have the Pub/Sub Publisher role
I've set up a Pub/Sub topic
Here's the code I'm using:
$google_course_id = '123456';
$topic_name = 'projects/my-app-name/topics/TopicName';
$feed_type = 'COURSE_WORK_CHANGES';
$user = User::find(2); // User who has authorized via OAuth and accepted all permissions
$client = new Google_Client();
$client->setAccessToken($user->get_google_social_token());
$classroom = new Google_Service_Classroom($client);
$pub_sub = new Google_Service_Classroom_CloudPubsubTopic();
$pub_sub->setTopicName($topic_name);
$work_changes_info = new Google_Service_Classroom_CourseWorkChangesInfo();
$work_changes_info->setCourseId($google_course_id);
$feed = new Google_Service_Classroom_Feed();
$feed->setCourseWorkChangesInfo($work_changes_info);
$feed->setFeedType($feed_type);
$registration = new Google_Service_Classroom_Registration();
$registration->setCloudPubsubTopic($pub_sub);
$registration->setFeed($feed);
$classroom->registrations->create($registration);
Unfortunately, I keep getting the 403 error.
Any help in identifying what I'm missing would be greatly appreciated!
I'm an idiot. While I remembered to add the push-notification scope to my google developer console, I forgot to add them to the Oauth linking code. Adding it to the bottom seems to have fixed the issue!
return Socialite::driver('google')
->scopes(['https://www.googleapis.com/auth/classroom.courses.readonly',
'https://www.googleapis.com/auth/classroom.rosters.readonly',
'https://www.googleapis.com/auth/classroom.coursework.students.readonly',
'https://www.googleapis.com/auth/classroom.guardianlinks.students.readonly',
'https://www.googleapis.com/auth/classroom.profile.emails',
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/classroom.push-notifications',
])
->with(['access_type' => 'offline', 'prompt' => 'consent select_account'])
->redirect();

How to configure My Web Application as SAML Test Connector (SP) using Onelogin?

I have added my web application into onelogin using SAML Test Connector.
In Configuration tab I have given the following values
Recipient : http://localhost:8080/em/live/pages/samlAuth/
ACS(Consumer) URL Validator* : ^
ACS (Consumer) URL* :http://localhost:8080/ws_em/rest/accounts/consume-saml
Login URL : http://localhost:8080/ws_em/rest/accounts/produce-saml
Where http://localhost:8080/ws_em/rest/accounts/produce-saml creates an SAML Request by taking IssuerUrl, SAML EndPoint Copied From Onelogin SSO Tab and ACS url as http://localhost:8080/ws_em/rest/accounts/consume-saml.
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/produce-saml")
public com.virima.em.core.Response SAMLAuthentication(){
com.Response resp = new com.Response();
AppSettings appSettings = new AppSettings();
appSettings.setAssertionConsumerServiceUrl(ACSUrl);
appSettings.setIssuer(IssuerUrl));
AccountSettings accSettings = new AccountSettings();
accSettings.setIdpSsoTargetUrl(IdpSsoTargetUrl);
AuthRequest authReq = new AuthRequest(appSettings,accSettings);
Map<String, String[]> parameters = request.getParameterMap();
String relayState = null;
for(String parameter : parameters.keySet()) {
if(parameter.equalsIgnoreCase("relaystate")) {
String[] values = parameters.get(parameter);
relayState = values[0];
}
}
String reqString = authReq.getSSOurl(relayState);
response.sendRedirect(reqString);
resp.setResponse(reqString);
return resp;
}
http://localhost:8080/ws_em/rest/accounts/consume-saml calls is supposed to take my SAML request and do the authentication . Here I am using the certificate generated in Onelogin SSO Tab
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/consume-saml")
public com.onelogin.saml.Response SAMLAuthenticationResponse(){
com.onelogin.saml.Response samlResponse = null;
String certificateS ="c"; //Certificate downloaded from Onelogin SSO Tab
AccountSettings accountSettings = new AccountSettings();
accountSettings.setCertificate(certificateS);
samlResponse = new com.onelogin.saml.Response(accountSettings,request.getParameter("SAMLResponse"),request.getRequestURL().toString());
if (samlResponse.isValid()) {
// the signature of the SAML Response is valid. The source is trusted
java.io.PrintWriter writer = response.getWriter();
writer.write("OK!");
String nameId = samlResponse.getNameId();
writer.write(nameId);
writer.flush();
} else {
// the signature of the SAML Response is not valid
java.io.PrintWriter writer = response.getWriter();
writer.write("Failed\n");
writer.write(samlResponse.getError());
writer.flush();
}
return samlResponse;
}
I am getting this error
Federation Exception: Malformed URL. Please contact your
administrator.
It doesn't seem to come inside the ACS url I have inside my app.
Is there any mistakes in my configuration ? Or is there a better way to do this ?
ACS is Assertion Consumer Service, is the endpoint that process at the SP the SAMLResponse sent by the Identity Provider, so the http://localhost:8080/ws_em/rest/accounts/consume-saml process and validate the SAMLResponse.
Do you have verbose trace error? Malformed URL must be that the code is trying to build a URL var with a non URL string.
BTW, You are using the java-saml toolkit, but the 1.0 version instead the recommended 2.0.
I highly recommend you to use the 2.0 and before work on your integration, try to run the app example

Identity server claims asp.net API

I'm currently writing an angular application that first authenticates against think texture identityserver3.
This works fine, and I receive the bearer token without any issues.
When I use my token on an call to my API, I'm authenticated. I can see my userid, but have lost my claims (username, roles,...).
What do I have to do for transferring my claims with my token, or getting the roles from the identityserver?
You can tell Identity Server to include specific claims in an access token by adding that claim to your API's Scope.
Example:
var apiScope = new Scope {
Name = "myApi",
DisplayName = "My API",
Type = ScopeType.Resource,
Claims = new List<ScopeClaim> {
new ScopeClaim("myClaimType")
}
};
You can also use the AlwaysIncludeInIdToken property of ScopeClaim to include the claims in identity tokens as well as access tokens.
See https://identityserver.github.io/Documentation/docsv2/configuration/scopesAndClaims.html for more info.
We are doing something very similar using MS Web API 2 and a Thinktecture Identity Server v3.
To verify the user's claims we created an Authentication Filter, and then called the Identity server directly to get the user's claims. The bearer token only grants authentication and it is up to the API to get the claims separately.
protected override bool IsAuthorized(HttpActionContext actionContext)
{
string identityServerUrl = WebConfigurationManager.AppSettings.Get("IdentityServerUrl") + "/connect/userinfo";
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = actionContext.Request.Headers.Authorization;
var response = httpClient.GetAsync(identityServerUrl).Result;
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
Dictionary<string, string> claims = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString.ToLower());
... Do stuff with your claims here ...
}
}
}

Resources