How to add security to Azure Function? - authentication

I’m new at Azure. So i’ve developed a simple Web app in net core 6 which autenticathes with AZ AD.
I also add to my solución an azure function but the idea is to add JWT to it .
From azure portal i added, authentication but i dont know how to get a token to , for example, test it with postman.
Does someone know how to do this? I’ve Watch a lot of videos but still can’t get it .
Regards
i need help to add security to my az function and be able to add jwt to my web app and to try tokens from postman.

I tried to reproduce the same in my environment and got the results like below:
Create an Azure AD Application and add API permissions:
Generate the Auth-Code by using below Endpoint:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
client_id=ClientID
&response_type=code
&redirect_uri=RedirectURI
&response_mode=query
&scope=[https://management.azure.com/.default](https://management.azure.com/.default "https://management.azure.com/.default")
&state=12345
To generate the token, I used the below parameters:
GET https://login.microsoftonline.com/TenantId/oauth2/v2.0/token 
client_id:ClientID
client_secret:ClientSecret
scope:https://management.azure.com/.default
grant_type:authorization_code
redirect_uri:RedirectUri
code:code
By using the above generated access token, you can access Azure Function successfully like below:
GET https://management.azure.com/subscriptions/SubID/resourceGroups/RG/providers/Microsoft.Web/sites/funcapp/functions/function?api-version=2022-03-01

Related

Having problem Authorizing Authenticated user account in Web API

I'm using ASP.Net Core 6 to build a secured Web API.
HOW I BUILT IT
dotnet new webapi --auth SingleOrg --aad-instance https://login.microsoftonline.com/ --client-id <CLIENT ID> --domain company.onmicrosoft.com --tenant-id <TENANT ID> --calls-graph true -o GraphTestService
APP REGISTRATION OF WEB API
I added a Scope in the Export API "EmployeeRecord.Read"
APP REGISTRATION FOR CLIENT (Public Client)
Added permission for Graph API (User.Read)
Added permission "EmployeeRecord.Read"
HOW I GET TOKEN USING THE CLIENT
I'm using "InteractiveBrowserCredential".
Everything works fine up until the Web service tries to call Graph API. It throws MsalUIRequiredException.
Understandable, since I did not include any graph API permissions when I requested a token.
FINALLY, THE PROBLEM
When I inspect the Bearer token that's returned, it has the "EmployeeRecord.Read" scope. Ok, that's fine. The Web API authorizes it; but the token doesn't have any permissions for Graph API.
When I add a graph API permission to the scopes, I get
AADSTS28000: Provided value for the input parameter scope is not valid because it contains more than one resource. Scope api://<APP URI ID>/EmployeeRecord.Read https://graph.microsoft.com/User.Read offline_access openid profile is not valid.
If I only include the graph API permission, the Web API returns an Unauthorized error.
WHAT I'VE TRIED
In addition to playing with the scopes, I tried adding my client application to the Web API app registration under the "Expose an API / Add A client Application". This made no difference. No difference in token or errors.
You are trying to add scopes for 2 different resource ,the scope parameter cannot be used to specify permissions for multiple resources similar issue .
we recommend you to use MSAL libarry , MSAL will store tokens for you and refresh whenever token is expired. Just call acquireTokenSilent to get an access token silently, and if you get an error, call acquireToken (see details on error handling here: https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-handling-exceptions#msal-for-ios-and-macos-errors)
for more info please check similar issue
Thanks

Authenticate Google Cloud Function Call outside GCP Environment

I am trying to call a google cloud function on the In Contact Studio to fulfill a logic in my IVR Call, but I am unable to do that as I have closed public access to my cloud function, and now I am not getting a way how to authenticate the call.
I tried using the command gcloud auth print-identity-token to get a ID_TOKEN But this ID_TOKEN will be refreshed every time and I can't use this again and again, so is there any way that I can generate a ID_TOKEN every time I try to call this function using a simple API Call??
OR
Is there any other way to solve my problem?
Ways I have Tried :-
I have gone through this Documentation:- https://cloud.google.com/functions/docs/securing/authenticating#end-users
and I was using the access style of End-User But it is a way in which the access token was getting generated via login using browser, I want to do everything via code, cause it will be used as a backend code for IVR(call facility for assistance in various tasks), in this method also we get a access token and not a ID_TOKEN, whereas to invoke a function we need a ID_TOKEN and not a access token.
Secondly I tried the gcloud auth print-identity-token command on the google cloud shell where i was logged in with my google account so it generated the JWT token and I used it as a bearer token and the function worked, but how can I generate the token outside GCP or get the on frequent intervals via code.
I want a program way(NodeJS) of doing this and not a UI way, cause I need to attach this with backend of my program, and all the ways I have gone through on the internet have the only way is through UI, and none of them have a program way for outside GCP environment, so i need help on this scenario.
As John said, you can use the Google Doc code example to perform an URL call: The library generate a secure HTTP client to generate request to your endpoint.
If you want to generate the token and use it by yourselve, you can use this piece of code
const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth()
auth.getIdTokenClient("").then(client => {
client.idTokenProvider.fetchIdToken("audience").then(token => {
console.log(token)
})
})

Any luck in using AddMicrosoftIdentityWebApp in combination with IdentityServer4?

I'm trying to get Microsoft configured as an external login provider in Identityserver4.
I succeeded by following identity server's documentation with using AddMicrosoftAccount:
services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
microsoftOptions.ClientId = configuration["MicrosoftLoginProvider:ClientId"];
microsoftOptions.ClientSecret = configuration["MicrosoftLoginProvider:ClientSecret"];
});
However, I didn't have luck with getting single sign-out to work. The documentation is in line with Microsoft's documentation at https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins?view=aspnetcore-5.0.
However, if you follow the instructions to create an app in Microsoft Developer Portal (portal.azure.com), the sample code on that portal suggests a different way. The sample application that the portal generated for me (WebApp-OpenIDConnect-DotNet) is using AddMicrosoftIdentityWebApp:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
Since this application is working out-of-the-box including single sign-out, Iam wondering if this is the way I have to continue.
To my surprise, however, I can't find any doc/blogs about how to integrate this approach in IdentityServer4. I almost got it to work myself, but there are a few weird issues.
Can someone clarify if using AddMicrosoftIdentityWebApp is the way to go to add Microsoft as an external identity provider to Identityserver4?
Has someone succeeded in getting AddMicrosoftIdentityWebApp to work with IdentityServer4?
THanks for your help!
I figured how to get it to work.
Actually, only two things I had to do.
First, I had to remove OpenIdConnectDefaults.AuthenticationScheme in the call to AddAuthentication in the example code that Microsoft generated. So the code becomes:
services.AddAuthentication()
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
Then, in the code that reads the external identity from a temporary cookie, I had to use CookieAuthenticationDefaults.AuthenticationScheme. So, that code now reads as follows:
var authenticationResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
That was all.
After digging around I found this statement here:
Microsoft.Identity.Web is a simpler way to use Azure AD in ASP.NET Core web apps and web APIs.
It doesn't replace ASP.NET Identity in any way, it doesn't replace AddJwtBearer or AddCookie or any of the lower level primitives, but it does use and configure them correctly for Azure AD.
It doesn't work with non-Azure identity providers. It replaces AzureAD.UI and AzureADB2C.UI which are obsolete in .NET 5.0
So, the conclusion is that Microsoft.Identity.Web does not work outside Azure AD and hence not with IdentityServer.
If you do get it to work then let me know!

