Azure AD Auth for Mobile Apps? - azure

I created a new mobile app to get consumed in my Xamarin.iOS app. My app doesnt have any registered user, all I need is to securely access the mobile app service api in my ios app.
After 10 hours of trying, I still couldn't figure a way to get his to work.
I've created a new mobile app, turned on Authentication / Authorization in setting(Azure Portal) and created a new Azure Active directory app.
I've secured my [MobileAppController] with [Authorize] tag.
To test I've requested a token
Method: POST
URL : https://login.microsoftonline.com/mytenant.onmicrosoft.com/oauth2/token
grant_type : client_credentials
client_id : {one from AD section for the app}
client_secret : {one from AD section for the app}
I've received a token but using it to access(POSTMAN app)
https://mytestmobileapp.azurewebsites.net/api/values
with headers
Authorization : Bearer {token}
is giving me a
"message": "Authorization has been denied for this request."
Any help would be appreciated.
Thank you ...

I answered on my blog post but I am also putting this here for anyone to see.
Why do you want to call the endpoint directly? The SDK client should handle all of this (as seen on their tutorial: https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-xamarin-ios-get-started-users/)
I do not think it is a good idea to re-implement the wheel by calling directly AD. There is a callback mechanism for the server to get that token from AD and I think this is what is missing here.

Have you looked at the examples at GitHub for Azure ActiveDirectory Library for ObjectiveC?
https://github.com/AzureAD/azure-activedirectory-library-for-objc
Some great examples and resources here that may help you :)

Ok finally after hours of terrible frustration I've found the answer. Thanks to the comments # https://github.com/Azure/azure-mobile-apps-ios-client/issues/14
I've setup Streaming logs and detailed error messages to figure out whats going on and I found this to be the error.
2016-01-18T20:06:31 PID[7448] Warning JWT validation failed: IDX10214: Audience validation failed. Audiences: 'https://quicktestmobileauthapp123.azurewebsites.net'. Did not match: validationParameters.ValidAudience: '8649d624-47ce-447f-9a5e-xxxxxxxxxxxx' or validationParameters.ValidAudiences: 'http://quicktestmobileauthapp123.azurewebsites.net'.
Then I realized I have to pass in resource when requesting the token.
My new token request
Method: POST
URL : https://login.microsoftonline.com/mytenant.onmicrosoft.com/oauth2/token
grant_type : client_credentials
client_id : {one from AD section for the app}
client_secret : {one from AD section for the app}
resource : {clientId from the AD section}
Then token I've received from the above method worked fine without any issues. Azure streaming logs are amazing.
UPDATE
I've created a new question with answer going through a step by step explanation. How to add simple authentication to azure mobile/web apps with Azure Active Directory?

Related

Azure B2C React SPA dose not providing access token

