Code Monkey home page Code Monkey logo

azure-maps-azuread-samples's Introduction

page_type languages products description urlFragment
sample
csharp
javascript
azure
azure-maps
aspnetcore
azure-ad
A collection of samples showing how to integrate Azure Active Directory with Azure Maps.
AzureMapsAADSamples

Azure Maps & Azure Active Directory Samples

These are 4 different samples using AspNetCore C# to quick start Azure AD authentication to Azure Maps. Each sample uses different authentication protocols depending on application need which are supported by Azure AD and Azure Role Based Access Control (RBAC).

Contents

Outline the file contents of the repository. It helps users navigate the codebase, build configuration and any related assets.

File/folder Description
src/ImplicitGrant Samples used to show user authentication without a server component.
src/OpenIdConnect Samples using Microsoft's recommended protocol for secure web applications
src/ClientGrant Samples showing application authentication without user interaction.
.gitignore Define what to ignore at commit time.
CONTRIBUTING.md Guidelines for contributing to the sample.
README.md The starting readme.
LICENSE The license for the sample.

Prerequisites

Prior to downloading these samples

Setup

In the Azure Active Directory, create new application registration

  • This application registration will represent the web application(s).
  • Each specific sample will describe the steps necessary for the different authentication protocols.
  • For the sake of this sample repository, the same application registration can be used.
  • For production we recommend a distinct application registration for each web application. Additionally, we highly recommend using Azure Managed Identity for any non-interactive autentication to Azure Maps. This will save credential management costs.
  • For display name, we can name it "WebApp" and leave the redirect uri empty for now and follow the individuals samples README.md.

In the Azure Portal create an Azure Maps account

  • Search for "Azure Maps" on create new resource and follow the portal to create a new account.
  • Once the account is created, retrieve the Azure Maps Client ID and keep on hand for the specific sample you wish to run.
  • This value should be used in the x-ms-client-id with all HTTP requests.
  • If using any SDK add it to the authenication options (JS).

Running the sample

  • Running the Web Applicaton samples are based on the AspNetCore MVC v2.2 documentation
  • Once all the individual sample README.md have been configured, Debug (F5 key) should build and start the application.
  • Make sure to run the web application with HTTPS configured.
  • If prompted for development HTTPS certificate via IIS or AspNetCore, accept the prompt to trust the certificate.

Key concepts

  • Using Azure Maps Web SDK supports 2 approaches for Azure AD access tokens.
  • If a server component like AspNetCore MVC is available for your application, we recommend OpenID Connect.
  • In the case of no server component, you must use implicit grant for an user interactive sign in experience. However, in the case for no interactive sign in, some server component must exist to retrieve an access token and provide it to the Azure Maps Web SDK.
  • Using Azure Service Authentication Library will help reduce the complexity and cost of credential management and allow for Azure Managed Identities to be used on the hosted platform such as Azure Virtual Machines or Azure App Service.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

azure-maps-azuread-samples's People

Contributors

cschotte avatar dependabot[bot] avatar jeffbdye avatar microsoftopensource avatar msftgits avatar rbrundritt avatar sagumpal avatar zedy-wj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

azure-maps-azuread-samples's Issues

403 error returned on all requests to atlas in AzureMapsWebApiToken sample code

I am trying to use the AzureMapsWebApiToken sample code. I have setup Azure Maps and Azure AD according to the README.

  1. I created the App Registration in Azure Active Directory
  2. I generated a Client Secret in Azure AD
  3. I created the environment variable AzureServicesAuthConnectionString including the IDs and made AppKey the same as the Client Secret
  4. I granted the Role Assignment in Azure AD to my Maps app registration

All requests to the atlas API return 403.

My requests do include an Authorization token (Bearer) in the header.

This is the error I get:

{
  "error": {
    "code": "403 Forbidden",
    "message": "Permission, capacity, or authentication issues."
  }
}

What am I doing wrong? Thank you.

Access denied, please inspect WWW-Authenticate header

Hi There,

I've been trying the OpenIdConnectSample but get the following error when loading the map:

{ "error": { "code": "Unauthorized", "message": "Access denied, please inspect WWW-Authenticate header.", "target": null, "details": [] } }
Checking out the master branch of the samples. The only changes I've made in the OpenIdConnect/AzureMapsOpenIdConnectV1 codebase are:

  • Modifying AzureAdOption.cs
    • Updating the ClientId & Tenant Id to my respective Tenant
    • To test initial working I commented out the key vault key retrieval and hard coded my setup secret to simplify the solution that I run locally
  • Modifying VIews/Maps/Index.cshtml with the ClientID of my App Registration in my subscription.

The App loads, retrieves a token correctly but then when it attempts to load the map, all of the tiles return a 401 with the above error. I believe i've setup all of the app registration side correctly as it woudn't let it retrieve the token otherwise. Token attached below. Any ideas?