Xero - OAuth1 to OAuth2 migration

I started working with adding migration from OAuth1a to OAuth2 inside my application and i face some problems.
This is what I've done :
I updated my partner app just like it is described here https://developer.xero.com/documentation/oauth2/migrate (added Auth2.0 redirect , got client id and secret etc ...)
I implemented token migration exactly as it is done here https://github.com/XeroAPI/xero-net-oauth2-sampletokenmigration and it works fine when OAuth1 token is valid :)
But when it is invalid and I'm doing refresh (using app updated in step 1) and call ~/oauth/migrate endpoint (using access token that i just recived after refresh step) to get OAuth2 token. I'm reciving this error "You can only migrate an OAuth1.0a connection to an OAuth2.0 connection for the currently authorised app". Also same thing happen when i create new connection (using partner applications created in in step 1) and than try to migrate this access token to Auth2.0.
Can anybody point me what I'm doing wrong ?
That is the error returned when you try to migrate to a newly created app. Are you sure you are using the tokens from the same Partner app tile in your /myapps dashboard.
It should look something like this, once you've added the correct OAuth2 redirect uri and generated your secret.

passing credential in HttpWebRequest In UrabanCode Deploy

I am using HttpwebRequest to pull list of all Components from Urban-code Deploy to my application. I have used my own credential in the code(C#) to access it. It is working fine. Now, i have to use the Service account that my company has, in order to pass the credential. I tried using DefaultCredential and defaultNetworkcredential but getting same error--Unauthorized access. Any help!!! Thank u!!!
You got an answer on the UrbanCode forum here: https://developer.ibm.com/answers/questions/372586/authentication-using-service-account-without-admin/?smartspace=urbancode
You just need a user account in the system with permissions to access the data. Accessing data via REST API requires the same permissions as through the UI. There's no way to bypass that.