I am working on my first project of connecting Azure B2C with MERN App. I wanted to Sign In using Azure B2C and authorise my web API using the Access Token.
I configured everything and applied configurations to this sample React tutorial provide by their documentation.
The problem arises while calling the Web API. The Web API call are sending without any token. When I check the code, acquireTokenSilent function returning empty accessToken from response.
instance.acquireTokenSilent({
scopes: protectedResources.apiHello.scopes,
account: account
}).then(async (response) => {
console.log(response)
The Request is:
Even though I looked many forums and Microsoft technical forums, no answer is not working.
But what I noticed is, it is requesting for grant_type: authorization_code but am not seeing access token in the response. Posting here the API call, request and response.
The Response is producing id_token but not access token,
I gave grant permission in the SPA App permission for task.read scope. I tried everything but I am still receiving the access token as empty. How could I fix this issue?
I tried to reproduce the same in my environment and got below results:
I registered one Azure AD B2C application for app1 and added scopes(task.read) as below:
Now I created one SPA registration and added API permissions by granting consent like this:
I created Sign up and sign in policy and ran the user flow as below:
Please Check authentication and access token and id token:
I signed in as user it gave me auth code in address bar.
https://<tenant name >.b2clogin.com/<tenant name> .onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_susi&client_id=<app id>&nonce=defaultNonce&redirect_uri=https://jwt.ms&scope=openid%20https%3A%2F%2F<tenant name>.onmicrosoft.com tasks.read&response_type=code&prompt=login&code_challenge_method=S256&code_challenge=<challenge paramater>
I generated the access token via Postman with commands like this:
POST https://tenant.b2clogin.com/tenant.onmicrosoft.com/policy/oauth2/v2.0/token
grant_type: authorization_code
client_id: SPA_appid
scope: https://tenant.onmicrosoft.com/app1/task.read
redirect_uri: redirect_uri
code: code
code_verifier: code_verifier
Postman
When I decode the token i getting scp in jwt .ms

SecurityTokenInvalidSignatureException: IDX10511

Looking for some answer. First time using Azure AD for authentication on ASP.Net Core and we have registered the app on azure for both my local and Dev-Server. Its working running on my laptop but after deploying to Dev server and changing the Client ID Value, it keeps giving me this error
*SecurityTokenInvalidSignatureException: IDX10511: Signature validation failed. Keys tried: 'System.Text.StringBuilder'.
kid: 'System.String'.
Exceptions caught:
'System.Text.StringBuilder'.
token: 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken'.
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(string token, TokenValidationParameters validationParameters)
Exception: An error was encountered while handling the remote login.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()*
Thank you in advance.
Danny
Thank you #User 45323833 posting your suggestion as an answer to help other community members.
" Solution from Microsoft: This problem caused due to your app registration:
May you have defined a scope from Graph API: User.Read User.ReadBasic.All Mail.Read
If a scope will be set from Graph API, the token can just be validated from Graph!
You can see that in jwt.io. If the aud is like "00000003-0000-0000-c000-000000000000" the token is from Graph.
To solve the problem please follow the below steps :
To protect our own custom API, you have to register an application to represent it on Azure AD and obtain an access_token/id_token for it.
Section - Expose an API: Create a new scope: name = access_as_user
Section - API permissions: Add a new permission for your registered application and your scope access_as_user
Section - Manifest: Change entry "accessTokenAcceptedVersion" from null to 2
Check the new token from azure with jwt.io. If the aud is equal the registered application id the token can be successfully validated."
For more information please refer this GitHub issue IDX10511: Signature validation failed. Keys tried: & Microsoft Documentation: Azure AD authentication with ASP.Net core web application

Get Azure AD Basic User Profile

I'm trying to get the users basic profile from Azure AD. I have a React Native app authenticating against a Native Azure AD App registration. The access_token I got from that request is used to authenticate against a Web app / Api. The user is shown the propper consent screen with the permissions I set in Azure AD.
Microsoft Graph API
Read all users' basic profiles
Sign in and read user profile
Windows Azure Active Directory
Read all users' basic profiles
Sign in and read user profile
(added both Graph API & AAD because I didn't know which one to use)
When I try and get the users profile through https://graph.microsoft.com/v1.0/users/me, with the access_token gotten from the previous request I get:
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {
"request-id": "00cdb708-bcf8-4b33-af21-14a046b16533",
"date": "2018-09-02T18:28:59"
}
}
}
The resource in my initial authentication request is the Web App / API's app id, and I don't think having 2 resources is an option (?).
What am I doing wrong, and what should I do to fix it? Thanks.
According to your descriptions, I assume you want to get the users profile, but get the error shows an invalid token.
Based on my test, the request URL that you posted is not correct.
It should be 'https://graph.microsoft.com/v1.0/me' or 'https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}'.
We can trouble shoot your problems as follows.
First, check request, if it has correct 'Authorization' field. This document shows that we need the Authorization field in the request headers.
Second, if you have added the Authorization field in the request headers, could you provide the main code that we can identify if problem is from there ?
While getting the access token add "resource" : "https://graph.microsoft.com/" and use that access token in header with Bearer than hit the url ---> https://graph.microsoft.com/me?api-version=1.6
Don't forget to add the resource while getting access token
Thank me later :P

Authorization_IdentityNotFound Error while accessing graph API

I have searched with the error which I found, Did not find any matching questions. So posting question. Appreciate if some one provides some pointers to proceed.
My goal is to access graph API in my desktop client. I have started using fiddler to experiment.
I have followed instructions provided at https://graph.microsoft.io/en-us/docs/authorization/app_only
registered Web APP using Application Registration portal using my Microsoft work account.
Provided 'Read all users' full profiles in Delegated permissions
Requested token and Used the token in Authorization header to call the graph API, Getting following error.
https://graph.microsoft.com/v1.0/users
119
{
"error": {
"code": "Authorization_IdentityNotFound",
"message": "The identity of the calling application could not be established.",
"innerError": {
"request-id": "4c3a7bc6-e3d8-453c-adc9-5a12fec3b0ee",
"date": "2016-05-11T00:46:23"
}
}
}
In my case, I got the same error after I used Quickstart (step 1), then configured automatically .net sample (step 2), then download the code sample (step 3) as shown in the picture below.
All steps was done successfully except step 3. Microsoft code generate, generate app id, and app secret in project successfully but the tenant was set to common in appsetting.json as seen in image below.
I thought it was a valid thing, but later found out that this caused the issue.
Solution:
I copied the Directory (tenant) ID, than replace common with tenant Id, and it worked. I am not sure if this is a bug in Azure Quickstart code generation.
This sample helped me understand the flows around app-only permissions.
https://blogs.msdn.microsoft.com/tsmatsuz/2016/10/07/application-permission-with-v2-endpoint-and-microsoft-graph/
Key takeaways for me:
Ensure you set up the app and specify the Application Permissions needed
Do have an admin grant the app permission to run against the relevant directory.
Get the relevant token:
Notice the scope in the request below is https://graph.microsoft.com/.default
POST https://login.microsoftonline.com/{tenantname}.onmicrosoft.com/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_id=6abf3364-0a60-4603-8276-e9abb0d843d6&client_secret=JfgrNM9CcW...&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
Use the token to request the relevant graph resource, eg:
GET https://graph.microsoft.com/v1.0/users/demouser01#[tenant-name].onmicrosoft.com/drive/root/children
Accept: application/json
Authorization: Bearer eyJ0eXAiOi
For me, I had not given admin consent. This is a critical step. My mistake was in thinking that by granting the app permissions, this was giving admin consent, but its not the same thing.
From step 3 on this site: https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service
I just pasted their call into a browser after filling in the tenant and client id, then signed in, and everything worked.
GET https://login.microsoftonline.com/{tenant}/adminconsent
?client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
&redirect_uri=http://localhost/myapp/permissions
while generating new access token, make sure to replace tenant_id with the actual tenant id
https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token
You'll find that this document is a better set of instructions for app-only apps.
There are two issues from your description that stand out.
You'll need to make the call with an X509 certificate for app-only flows.
You need to set up app scopes, rather than delegated scopes on your app - delegated scopes are for delegate flows rather than app-only flows.

Unsupported app only token issue in authenticating office365

I have followed this link https://msdn.microsoft.com/en-us/office/office365/howto/building-service-apps-in-office-365 to
set-up the Daemon or Server Application to Web API authentication method in Office365 to get access token.
The sample access token request is given below
POST https://login.microsoftonline.com/{tenant-id}/oauth2/token
grant_type : client_credentials
client_id : {clientId}
client_secret : {clientSecret}
resource : https://{tenant}.sharepoint.com
For Example:
https://login.microsoftonline.com/cae788bd-7a55-4fb5-9d1f-3aa5365e14a/oauth2/token
grant_type : client_credentials
client_id : 1dd0a211-06f1-4f6a-a232-b3a8dcab829b
client_secret : ZWtkWm9M5Ucx5j29UoXPy7GKG+Hu0eNdVFYO+lH761w=
resource : https://{tenant}.sharepoint.com
From the above api request, I am getting an access token, when I tried to create the folder or accessing any other api's from the above access token then it is
showing an error as "Unsupported app only token". I have tried to call this webservices to get this error:
PUT https://{tenant}.sharepoint.com/_api/v1.0/Files/{parent-id}/children/{folder-name}
Authorization : BearerBearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE
Content-Type : application/json
Accept : application/json
But previously we have used the same Daemon or Server Application to Web API authentication method in Office365 to get access token and it was working fine.
And we have used the accesstoken to access the office 365 API's but now it is showing error as "Unsupported app only token".
Manoj,
I got the App-only working in a WPF application for the Mail API, did you setup the certificate?
According to the blog you mention
Because of the broad access these kinds of apps enjoy, there is an additional requirement for the app to successfully obtain an access token. Instead of using a client ID and client secret, the app must use an X.509 certificate with a public/private key pair.
See this link how to set it up:
Performing app-only operations on SharePoint Online through Azure AD

Resources