{ "aud": "https://atlas.microsoft.com/", "iss": "https://sts.windows.net/922b2f31-c0b5-401d-beb7-b2de2e4bb274/", "iat": 1596037862, "nbf": 1596037862, "exp": 1596041762, "acr": "1", "aio": "AUQAu/8QAAAAVRr7IetliJDyH4InMCVUaWRfVla0vXrsZ1ml8TDxMpZTpMbaRngwWIgpzXqsofguiwr2p5+IwuWm+McW7abupg==", "altsecid": "1:live.com:000340011DAF5551", "amr": [ "pwd" ], "appid": "<redacted>", "appidacr": "1", "email": "<redacted>", "family_name": "<redacted>", "given_name": "<redacted>", "groups": [ "763dcd68-5a8f-43e6-8c59-31572bb929a5" ], "idp": "live.com", "ipaddr": "31.51.191.176", "name": "<redacted>", "oid": "37ea4a95-dc35-4b8d-9291-5ce4c3288deb", "puid": "100320009AFA0721", "scp": "user_impersonation", "sub": "T-hjRsm0ldBhG34QtjxF83G6V6toh2L5xv0y7K9eiRQ", "tid": "922b2f31-c0b5-401d-beb7-b2de2e4bb274", "unique_name": "<redacted>", "uti": "5ljDW6caSE62tgZp4DDVAA", "ver": "1.0", "wids": [ "62e90394-69f5-4237-9190-012177145e10" ] }

403 response codes using anonymous authentication

I'm using anon auth. I have everything setup correctly. Azure function and what not. In my case, I interface it through api manager. I'm getting the token back just fine. Here's what my token looks like.

{
"typ": "JWT",
"alg": "RS256",
"x5t": "T1St-dLTvyWRgxB_676u8krXS-I",
"kid": "T1St-dLTvyWRgxB_676u8krXS-I"
}.{
"aud": "https://atlas.microsoft.com",
"iss": "https://sts.windows.net/organization-tenant-id/",
"iat": redacted,
"nbf": redacted,
"exp": redacted,
"aio": "E2VgYEhr+f96e6v0ew+LzbvMWS89BQA=",
"appid": "a8a9f121-896a-4a4d-a181-1922e02a2683",
"appidacr": "2",
"idp": "https://sts.windows.net/organization-tenant-id/",
"oid": "5a0e95b4-60d3-49d0-aa1f-a4ded8c3b41f",
"rh": "0.AAcAPtc9i3JOeUaxkVbaFYhxKyKgHroHWNVBu-spLH4c9fYHAAA.",
"sub": "5a0e95b4-60d3-49d0-aa1f-a4ded8c3b41f",
"tid": "organization-tenant-id",
"uti": "mh7SaofszEeVW5EP8DRdAA",
"ver": "1.0"
}.[Signature]

Here's my javascript code (this.mapKey is assigned the token value after it's retrieved from apim so by the time the code below executes this member variable is already populated)

new atlas.Map(this.mapElement.nativeElement, {
      // view: 'Unifed',
      center: [-79.995888, 40.440624],
      zoom: 11,
      language: 'en-US',
      disableTelemetry: true,
      authOptions: {
        authType: atlas.AuthenticationType.anonymous,
        clientId: "azure-map-client-id",
        getToken: (resolve: any, reject: any, map: any) => {
          resolve(this.mapKey);
        }
      }
    });

The map initially loads just fine. It's moving around when 403s start throwing. It's completely random. Sometimes the attribution endpoint throws and sometimes it's the tile endpoint. Sometimes it's both. Doesn't make any sense why. Can you help?

DefaultAzureCredential failed to retrieve a token from the included credentials

Im having issues acquiring an access token for use with this Azure Maps library.

Environment: .NET Core 7.0 using DefaultAzureCredential.
Testing in local development using an account that is logged in to Microsoft through Visual Studio.
I am successfully using the same account with DefaultAzureCredential for connecting to all other services in my app, such as Azure KeyVault, Blob Storage, Azure SignalR etc. So I dont beleive there is an issue with the user account being used in attemtping to acquire this token.

In my Azure Maps Account, I have double checked that my user account has the required role assignment "Reader" in the Access Control (IAM) menu blade.

I have tried re-logging in to Microsoft via Visual Studio but made no difference.

Sample code from my Controller:

private static readonly DefaultAzureCredential tokenProvider = new(new DefaultAzureCredentialOptions()
{
	Diagnostics =
	{
		LoggedHeaderNames = { "x-ms-request-id" },
		LoggedQueryParameters = { "api-version" },
		IsLoggingContentEnabled = true
	},
	TenantId = "d66310f1d-6de38-4f76-a23f-875dae78643e",
	//ExcludeAzureCliCredential = true,
	//ExcludeAzurePowerShellCredential = true,
	//ExcludeInteractiveBrowserCredential = true,
	//ExcludeManagedIdentityCredential = true,
	//ExcludeEnvironmentCredential = true,
	//ExcludeSharedTokenCacheCredential = true,
	//ExcludeVisualStudioCodeCredential = true,
});

