I am using Managed Identity to connect to Azure Service Bus and it used to work fine.
This morning, I realized that this approach wasn't working anymore locally (using Visual Studio) and also on the deployed application (using managed identity).
I have a custom token provider class:
public class AzureServicebusManagedIdentityTokenProvider : TokenProvider
{
private const string Resource = "https://servicebus.azure.net/";
protected readonly string TenantId;
public AzureServicebusManagedIdentityTokenProvider(string tenantId = null)
{
TenantId = string.IsNullOrWhiteSpace(tenantId) ? null : tenantId;
}
public override async Task<SecurityToken> GetTokenAsync(string appliesTo, TimeSpan timeout)
{
string accessToken = await GetAccessToken(Resource);
return new JsonSecurityToken(accessToken, appliesTo);
}
private async Task<string> GetAccessToken(string resource)
{
var authProvider = new AzureServiceTokenProvider();
return await authProvider.GetAccessTokenAsync(resource, TenantId);
}
}
Then for example to send a message:
var sbMessageSender = new MessageSender(new ServiceBusConnection("<my connectionstring>")
{
TransportType = TransportType.Amqp,
TokenProvider = new AzureServicebusManagedIdentityTokenProvider("<my tenant id>")
}, "my queue name", RetryPolicy.Default);
var json = JsonConvert.SerializeObject(<message to send>);
var message = new Message(Encoding.UTF8.GetBytes(json));
await sbMessageSender.SendAsync(message);
This error is thrown:
Put token failed. status-code: 401, status-description: InvalidIssuer: Token issuer is invalid. TrackingId:5c6c17c7-7a9e-49f3-adf7-5dbfb35b3daf, SystemTracker:NoSystemTracker, Timestamp:2019-10-29T08:56:17.
I've checked that I have 'Azure Service Bus Data Owner' role and that the 'Azure App authentication' tool in visual studio is set to the appropriate account.
I am using these nuget packages:
Microsoft.Azure.Services.AppAuthentication v1.3.1
Microsoft.Azure.ServiceBus v3.4.0
Not sure If I am doing something stupid (as it used to work ) but any help would be appreciated.
This appears to be due to an issue within Azure. Per the response on my support ticket:
...this issue was caused by the latest service update where there was a syncing issue on the backend subscription ID info for the namespace. This only happens when a namespace is updated. Since RBAC authentication relies on constructing ARM resourceID using the stored subscription ID you saw authentication issues. The issue is now resolved and it should not re-occur.
Related
When I inject IConfiguration in a function, it does not find any keys that only live in my "Azure App Configuration".
I have a functionApp (V3) that accesses App Configuration using the DefaultAzureCredential. I am running this locally in debug hence the need for a default credential. I also have multiple Tenants so I had to set the VisualStudioTenantId and SharedTokenCacheTenantId on DefaultAzureCredentialOptions. My Visual studio user was also given the role "App Configuration Data Reader" to be able to debug.
When connecting to App configuration I get no errors.
Editedto add: I have setup AppConfiguration to authenticate with AzureAD.
See code below:
public override async void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
{
var credOptions = new DefaultAzureCredentialOptions();
var tenantId = Environment.GetEnvironmentVariable("Tenant_Id");
credOptions.VisualStudioTenantId = tenantId;
credOptions.SharedTokenCacheTenantId = tenantId;
var cred = new DefaultAzureCredential(credOptions);
/*Works but requires SharedTokenCacheTenantId*/
var secretClient = new SecretClient(new Uri(vaultURI), cred);
var secret = await secretClient.GetSecretAsync("<secret name>");
/*Works but where are my keys when I try to access them?*/
builder.ConfigurationBuilder.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigURI), cred);
}).Build(); //Should I be building this??
}
In my function
public FunctName(IConfiguration configuration)
{
_configuration = configuration;
}
And when I access the property
var prop = _configuration["PropertyName"];
There is an example function app that uses IFunctionsConfigurationBuilder here https://github.com/Azure/AppConfiguration/blob/main/examples/DotNetCore/AzureFunction/FunctionApp/Startup.cs . I would recommend taking a look and seeing if there are any missing pieces.
The title mentions "using DefaultAzureCredential on local". Does that mean that this works as expected if you use a connection string?
Notice the async void ConfigureAppConfiguration. This caused my ConfigureAppConfiguration to not execute synchronously, causing configure to add my App Configuration before it was populated.
I'm getting Unauthorized error when try to send message from azure Bot channel to api. I have deployed azure app and Bot channel with pulumi. In azure application I have noticed that there is a warning in authentication section about Implicit Grant.
If I disable Implicit Grant setting from azure portal then Bot channel works fine. I'm creating azure application with default settings as per pulumi documentation but there is no option to remove this Implicit Grant settings
I have created Azure application and Bot channel with pulumi using this link
public static AzureAD.Application Create()
{
var name = "app-name";
var azureApp = new AzureAD.Application(name, new AzureAD.ApplicationArgs
{
Name = name
// Tried combinations of the following lines, but it makes no difference
//, Type = "native"
//, Oauth2AllowImplicitFlow = false
});
CreatePrincipal(azureApp);
return azureApp;
}
private static void CreatePrincipal(AzureAD.Application azureApp)
{
var name = "app-principal";
new AzureAD.ServicePrincipal(name, new AzureAD.ServicePrincipalArgs
{
ApplicationId = azureApp.ApplicationId
});
}
public static ChannelsRegistration Create(ResourceGroup resourceGroup, AzureAD.Application teamsBotAzureApp)
{
var channelName = "Channel";
var channel = new ChannelsRegistration(channelName, new ChannelsRegistrationArgs
{
Location = "global",
ResourceGroupName = resourceGroup.Name,
Sku = "F0",
MicrosoftAppId = teamsBotAzureApp.ApplicationId,
Endpoint = "https://azurefunction.com/api/BotMessagesHandler"
});
CreateChannel(resourceGroup, channel);
return channel;
}
In azure ad, the setting of Implicit Grant is controlled by the parameters in the Manifest(you can also set them in the UI, then they will be changed in the manifest), Access tokens corresponds to oauth2AllowImplicitFlow, ID tokens corresponds to oauth2AllowIdTokenImplicitFlow.
If you create the app with pulumi, you can set the Oauth2AllowImplicitFlow = false to disable the Access tokens, but looks there is no oauth2AllowIdTokenImplicitFlow in the pulumi inputs, so you could not disable the ID tokens via pulumi.
You could try the workarounds below.
1.From the warning, it says You should remove these settings or register the appropriate redirect URI. So you could try to create the app with a redirect URI(i.e. ReplyUrls ) with the code like below, see if it works without disabling the ID tokens.
ReplyUrls =
{
"https://replyurl",
}
2.If it is accepted, you could use the Microsoft Graph SDK to update the application after creating it. Set the enableIdTokenIssuance to false in implicitGrantSettings of web property, then the ID tokens will be disabled.
I have successfully published Azure App Service from VS-2019 using WebForms. I have successfully secured it so that users must login using an Azure AAD account in the same domain as the App Service. I have successfully created an Azure SQL database. I have successfully added users from the AAD domain to the database and connected to the db, from within the Azure App Service, by hard-coding one of the Azure AAD account users I created, into the connection string.
Now I want to use the authenticated AAD user from the App Service login to connect to the Azure SQL database. Everything I've tried thus far has failed.
I'm pretty new to Azure. Most of my experience is with SQL Server/Visual Studio on an internal corporate domain, with no Cloud services whatsoever.
Anyone have any suggestions?
This is my authentication code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Extensions;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using System.Net.Http;
namespace Church
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]);
private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
string authority = aadInstance + tenantId;
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = (context) =>
{
return System.Threading.Tasks.Task.FromResult(0);
},
SecurityTokenValidated = (context) =>
{
var claims = context.AuthenticationTicket.Identity.Claims;
var groups = from c in claims
where c.Type == "groups"
select c;
foreach (var group in groups)
{
context.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Role, group.Value));
}
return Task.FromResult(0);
}
}
}
);
// This makes any middleware defined above this line run before the Authorization rule is applied in web.config
app.UseStageMarker(PipelineStage.Authenticate);
}
private static string EnsureTrailingSlash(string value)
{
if (value == null)
{
value = string.Empty;
}
if (!value.EndsWith("/", StringComparison.Ordinal))
{
return value + "/";
}
return value;
}
}
}
enter code here
This task a is bit more complicated.
In order to achieve what you desire, you have to configure the EasyAuth (the app service Authentication / Authorization service) to also get an access token for Azure SQL DB.
You can read more about access tokens with Azure app service authentication here.
Pay attention to the part for the Azure Active Directory configuration. You will be instructed to go to https://resources.azure.com/, find your app service and update the following properties:
"additionalLoginParams": ["response_type=code id_token",
"resource="]
for the resource parameter, you should use https://database.windows.net/, which is the identifier of Azure SQL DB. This will allow the app service authentication services (EasyAuth) to get an access token, on behalf of the user for Azure SQL DB. You will then be able to get this access token from the HTTP HEADER X-MS-TOKEN-AAD-ACCESS-TOKEN (also described on the same documentation page).
Once you manage to get an access token for Azure SQL DB, then you should use token authentication for azure SQL DB and not user/password based. The token authentication part of the documentation is well hidden here and this example demonstrates it:
string ConnectionString =#"Data Source=n9lxnyuzhv.database.windows.net; Initial Catalog=testdb;"
SqlConnection conn = new SqlConnection(ConnectionString);
conn.AccessToken = "Your JWT token that you took from HTTP HEADER X-MS-TOKEN-AAD-ACESS-TOKEN"
conn.Open();
I created a simple ASP.NET Core Web application using OAuth authentication from Google. I have this running on my local machine fine.
Yet after deploying this as an AppService to Azure the OAuth redirects seem to get messed up.
The app itself can be found here:
https://gcalworkshiftui20180322114905.azurewebsites.net/
Here's an url that actually returns a result and shows that the app is running:
https://gcalworkshiftui20180322114905.azurewebsites.net/Account/Login?ReturnUrl=%2F
Sometimes the app responds fine but once I try to login using Google it keeps loading forever and eventually comes back with the following message:
The specified CGI application encountered an error and the server terminated the process.
Behind the scenes, the authentication callback that seems to be failing with a 502.3 error:
502.3 Bad Gateway “The operation timed out”
The error trace can be found here:
https://gcalworkshiftui20180322114905.azurewebsites.net/errorlog.xml
The documentation from Microsoft hasn't really helped yet.
https://learn.microsoft.com/en-us/azure/app-service/app-service-authentication-overview
Further investigation leads me to believe that this has to do with the following code:
public GCalService(string clientId, string secret)
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json");
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = clientId,
ClientSecret = secret
},
new[] {CalendarService.Scope.Calendar},
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
// Create Google Calendar API service.
_service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "gcalworkshift"
});
}
As I can imagine Azure not supporting personal folders? Googling about this doesn't tell me much.
I followed Facebook, Google, and external provider authentication in ASP.NET Core and Google external login setup in ASP.NET Core to create a ASP.NET Core Web Application with Google authentication to check this issue.
I also followed .NET console application to access the Google Calendar API and Calendar.ASP.NET.MVC5 to build my sample project. Here is the core code, you could refer to them:
Startup.cs
public class Startup
{
public readonly IDataStore dataStore = new FileDataStore(GoogleWebAuthorizationBroker.Folder); //C:\Users\{username}\AppData\Roaming\Google.Apis.Auth
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication().AddGoogle(googleOptions =>
{
googleOptions.ClientId = "{ClientId}";
googleOptions.ClientSecret = "{ClientSecret}";
googleOptions.Scope.Add(CalendarService.Scope.CalendarReadonly); //"https://www.googleapis.com/auth/calendar.readonly"
googleOptions.AccessType = "offline"; //request a refresh_token
googleOptions.Events = new OAuthEvents()
{
OnCreatingTicket = async (context) =>
{
var userEmail = context.Identity.FindFirst(ClaimTypes.Email).Value;
var tokenResponse = new TokenResponse()
{
AccessToken = context.AccessToken,
RefreshToken = context.RefreshToken,
ExpiresInSeconds = (long)context.ExpiresIn.Value.TotalSeconds,
IssuedUtc = DateTime.UtcNow
};
await dataStore.StoreAsync(userEmail, tokenResponse);
}
};
});
services.AddMvc();
}
}
}
CalendarController.cs
[Authorize]
public class CalendarController : Controller
{
private readonly IDataStore dataStore = new FileDataStore(GoogleWebAuthorizationBroker.Folder);
private async Task<UserCredential> GetCredentialForApiAsync()
{
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "{ClientId}",
ClientSecret = "{ClientSecret}",
},
Scopes = new[] {
"openid",
"email",
CalendarService.Scope.CalendarReadonly
}
};
var flow = new GoogleAuthorizationCodeFlow(initializer);
string userEmail = ((ClaimsIdentity)HttpContext.User.Identity).FindFirst(ClaimTypes.Name).Value;
var token = await dataStore.GetAsync<TokenResponse>(userEmail);
return new UserCredential(flow, userEmail, token);
}
// GET: /Calendar/ListCalendars
public async Task<ActionResult> ListCalendars()
{
const int MaxEventsPerCalendar = 20;
const int MaxEventsOverall = 50;
var credential = await GetCredentialForApiAsync();
var initializer = new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "ASP.NET Core Google Calendar Sample",
};
var service = new CalendarService(initializer);
// Fetch the list of calendars.
var calendars = await service.CalendarList.List().ExecuteAsync();
return Json(calendars.Items);
}
}
Before deploying to Azure web app, I changed the folder parameter for constructing the FileDataStore to D:\home, but got the following error:
UnauthorizedAccessException: Access to the path 'D:\home\Google.Apis.Auth.OAuth2.Responses.TokenResponse-{user-identifier}' is denied.
Then, I tried to set the parameter folder to D:\home\site and redeploy my web application and found it could work as expected and the logged user crendentials would be saved under the D:\home\site of your azure web app server.
Azure Web Apps run in a secure environment called the sandbox which has some limitations, details you could follow Azure Web App sandbox.
Additionally, you mentioned about the App Service Authentication which provides build-in authentication without adding any code in your code. Since you have wrote the code in your web application for authentication, you do not need to set up the App Service Authentication.
For using App Service Authentication, you could follow here for configuration, then your NetCore backend can obtain additional user details (access_token,refresh_token,etc.) through an HTTP GET on the /.auth/me endpoint, details you could follow this similar issue. After retrieved the token response for the logged user, you could manually construct the UserCredential, then build the CalendarService.
I created a basic project using Visual Studio 2015 Update 3 for Web API (nothing custom, bare bone) and deployed it to Azure (Free Account) following the instruction here.
Then I created a Console client with the following code.
public static async Task<bool> ReadValues()
{
try
{
// Authenticate the user and get a token from Azure AD
//AuthenticationResult authResult = await AuthContext.AcquireTokenSilentAsync(Resource, ClientId);
AuthenticationResult authResult = AuthContext.AcquireToken(Resource, ClientId, RedirectUri);
// Create an HTTP client and add the token to the Authorization header
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
//"Bearer"
authResult.AccessTokenType
, authResult.AccessToken);
// Call the Web API to get the values
var requestUri = new Uri(WebApiUri, "api/values");
Console.WriteLine("Reading values from '{0}'.", requestUri);
HttpResponseMessage httpResponse = await httpClient.GetAsync(requestUri);
Console.WriteLine("HTTP Status Code: '{0}'", httpResponse.StatusCode.ToString());
//Console.WriteLine("HTTP Header: '{0}'", httpClient.DefaultRequestHeaders.Authorization.ToString());
if (httpResponse.IsSuccessStatusCode)
{
//
// Code to do something with the data returned goes here.
//
var s = await httpResponse.Content.ReadAsStringAsync();
Console.WriteLine(s);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(httpResponse.ReasonPhrase);
}
return (httpResponse.IsSuccessStatusCode);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
It works fine when I run the WEB API locally from the Visual Studio in debug, but when I deploy it to the Azure, it returns Unauthorized.
Few common things that I might get asked:
I do receive a valid bearer token
I have created the App registrations in the Azure AD for bot hthe WEB API and the client
The client and WEB API are using the correct redirect, resource uri
The account I am using to login is the same as the one used to create the Azure account and it has full privileges in the domain/AD/API
On the API side, this is whole of the startup.auth.cs
using System.Configuration;
using System.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using WebApi;
[assembly: OwinStartup("default", typeof(Startup))]
namespace WebApi
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters {
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
});
}
}
}
What else should I check?
Other references
https://www.simple-talk.com/cloud/security-and-compliance/azure-active-directory-part-3-developing-native-client-applications/
Thanks for help from Juunas who provided me with a working copy, I was able to narrow down the cause. When I attached a debugger to the Azure instance of the Web API I was able to see a exception for Bad Audience. On trying to retrace my steps, I found that while deployment from Visual Studio, I was selection Enterprise Authentication in settings that was causing the web.config to change in way that lead to the problem. Not selecting that option, I was able to access the API through bearer token.