I have a V3 Bot, and from a Dialog I want to call an Azure Function which is locked down by Azure AD V1. I want to get a token from Azure AD and use this token to access the Azure Function.
I'm trying to use OAuthCard with an Azure AD provider, and setting the Resource URL to my Azure Function https://my-function-app.azurewebsites.net
When I sign in to the OAuthCard I get the error "The application named https://my-function-app.azurewebsites.net was not found in the tenant named 880fb54d-f717-4364-9a22-df9ac5c77f6d"
The Function App does live in that tenant. Below are the OAuth Connection Settings configured in the Bot Channel Registration.
Is it possible to use OAuthCard to call an Azure Function locked down by Azure AD?
I have a V3 Bot, and from a Dialog I want to call an Azure Function which is locked down by Azure AD V1. I want to get a token from Azure AD and use this token to access the Azure Function.
If possible, you can directly make request to acquire an access token for the https://my-function-app.azurewebsites.net from you bot application, like below:
//Acquire token
var client = new RestClient($"https://login.microsoftonline.com/{tenantId}/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}&resource={resource}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(response.Content);
var access_token = tokenResponse.access_token;
TokenResponse class:
public class TokenResponse
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string ext_expires_in { get; set; }
public string expires_on { get; set; }
public string not_before { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
}
and then you can call/access your function app endpoint using that access token.
//Call Azure function using access token
var client2 = new RestClient($"https://xxxxfunction.azurewebsites.net/api/HttpTriggerFunc?code=CR9X9VsIattzWybmvasvpjAXfQU2feRuV3jXC6p/0B2AlFgl4LwPMw==");
var request2 = new RestRequest(Method.POST);
request2.AddHeader("Authorization", $"Bearer {access_token}");
request2.AddHeader("Content-Type", "application/json");
request2.RequestFormat = DataFormat.Json;
request2.AddBody(new { name = "Fei Han" });
IRestResponse response2 = client2.Execute(request2);
var funcResponse = JsonConvert.DeserializeObject<string>(response2.Content);
await context.PostAsync($"Response returned from Azure function: {funcResponse}.");
Test result:
Note:
For detailed information, please check "Service to service calls using client credentials".
Related
Below is the output from an error which is being generated whilst trying to authenticate credentials with Azure for allowing public access to a Power BI Embedded report:
It has initially displayed a pop to confirm that I want to give but after I have given permission the above error is displayed.
I have checked the credentials I have entered in the appsettings.json file and have confirmed that they are correct.
In the Startup.cs file I have added this section:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"), "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' '))
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
services.AddScoped(typeof(PowerBiServiceApi));
services.AddRazorPages()
.AddMicrosoftIdentityUI();
The error itself is being generated whilst acquiring the access token in the PowerBiServiceApi the code for which is provided below:
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using Microsoft.PowerBI.Api;
using Microsoft.PowerBI.Api.Models;
using Microsoft.Rest;
namespace NDTSM2.Services.Implementations.PowerBI
{
// A view model class to pass the data needed to embed a single report.
public class EmbeddedReportViewModel
{
public string Id;
public string Name;
public string EmbedUrl;
public string Token;
}
public class PowerBiServiceApi
{
private ITokenAcquisition tokenAcquisition { get; }
private string urlPowerBiServiceApiRoot { get; }
public PowerBiServiceApi(IConfiguration configuration, ITokenAcquisition tokenAcquisition)
{
this.urlPowerBiServiceApiRoot = configuration["PowerBi:ServiceRootUrl"];
this.tokenAcquisition = tokenAcquisition;
}
public const string powerbiApiDefaultScope = "https://analysis.windows.net/powerbi/api/.default";
// A method to get the Azure AD token (also known as 'access token')
public string GetAccessToken()
{
return this.tokenAcquisition.GetAccessTokenForAppAsync(powerbiApiDefaultScope).Result;
}
public PowerBIClient GetPowerBiClient()
{
var tokenCredentials = new TokenCredentials(GetAccessToken(), "Bearer");
return new PowerBIClient(new Uri(urlPowerBiServiceApiRoot), tokenCredentials);
}
public async Task<EmbeddedReportViewModel> GetReport(Guid WorkspaceId, Guid ReportId)
{
PowerBIClient pbiClient = GetPowerBiClient();
// Call the Power BI service API to get the embedding data
var report = await pbiClient.Reports.GetReportInGroupAsync(WorkspaceId, ReportId);
// Generate a read-only embed token for the report
var datasetId = report.DatasetId;
var tokenRequest = new GenerateTokenRequest(TokenAccessLevel.View, datasetId);
var embedTokenResponse = await pbiClient.Reports.GenerateTokenAsync(WorkspaceId, ReportId, tokenRequest);
var embedToken = embedTokenResponse.Token;
// Return the report embedded data to caller
return new EmbeddedReportViewModel
{
Id = report.Id.ToString(),
EmbedUrl = report.EmbedUrl,
Name = report.Name,
Token = embedToken
};
}
}
}
Does anyone have any ideas why the error is being generated (have looked for guidance but so far none of the advice has rectified the issue)?
Any help would be very much appreciated.
Further to original question:
Error Details:
Operation returned an invalid status code 'Unauthorized'
at Microsoft.PowerBI.Api.ReportsOperations.GetReportInGroupWithHttpMessagesAsync(Guid groupId, Guid reportId, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.PowerBI.Api.ReportsOperationsExtensions.GetReportInGroupAsync(IReportsOperations operations, Guid groupId, Guid reportId, CancellationToken cancellationToken)
at Microsoft.PowerBI.Api.ReportsOperationsExtensions.GetReportInGroup(IReportsOperations operations, Guid groupId, Guid reportId)
at NDTSM2.Services.Implementations.PowerBI.PbiEmbedService.GetEmbedParams(Guid workspaceId, Guid reportId, Guid additionalDatasetId) in C:\Users\cryof\Desktop\NDTMS4\Service\NDTSM2.SERVICES\Implementations\PowerBI\PbiEmbedService.cs:line 41
at NDTMS2.Web.Controllers.EmbedInfoController.GetEmbedInfo() in C:\Users\cryof\Desktop\NDTMS4\NDTMS2.WEB\Controllers\EmbedInfoController.cs:line 40
The line that is generating the error in the PbiEmbedService is this:
var pbiReport = pbiClient.Reports.GetReportInGroup(workspaceId, reportId);
Follow the sample here
// For app only authentication, we need the specific tenant id in the authority url
var tenantSpecificUrl = azureAd.Value.AuthorityUrl.Replace("organizations", azureAd.Value.TenantId);
// Create a confidential client to authorize the app with the AAD app
IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
.Create(azureAd.Value.ClientId)
.WithClientSecret(azureAd.Value.ClientSecret)
.WithAuthority(tenantSpecificUrl)
.Build();
// Make a client call if Access token is not available in cache
authenticationResult = clientApp.AcquireTokenForClient(azureAd.Value.ScopeBase).ExecuteAsync().Result;
Similar issue here. I have checked the answer and try to implement all the possible forms of link in my startup.cs class with the following code:
var idClient = ConfidentialClientApplicationBuilder.Create(appId)
.WithRedirectUri(redirectUri)
.WithTenantId(tenantId)
.WithClientSecret(appSecret)
.WithAuthority(Authority) // Authority contains the link as mentioned in the page(link attached above)
.Build();
I still get the similar error:
"OpenIdConnectMessage.Error was not null, indicating an error. Error: 'invalid_request'. Error_Description (may be empty): 'AADSTS50194: Application 'xxx-xxx-xxx-xxx-xxxx'(ASPNET-Quickstart) is not configured as a multi-tenant application. Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant.
Trace ID: xxx-xxx-xxx-xxx-xxxx
Correlation ID: xxx-xxx-xxx-xxx-xxxx
Timestamp: 2022-06-11 05:33:24Z'. Error_Uri (may be empty): 'error_uri is null'."
The combination of links I have used in variable Authority are the following: "https://login.microsoftonline.com/MY_TENANT_NAME" and "https://login.microsoftonline.com/MY_TENANT_ID"
I am being redirect to login page but after entering credentials OnAuthenticationFailedAsync method is being executed. This is the code of my startup class:
[assembly: OwinStartup(typeof(Web.Startup))]
namespace Web
{
public partial class Startup
{
// Load configuration settings from PrivateSettings.config
private static string appId = ConfigurationManager.AppSettings["ida:AppId"];
private static string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];
private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
private static string graphScopes = ConfigurationManager.AppSettings["ida:AppScopes"];
private static string tenantId = ConfigurationManager.AppSettings["ida:tenantId"];
private static string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]);
public static string Authority = "https://graph.microsoft.com/"+ tenantId;
string graphResourceId = "https://graph.microsoft.com/";
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = appId,
Authority = "https://login.microsoftonline.com/common/v2.0",
Scope = $"openid email profile offline_access {graphScopes}",
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
TokenValidationParameters = new TokenValidationParameters
{
// For demo purposes only, see below
ValidateIssuer = true
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailedAsync,
AuthorizationCodeReceived = OnAuthorizationCodeReceivedAsync
}
}
);
}
private static Task OnAuthenticationFailedAsync(AuthenticationFailedNotification<OpenIdConnectMessage,
OpenIdConnectAuthenticationOptions> notification)
{
notification.HandleResponse();
string redirect = $"/Home/Error?message={notification.Exception.Message}";
if (notification.ProtocolMessage != null && !string.IsNullOrEmpty(notification.ProtocolMessage.ErrorDescription))
{
redirect += $"&debug={notification.ProtocolMessage.ErrorDescription}";
}
notification.Response.Redirect(redirect);
return Task.FromResult(0);
}
private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
{
var idClient = ConfidentialClientApplicationBuilder.Create(appId)
.WithRedirectUri(redirectUri)
.WithTenantId(tenantId)
.WithClientSecret(appSecret)
.WithAuthority(Authority)
.Build();
string email = string.Empty;
try
{
string[] scopes = graphScopes.Split(' ');
var result = await idClient.AcquireTokenByAuthorizationCode(
scopes, notification.Code).ExecuteAsync();
email = await GraphHelper.GetUserDetailsAsync(result.AccessToken);
}
catch (MsalException ex)
{
System.Diagnostics.Trace.TraceError(ex.Message);
}
notification.HandleResponse();
notification.Response.Redirect($"/Account/SignInAzure?email={email}");
}
private static string EnsureTrailingSlash(string value)
{
if (value == null)
{
value = string.Empty;
}
if (!value.EndsWith("/", StringComparison.Ordinal))
{
return value + "/";
}
return value;
}
}
}
My application is for single tenant so please don't suggest me to change the setting and make it for multi-tenant.
Please check below points:
After trying to change it to specific tenant i.e.;
After changing to Ex: - https://login.microsoftonline.com/contoso.onmicrosoft.com (or tenant id),
please save changes ,refresh portal / everything and try again.
If still it shows the error , check if the Application is registered to the Azure AD Tenant as Multi Tenant Application.
Then if it still remains check if the account is actually on Azure
AD ,as this error can occur when the user credentials you are trying
to use does not belong to the same tenant where the application is
actually registered in.
If it is different tenant and you are trying to access from different
account, then you may need to change its supported account types to
any organizational directory or you need to check for correct
credentials. If not check everything or create a new app registration
.
Also please check this "Use a tenant-specific endpoint or configure the application to be multi-tenant" when signing into my Azure website for possible
ways to solve the issue.
Else you can raise a support request
References:
msal - MsalException: Applicationis not configured as a multi-tenant
application. Android - Stack Overflow
Use single-tenant Azure AD apps with Microsoft Graph Toolkit -
Waldek Mastykarz
I'm attempting to acquire a token from AD or Azure AD but my call to AcquireTokenByIntegratedWindowsAuth results in this:
MSAL.Desktop.4.14.0.0.MsalClientException:
ErrorCode: parsing_wstrust_response_failed
Microsoft.Identity.Client.MsalClientException: An error occurred while sending the request.
---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
---> System.ComponentModel.Win32Exception: The system cannot contact a domain controller to service the authentication request. Please try again later
According to the team that registered my app in Azure I'm a public client and I've got rights to use 'user.read'
Any idea what could be up so that I can communicate something back to our firm's Azure team. It could be my fault, their fault or MS's fault, I'd just like to know who to complain to. Most of the code is generated by the Azure portal, I just changed the call to AcquireTokenInteractive to AcquireTokenByIntegratedWindowsAuth since my final goal is to silently get the token all the time.
public partial class MainWindow : Window
{
string graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me";
string[] scopes = new string[] { "user.read" };
public MainWindow()
{
InitializeComponent();
}
private async void CallGraphButton_Click(object sender, RoutedEventArgs e)
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
AuthenticationResult authResult = null;
var app = App.PublicClientApp;
ResultText.Text = string.Empty;
TokenInfoText.Text = string.Empty;
var accounts = await app.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
try
{
authResult = await app.AcquireTokenSilent(scopes, firstAccount)
.ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
authResult = await app.AcquireTokenByIntegratedWindowsAuth(scopes)
.ExecuteAsync(CancellationToken.None);
}
catch (MsalException msalex)
{
ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
}
}
public partial class App : Application
{
static App()
{
_clientApp = PublicClientApplicationBuilder.Create(ClientId)
.WithAuthority($"{Instance}{Tenant}")
.WithDefaultRedirectUri()
.Build();
TokenCacheHelper.EnableSerialization(_clientApp.UserTokenCache);
}
private static string ClientId = "<My Client ID>";
private static string Tenant = "<Our Tenant ID>";
private static string Instance = "https://login.microsoftonline.com/";
private static IPublicClientApplication _clientApp ;
public static IPublicClientApplication PublicClientApp { get { return _clientApp; } }
}
Based on https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Integrated-Windows-Authentication, there are a number of constraints surrounding the AcquireTokenByIntegratedWindowsAuth method.
If you are testing with your own user account, consent must be granted to the application for your account. Also, 2FA cannot be enabled when using this Auth flow.
For other users, they will need to consent to the application accessing their account details, or the tenant admin must grant consent across the tenant using the Grant admin consent for Tenant button in the portal.
This flow only applies to "federated users" (e.g. created in AD rather than AzureAD).
This flow is targeted primarily at desktop applications. It only works with .net desktop, .net core and Windows Universal Apps.
I am trying to send permissions for documentdb for a specific user from my azure server to my client app, which are xamarin forms.
On server side everything looks good and I can see users specific permissions and token.
But when permissions are received in the client, the token is stripped away, why?
I am new with documentdb so hopefully it is just me.
I am using an Azure Mobile App service as backend.
My backend controller returns an object holding properties for documentdb database including a list of permissions for the user.
public class DbConfig
{
public string DatabaseName { get; set; }
public string CollectionId { get; set; }
public string EndpointUri { get; set; }
public IList<Permission> Permissions { get; set; }
}
I create a permission for a user for the entire collection if not already created.
public async Task<Permission> CreatePermissionAsync(string resourceLink, string userLink, PermissionMode mode, string resourcePartitionKey = null)
{
try
{
Permission permission = new Permission
{
Id = Guid.NewGuid().ToString("N"),
PermissionMode = mode,
ResourceLink = resourceLink
};
if (resourcePartitionKey != null)
{
permission.ResourcePartitionKey = new PartitionKey(resourcePartitionKey);
}
var result = await client.CreatePermissionAsync(userLink, permission);
DbConfig.Permissions.Add(result);
return result;
}
catch (Exception e)
{
Trace.WriteLine($"##### Exception: {e}");
throw;
}
}
I retrieve permissions for a user with this method.
public List<Permission> GetPermissionsForUserPermissionLink(User user)
{
var permFeed = client.CreatePermissionQuery(user.PermissionsLink);
List<Permission> permList = new List<Permission>();
foreach (Permission perm in permFeed)
{
permList.Add(perm);
DbConfig.Permissions.Add(perm);
}
return permList;
}
On the client side in my Xamarin forms app i use this call to my custom controller in the backend.
var parameters = new Dictionary<string, string> { { "userid", Settings.AzureUserId } };
dbConfig = await client.InvokeApiAsync<DbConfig>("Settings", HttpMethod.Get, parameters);
When i look at the permissionlist in the dbConfig object the token for a permission is null. My thought was that I could instantiate a documentdb client based on the permissionslist but it fails.
public void CreateDocumentDbClient(DbConfig config)
{
client = new DocumentClient(new Uri(config.EndPointUri), config.Permissions);
collectionLink = UriFactory.CreateDocumentCollectionUri(config.DatabaseName, config.CollectionId);
IsInitialized = true;
}
EDITS MADE FROM ANSWER
Just for finish up upon question.
I created a custom class holding both Permission and Token
public class PermissionCustom
{
public Permission Permission { get; set; }
public string Token { get; set; }
}
This makes it possible to create a documentdb client like this:
client = new DocumentClient(new Uri(config.EndPointUri), config.Permissions[0].Token);
So far so good :-) but it doesn't makes it easier to secure your database considering users could have many permissions for different resources. Even though it is properly to make it more secure, the token is readonly in the first place.
According to your code, I have checked this issue and found I could encounter the same issue. When you invoke client.InvokeApiAsync<DbConfig>("Settings", HttpMethod.Get, parameters);, you would send request with the following link:
https://{your-app-name}.azurewebsites.net/api/settings?userid={Settings.AzureUserId}
By using fiddler you could find that the token has been sent to your mobile client as follows:
But when deserialize it to Permission, the token has not been initialized correctly. I found that the token property is read only as follows:
In summary, I recommend that you need to define your custom Permission class and refer to the Permission class provided by DocumentDB client SDK for defining the properties you need within your custom permission class in your mobile client.
I'm trying to use OAuth bearer authentication in a Web API application, everything works fine on my local IIS, I'm able to get the token as you can see here:
But when I publish my project to a ApiApp in Azure it doesn't work at all. I get the response:
{
"message": "No HTTP resource was found that matches the request URI 'https://mysite.azurewebsites.net/API/login'.",
"messageDetail": "No type was found that matches the controller named 'login'."
}
As shown in here:
My Startup.Auth class looks like:
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/login"),
Provider = new ApplicationOAuthProvider(),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
//#if DEBUG
AllowInsecureHttp = true
//#endif
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthAuthorizationServer(OAuthOptions);
}
}
I hope you can tell me what I'm doing wrong.
I've just find out that I was using an incorrect url. I was using /api/login instead of just /login.