private AccessToken AccessToken { get; set; }  

[HttpGet]
[Authorize(Policy = AuthorizationPolicies.AssignmentToViewMapsRoleRequired)]
public async Task<IActionResult> GetAzureMapsToken()
{
	using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();

	try
	{
		// tokenProvider will cache the token in memory, if you would like to reduce the dependency on Azure AD we recommend
		// implementing a distributed cache combined with using the other methods available on tokenProvider.
		AccessToken = await tokenProvider.GetTokenAsync(new TokenRequestContext(new string[] { "https://atlas.microsoft.com/.default" }));
		
	}
	catch (Exception ex) 
	{
		var ex1 = ex;
	}

	return Ok(AccessToken.Token);
} 

I get the following logs output, but I cant see any details that gives me any means to properly troubleshoot the issue:

[Informational] Azure-Identity: DefaultAzureCredential.GetToken invoked. Scopes: [ https://atlas.microsoft.com/.default ] ParentRequestId:
[Informational] Azure-Identity: EnvironmentCredential.GetToken invoked. Scopes: [ https://atlas.microsoft.com/.default ] ParentRequestId:
[Informational] Azure-Identity: EnvironmentCredential.GetToken was unable to retrieve an access token. Scopes: [ https://atlas.microsoft.com/.default ] ParentRequestId: Exception: Azure.Identity.CredentialUnavailableException (0x80131500): EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot
[Informational] Azure-Identity: ManagedIdentityCredential.GetToken invoked. Scopes: [ https://atlas.microsoft.com/.default ] ParentRequestId:
[Informational] Azure-Identity: False MSAL 4.51.0.0 MSAL.NetCore .NET 7.0.4 Microsoft Windows 10.0.19045 [2023-04-04 21:50:55Z - 11466bb9-b852-41b6-ac6d-964050a73fdc] MSAL MSAL.NetCore with assembly version '4.51.0.0'. CorrelationId(11466bb9-b852-41b6-ac6d-964050a73fdc)
[Informational] Azure-Identity: False MSAL 4.51.0.0 MSAL.NetCore .NET 7.0.4 Microsoft Windows 10.0.19045 [2023-04-04 21:50:55Z - 11466bb9-b852-41b6-ac6d-964050a73fdc] === AcquireTokenForClientParameters ===
SendX5C: False
ForceRefresh: False

[Informational] Azure-Identity: False MSAL 4.51.0.0 MSAL.NetCore .NET 7.0.4 Microsoft Windows 10.0.19045 [2023-04-04 21:50:55Z - 11466bb9-b852-41b6-ac6d-964050a73fdc]
=== Request Data ===
Authority Provided? - True
Scopes - https://atlas.microsoft.com/.default
Extra Query Params Keys (space separated) -
ApiId - AcquireTokenForClient
IsConfidentialClient - True
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - 11466bb9-b852-41b6-ac6d-964050a73fdc
UserAssertion set: False
LongRunningOboCacheKey set: False
Region configured:

[Informational] Azure-Identity: False MSAL 4.51.0.0 MSAL.NetCore .NET 7.0.4 Microsoft Windows 10.0.19045 [2023-04-04 21:50:55Z - 11466bb9-b852-41b6-ac6d-964050a73fdc] === Token Acquisition (ClientCredentialRequest) started:
Scopes: https://atlas.microsoft.com/.default
Authority Host: login.microsoftonline.com
[Informational] Azure-Identity: False MSAL 4.51.0.0 MSAL.NetCore .NET 7.0.4 Microsoft Windows 10.0.19045 [2023-04-04 21:50:55Z - 11466bb9-b852-41b6-ac6d-964050a73fdc] [Region discovery] Not using a regional authority.
[Informational] Azure-Identity: False MSAL 4.51.0.0 MSAL.NetCore .NET 7.0.4 Microsoft Windows 10.0.19045 [2023-04-04 21:50:55Z - 11466bb9-b852-41b6-ac6d-964050a73fdc] [Instance Discovery] Skipping Instance discovery because it is disabled.
[Informational] Azure-Core: Request [a9ced34e-0ee6-4582-a392-508a0c5c751f] GET http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=REDACTED
Metadata:REDACTED
x-ms-client-request-id:a9ced34e-0ee6-4582-a392-508a0c5c751f
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.8.2 (.NET 7.0.4; Microsoft Windows 10.0.19045)
client assembly: Azure.Identity

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.