Azure OAuth to function app issues - azure

I have a very basic function app that takes a GET and returns some static text. Eventually I would like it to write a POST body to a queue but to keep it simple the function just returns text. If I keep auth off, I can load the url and get a response in my browser or postman. If I enable aad auth within the function app and create a simple app reg then goto the site in my browser I get prompted for auth and I can login interactively; no worries so far.
I would like to access the function using a secret key for application usage with no interactive login, so within the app reg I go to Keys and generate one. This is where my problems start. If I use postman and configure oauth using my app id and key I can get a token, I have verified this also by doing a POST to https://login.microsoftonline.com//oauth2/token directly and noting the bearer token reply. However when I try an access my function app using the bearer token (either by manually adding an Authorization header or letting postman add it from the oauth 2.0 form) I am always denied with a 401 stating 'You do not have permission to view this directory or page.' when I do a GET to my function app. Can someone point me in the right direction? Thanks in advance.
Example reply from login url
{
"token_type": "Bearer",
"expires_in": "3599",
"ext_expires_in": "0",
"expires_on": "1525312644",
"not_before": "1525308744",
"resource": "https://<siteaddress>.azurewebsites.net/",
"access_token": "eyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx..etc..."
}
Response from get against function app with token
GET /api/t2 HTTP/1.1
> Host: <sitename>.azurewebsites.net
> Authorization: Bearer eyxxxxxxxxxxxxxxxxxxxxxxxxxxxx.....etc....
> Accept: */*
< HTTP/1.1 401 Unauthorized
< Content-Length: 58
< Content-Type: text/html
< WWW-Authenticate: Bearer realm="<sitename>.azurewebsites.net" authorization_uri="https://login.windows.net/<tenantid>/oauth2/authorize" resource_id="<app reg id>"
< X-Powered-By: ASP.NET
< Date: Thu, 03 May 2018 01:12:43 GMT

I believe you're mixing Azure AD integration with function keys (API key authorization).
The latter is a self-contained authorization mechanism and works by appending
?code=<func-key-from-portal>
to the function URL, or by passing a
x-functions-key: <func-key-from-portal>
header with every request to the function. No OAuth is involved when using function keys.
Example:
GET /api/get-issues HTTP/1.1
Host: {funcapp}.azurewebsites.net
User-Agent: ajax-library-of-the-day
x-functions-key: rkW0PqT.....zcUBQ==
or
GET /api/get-issues?code=rkW0PqT.....zcUBQ== HTTP/1.1
Host: {funcapp}.azurewebsites.net
User-Agent: ajax-library-of-the-day

Related

How to debug Bearer error="invalid_token"

We are building an application with a SPA front end and an API backend.
We are using the MSAL authentication library, the frontend and backend are registered as applications in Azure AD.
We get a HTTP 401 error.
To try and debug the problem, we have taken the token from the SPA application, and put it in jwt.io, it looks fine. We have also tried sending the request from Postman, with the bearer token. Still same problem.
Is there a way to find out in what way the token is invalid?
A simple check to get some clue why the token is not accpted, is to set this flag to true in AddJwtBearer:
.AddJwtBearer(opt =>
{
opt.IncludeErrorDetails = true;
...
Doing so, will include why it was rejected in the WWW-Authenticate response header:
HTTP/1.1 401 Unauthorized
Date: Sun, 02 Aug 2020 11:19:06 GMT
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"
The second step is to check the logs from the AddJwtBearer handler.

What value to give for "scope" option when I want to access an Azure function API that is protected with Azure AD in Postman

I am working on an Azure Function API that is protected by Azure AD, it's working fine when I request it with browser once I logged in with a valid account, but when I tried with postman it still shows unauthorized access,
I have got an access token to send with the request, but for the scope property I have given is this value, https://graph.microsoft.com/.default which I think might be the problem. But not sure what I am doing wrong and what to put in the scope field in the get new access tokenoption in postman to authenticate to my API.
HTTP Request Postman Making
GET /api/events/active HTTP/1.1
Host: moya-backend-ascentic.azurewebsites.net
Authorization: Bearer ****IHqMgweN86fDnyL4jvz9P6ZllpjjD9t***
User-Agent: PostmanRuntime/7.13.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 655e0672-4928-409e-a709-841a92ee6f14,22cbf978-f196-4099-ae10-d162d3068507
Host: moya-backend-ascentic.azurewebsites.net
accept-encoding: gzip, deflate
Connection: keep-alive
cache-control: no-cache
The scope should be: your-api-client-id/.default.
Replace your-api-client-id with the client id/application id for your API app in Azure AD.
Now since browser-based login seems to be working, you may have setup the wrong kind of authentication on the API.
If the token still doesn't work, you'll need to setup JWT authentication on the app instead of browser/cookie based.
If you are using v2.0 endpoint, the scope should be {your_client_id}/.default. Just like #juunas said.
If you are using v1.0 endpoint, you only need resource parameter. The resource should be {your_client_id}
Note: If you are using the 'get new access token' function in postman, the Access Token URL should be https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token

"Authorization has been denied for this request" when accessing Web API deployed in Azure

Following on from this question:
AADSTS50013: Assertion audience claim does not match the required value
I've now successfully got the web apps running with this security model:
SPA application using adal.js/adal_angular.js to authenticate via AAD.
Returned token is passed to web api [API1] that runs on the same machine.
That web api gets a new token on behalf of the user to access a downstream API [API2].
The downstream api gets a new token on behalf of the user to access another downstream API [API3].
Now, when I have [API2] running locally, this is all working.
However, when I deploy that web app to my Azure subscription, and attempt to call it (without changing anything else other than the url in the REST API call from [API1]), I get the following:
{"Message":"Authorization has been denied for this request."}
There doesn't appear to be any other error details returned or in the Fiddler trace. Comparing the jwt token payloads between the call that works and the one that doesn't, doesn't reveal much. They appear the same other than the expiry claims and the "aio" (not sure what that is).
The only change is the URL of the deployed web app (from http://localhost:8080/ to http://mywebappname.azurewebsites.net/)
Note that the web app is deployed into a different AD tenant to the one where the app registrations and [API3] are located, but I didn't think this mattered.
Any thoughts out there on what I might need to change when I deploy, or how to troubleshoot this further?
Update: Request works with Curl
Making the same request using curl is working:
curl -H "Authorization: Bearer ey..." http://mywebapi.azurewebsites.net/api/resource
So the issue appears to be how I'm making the request in my C# code? Comparing the headers in Fiddler, I don't see any difference.
This is the Fiddler trace from curl that is working:
GET http://mywebapi.azurewebsites.net/api/resource HTTP/1.1
Host: mywebapi.azurewebsites.net
User-Agent: curl/7.46.0
Accept: */*
Connection: Keep-Alive
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJ<snip>
This is the Fiddler trace from my code that is not working:
GET http://mywebapi.azurewebsites.net/api/resource HTTP/1.1
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJ<snip>
Accept: */*
User-Agent: RestSharp/100.0.0.0
Host: mywebapi.azurewebsites.net
Accept-Encoding: gzip, deflate
Here is the request from C#:
var restClient = new RestClient(serviceUrl) { Timeout = timeout};
var restRequest = new RestRequest(apiEndpoint, Method.GET);
var bearerToken = $"Bearer {securityToken}";
restRequest.AddParameter("Authorization", bearerToken, ParameterType.HttpHeader);
var response = restClient.Execute(restRequest);
On the Azure web site logs, I can see that the authentication type for the successful curl request is "JWT", however for the failed requests from my code they are "anonymous".
Somehow the header must be being stripped despite it showing up correctly in the Fiddler trace? Is this possible?
In an unrelated issue, I had to delete all untrusted certificates from my machine (Internet Options->Content->Certificates).
And I noticed after doing this, my problem was resolved. It was a very long list of certificates, so I don't know which one(s) were causing the problem, or why.
Given the lack of responses, its obviously a very obscure issue, but unfortunately we didn't get to the bottom of it. If it occurs again, I can be a bit more methodical when I do it.

Getting a DocuSign access token for an SSO user

I'm trying to get access tokens for users in order to use the iOS SDK for integrating in-person signings.
Our DocuSign users are set up as Single sign-on. We have a non-SSO, API user configured with the user settings apiAccountWideAccess and allowSendOnBehalfOf enabled.
I request an access token for the non-SSO, API user as follows:
POST /restapi/v2/oauth2/token HTTP/1.1
Host: demo.docusign.net
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
grant_type=password&client_id=<client_id>&scope=api&username=<useranme>&password=<password>
This results in the following response:
{
"access_token": "<access-token>",
"token_type": "bearer",
"scope": "api"
}
I then use the access token from the above response to try to get an access token for an SSO user as follows:
POST /restapi/v2/oauth2/token HTTP/1.1
Host: demo.docusign.net
Authorization: Bearer <access-token-from-response-above>
Accept: application/json
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
grant_type=password&client_id=<client_id>&username=<email-address-of-sso-user>&password=&scope=api
This results in the following response:
{
"errorCode": "UNSPECIFIED_ERROR",
"message": "Object reference not set to an instance of an object."
}
I'm following the documentation here (Obtaining access_tokens for Other Account Users).
Is it possible to get access tokens for the REST API on behalf of SSO users?
Unfortunately you can not use the API as a SSO enabled user at this time.
If you need to use the API as a SSO user, you have to have that user on the SSO Exempt list.
Generally integrations use Send On Behalf Of to authenticate as the API user (that on the exempt list) and makes the calls on behalf of the users who have SSO enabled.
The error doesn't indicate the actual issue and I've filed a bug with DocuSign Support to get that portion addressed.

Clarification on REST APIs around user management in an account

I recently created a docusign developer account and integrator key and was playing with docusign REST APIs and had some questions
I can retrieve full list of users under my account by using following REST call.
https://demo.docusign.net/restapi/v2/accounts/<accountid>/users?additional_info=true
However if I try and retrieve a specific user (other than the one I am passing in my X-Docusign-authentication) header i get http 400 error with message that the "Invalid UserId. UserId specified in request uri does not match authenticated user"
https://demo.docusign.net/restapi/v2/accounts/<accountid>/users/0d51a699-b17a-48b7-95b6-1e9e9806deb6
In both cases i am sending the following header.
X-DocuSign-Authentication: <DocuSignCredentials><Username>{0}</Username><Password>{1}</Password><IntegratorKey>{2}</IntegratorKey></DocuSignCredentials>
I am surprised that while I can read all users fine, I cannot just read one specific user. Surely it doesn't seem like this is security thing since I can read the user via one API but not the other using the same auth token.
What am i missing?
I guess I can go the route of SOBO (Send on behalf of functionality), but I wanted to confirm if above behavior is expected.
Update#1
: I went the SOBO approach and now i get a different error (USER_NOT_ACCOUNT_ADMIN) as shown below
GET /restapi/v2/accounts/{accountid}/users/0fe29a55-5564-42a9-b09d-cbe699db13dd HTTP/1.1
Authorization: bearer {token for authenticating user}
X-DocuSign-Act-As-User: {operating user's email}
Accept: application/json
Host: demo.docusign.net
Connection: Keep-Alive
HTTP/1.1 401 Unauthorized
Cache-Control: no-cache
Content-Length: 100
Content-Type: application/json; charset=utf-8
Date: Thu, 17 Oct 2013 21:18:32 GMT
Strict-Transport-Security: max-age=7776000; includeSubDomains
{
"errorCode": "USER_NOT_ACCOUNT_ADMIN",
"message": "User is not an account administrator."
}
I also tried the second SOBO approach of getting a oauth token for the operating user but got back http 400 error with below message
{
"error": "invalid_request",
"error_description": "An OAuth2 error occurred."
}
So while i can get an oauth token for the autheitcating user, i am not able obtain oauth token for the operating user or act on their behalf.
I have made sure that authenticating user is "Account Administrator" and has both "apiAccountWideAccess" and "•allowSendOnBehalfOf" set to true. The only thing set to "false" is "canSendAPIRequests". My account id in sandbox environment is "601565a7-e9c7-463b-9d7c-622aed905ea8" Any ideas?
Update#2
Instead of generating oauth tokens on behalf of both authenticating user and operating user, i tried passing below header and i can finally get another user's profile and update another user's profile.
X-DocuSign-Authentication: <DocuSignCredentials><SendOnBehalfOf>{operating userid}</SendOnBehalfOf><Username>{authenticating userid}</Username><Password>{authenticating user's password}</Password><IntegratorKey>{developer's integrator key}</IntegratorKey></DocuSignCredentials>
Great!
So here is status of what works and what doesn't.
Works with no SOBO header anywhere
GET /restapi/v2/accounts/357938/users?additional_info=true // Read all users
GET /restapi/v2/accounts/357938/users?email=someshchandraatwork#gmail.com&additional_info=true // Read single user by email
POST /restapi/v2/accounts/357938/users // Add users
DELETE /restapi/v2/accounts/357938/users // Close users
*Works with SOBO in X-DocuSign-Authentication header
PUT /restapi/v2/accounts/357938/users/74a021e1-3090-4843-b9ab-cceb7cd119f4/profile // Update user's profile
GET /restapi/v2/accounts/357938/users/74a021e1-3090-4843-b9ab-cceb7cd119f4/profile // Read user's profile
Still doesn't work with or without SOBO**
GET /restapi/v2/accounts/357938/users/74a021e1-3090-4843-b9ab-cceb7cd119f4/settings
GET /restapi/v2/accounts/357938/users/74a021e1-3090-4843-b9ab-cceb7cd119f4
In both not working cases i get following error
Without SOBO i get error that userid doesn't match autheitcating user.
With SOBO i get error than user is not an account admin
I would very much appreciate any help in resolving the not working cases. I can provide more detaisl as needed.
Secondly I want to implement a scenario where I can deactivate a user in an account so they can no longer log into docusign. And subsequently I would like to enable that user back again with same permission that they had before they were disabled.
I see that user has a "userStatus" field and was wondering if I can use that to de-activate the user and then re-activate if needed. If this is supported then what value would correspond to deactivating the user?
The other thing I note is that on DELETE a user, the user is only soft-deleted since I can still query the user with the status "CLOSED". That would solve my "deactivate" problem. However I was not sure if there is a way to reactivate them back again after the user has been "closed"?
I believe this might be an account administration issue. I'm not sure why but I looked at your account settings from DocuSign's side and I saw the "Send on Behalf of" was not checked on your account- which is weird since it seems you have access to the setting in your Console -> Preferences settings.
But in either case I'm wondering if the setting I just enabled on your account has solved your issue, as it might have.
I'm also not sure about the user info portion of your question, let me see if I can come up with anything for that and I'll edit my answer once I do.
In reply to Erign's post above.
Anyone who is an account admin should be able to modify/add/delete users in an account. I'm not sure if your SOBO steps are correct though, can you confirm that you are following THESE STEPS exactly? If so, at which step do you run into issues or get an error?– Ergin5 mins ago
Yes i am following those steps. I am able to generate oauth token for the autheitcating user , but get an error when doing the same for the operating user. Below are my request and responses.
1. REQUEST FOR AUTH TOKEN FOR AUTHENTICATING USER
POST /restapi/v2/oauth2/token HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: demo.docusign.net
Content-Length: 139
Expect: 100-continue
Connection: Keep-Alive
grant_type=password&client_id={integratorykey}&username={authenticating user's email}&password={authenticating user's password}&scope=api
RESPONSE
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 100
Content-Type: application/json; charset=utf-8
Date: Thu, 17 Oct 2013 22:57:26 GMT
Strict-Transport-Security: max-age=7776000; includeSubDomains
{
"access_token": "{authenticating user's token}",
"token_type": "bearer",
"scope": "api"
}
2. REQUEST FOR AUTH TOKEN FOR OPERATING USER
POST /restapi/v2/oauth2/token HTTP/1.1
Authorization: bearer {authenticating user's token}
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: demo.docusign.net
Content-Length: 137
Expect: 100-continue
grant_type=password&client_id={integratorykey}&username={operating user's id}&password={empty}&scope=api
RESPONSE
HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Content-Length: 87
Content-Type: application/json; charset=utf-8
Date: Thu, 17 Oct 2013 22:57:29 GMT
Strict-Transport-Security: max-age=7776000; includeSubDomains
{
"error": "invalid_request",
"error_description": "An OAuth2 error occurred."
}

Resources