Giter VIP home page Giter VIP logo

azure-samples / ms-identity-javascript-angular-spa-aspnetcore-webapi Goto Github PK

View Code? Open in Web Editor NEW
74.0 29.0 32.0 485 KB

An Angular single-page application that authenticates users with Azure AD and calls a protected ASP.NET Core web API using MSAL Angular

PowerShell 36.16% C# 15.43% JavaScript 3.57% TypeScript 35.55% CSS 1.73% HTML 7.56%
asp-net-core javascript angular microsoft-identity-platform msal-angular msal-js webapi single-page-app oauth2 authorization-code-grant pkce-flow

ms-identity-javascript-angular-spa-aspnetcore-webapi's Introduction

ms-identity-javascript-angular-spa-aspnetcore-webapi's People

Contributors

derisen avatar jennyf19 avatar jmprieur avatar microsoft-github-operations[bot] avatar microsoftopensource avatar pmaytak avatar syendev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  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  avatar  avatar  avatar  avatar  avatar

ms-identity-javascript-angular-spa-aspnetcore-webapi's Issues

User group in token claims

Hi,
is possibile retrieve user groups into token?
In the azure portal I had add group in token configuration, but I can't see in the token.

Thanks

How to move required scope check in API project out of controller?

Scope checking in the controller inside every method is not ideal and would not be recommended for production use. I'm hoping there's a better way to do this e.g. somewhere inside Startup.cs?

    public class TodoListController : ControllerBase
    {
        // The Web API will only accept tokens 1) for users, and 
        // 2) having the access_as_user scope for this API
        static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" }; <--- This should be in Startup.cs

        .  .  .  .  .  .  .

        // GET: api/TodoItems
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
        {
            HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);    <--- This check should be in Startup.cs
            string owner = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            return await _context.TodoItems.Where(item => item.Owner == owner).ToListAsync();
        }
}

Protected Resource Map

Please follow the issue template below. Failure to do so will result in a delay in answering your question.

Library

@azure/[email protected]

Description

How do I correctly specify resources in the protected resource map for a custom web api?

I have mine specified and the MSAL_Interceptor does not appear to be adding the "Authorization" header and the access token to the http request.

I have a endpoint that looks like this: https://someserver.xyz.com/api/GetSomeStuff

I created an App registration for the WebAPI and setup an access scope called access_as_user and specified that it was available to admins and users.

In my custom web api, I specified the client id of the app registration.

In my angular code, I changed the auth-config.json file to look like this
{
"credentials": {
"clientId": "617a6feb-386a-4395-8059-880e430e3329",
"tenantId": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
},
"configuration": {
"redirectUri": "http://localhost:4200",
"postLogoutRedirectUri": "http://localhost:4200"
},
"resources": {
"API": {
"resourceUri": " https://someserver.xyz.com/api/GetSomeStuff",
"resourceScopes": [ "api://ca026bc3-0e37-4526-8ddd-8eea8b64b09b/access_as_user" ]
},
"graph": {
"resourceUri": "https://graph.microsoft.com/v1.0/me",
"resourceScopes": ["user.read"]
}
}
}

Now in my app.module.ts file my MSALInterceptorConfigFactory method looks like this
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
const protectedResourceMap = new Map<string, Array>();
protectedResourceMap.set(auth.resources.API.resourceUri, auth.resources.API.resourceScopes);
protectedResourceMap.set(auth.resources.graph.resourceUri, auth.resources.graph.resourceScopes);

return {
interactionType: InteractionType.Redirect,
protectedResourceMap
};
}

Does anybody see anything wrong with what I've done?

PKCE Error with MSAL and Angular App

Please follow the issue template below. Failure to do so will result in a delay in answering your question.

Library

Description

We have a angular 10 application that we have developed that is using MSAL.

We are in the process of trying to deploy it to our Qual environment for user acceptances testing.

The Azure Administrator has added the SPA url for our qual website (Example: https://somefunwebsite-q.domain.com)

The Angular app has been compiled with ng build --prod and deployed to the front end servers.

When we try and browse to the application in Chrome, if you look at the console. we are getting this error:
ERROR Error: Uncaught (in promise): BrowserAuthError: pkce_not_created: The PKCE code challenge and verifier could not be generated. Detail:TypeError: Cannot read property 'digest' of undefined
BrowserAuthError: pkce_not_created: The PKCE code challenge and verifier could not be generated. Detail:TypeError: Cannot read property 'digest' of undefined

This did not occur in our lower environments, dev or test.

What is wrong and how do I correct it?

Return roles and groups in the authentication token SPA

Hi,

I cloned this repo and did all the tutorial to add the authentication to my SPA and Web API.
But I need to return the roles or the group claims in the bearer token.

I added the roles to the App Registrations Manifest, added the claim 'groups' in the Token Configuration menu and set the "User assignment required?" as yes in my Enterprise App Configuration, but I still couldn't return the roles or groups within the token.

Is it possible? And if it is, how can I do it?

Thanks.

Is storage of tokens in browser localStorage insecure?

Library

Description

I have noticed that tokens are stored in localStorage in the browser. Is this not vulnerable to Cross Site Scripting (XSS)? I have seen a lot of advice saying to not do this, as nothing stored on the browser is safe. Could an attacker not get the tokens from local storage and then just call my API maliciously? (deleting all my users todos, for example (gasp!))

Instead, some people have recommended validating the token on the server and then issuing an Cookie instead, but I don't know how to do this when using the Microsoft.Identity.Web library.

Any help appreciated.

Cheers

Multi tenant only

Thank you for this great example. I'm also using msal in my Vue.js app and wanted to use this to get it correctly communicating with the backend. However, when I run this I get the following error:

image

This is because we don't use multi tenant in our setup. Is there a quick fix for this?

CORS issue

Excellent code and tutorial.

Authentication works!

However, I get a CORS exception in the console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:44351/api/todolist/. (Reason: CORS request did not succeed).

Can you help me to resolve please?

Error - Bearer error="invalid_token"

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(Configuration);

I just copied the code given in the repo and when I run the code I get Bearer error="invalid_token" error.

After going thru the documentation I even registered for the events

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(options =>
        {
            options.Audience = "";
            options.TokenValidationParameters.ValidateAudience = false;
            options.Events = new JwtBearerEvents
            {
                OnAuthenticationFailed = AuthenticationFailed,
                 
                OnForbidden = OnForbidden

            };

            options.Authority = "";
        }, apiOptions =>
        {
            apiOptions.ClientId = "";
            apiOptions.Authority = "";
            apiOptions.Domain = "";
            apiOptions.Instance = "https://login.microsoftonline.com";
            apiOptions.TenantId = "";
            apiOptions.Events = new AspNetCore.Authentication.OpenIdConnect.OpenIdConnectEvents
            {
                OnAuthenticationFailed = OnApiAuthFailed,
             OnTokenValidated = OnTokenValidated,
             OnAccessDenied = OnAccessDenied,
             OnRemoteFailure = OnRemoteFailure,
             OnTokenResponseReceived = OnTokenResponseReceived
               

            };


        }, "Bearer", true);

None of the events registered are firing except for OnMessageReceived.

Any help appreciated

Thank you

Request an example with Vue.js and node

It would be great if there was an example like this with Vue.js and node as a backend. My Angular skills are not so super duper and dotnet is something I don't master. Thanks anyway for making this, it does exactly what I need but the translation takes a bit of time for me.

Uncaught (in promise): BrowserAuthError: interaction_in_progress: Interaction is currently in progress.

Library

Important: Please fill in your exact version number above, e.g. [email protected].

Framework

Angular 11
Asp.NET Core 3.1

Description

I've explained the issue here. I hope you don't dismiss this. The reason why I posting both here and there is because I am not sure wherein the issue lies. I hope you guys understand ✌😁

Error Message

ERROR Error: Uncaught (in promise): BrowserAuthError: interaction_in_progress: Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API.
AuthError@http://localhost:4200/vendor.js:104091:24
BrowserAuthError@http://localhost:4200/vendor.js:110633:28
u8tD/BrowserAuthError.createInteractionInProgressError@http://localhost:4200/vendor.js:110694:16
u8tD/ClientApplication.prototype.preflightInteractiveRequest@http://localhost:4200/vendor.js:114110:36
u8tD/ClientApplication.prototype.acquireTokenRedirect/</<@http://localhost:4200/vendor.js:113480:45
step@http://localhost:4200/vendor.js:103642:23
verb/<@http://localhost:4200/vendor.js:103623:53
__awaiter/<@http://localhost:4200/vendor.js:103616:71
ZoneAwarePromise@http://localhost:4200/polyfills.js:10225:33
__awaiter@http://localhost:4200/vendor.js:103612:12
u8tD/ClientApplication.prototype.acquireTokenRedirect@http://localhost:4200/vendor.js:113465:16
u8tD/PublicClientApplication.prototype.loginRedirect/</<@http://localhost:4200/vendor.js:114372:44
step@http://localhost:4200/vendor.js:103642:23
verb/<@http://localhost:4200/vendor.js:103623:53
__awaiter/<@http://localhost:4200/vendor.js:103616:71
ZoneAwarePromise@http://localhost:4200/polyfills.js:10225:33
__awaiter@http://localhost:4200/vendor.js:103612:12
u8tD/PublicClientApplication.prototype.loginRedirect@http://localhost:4200/vendor.js:114369:16
loginRedirect@http://localhost:4200/vendor.js:14112:80
login@http://localhost:4200/main.js:605:34
NavBarComponent_button_6_Template_button_click_0_listener@http://localhost:4200/main.js:552:300
executeListenerWithErrorHandling@http://localhost:4200/vendor.js:47653:16
wrapListenerIn_markDirtyAndPreventDefault@http://localhost:4200/vendor.js:47688:54
decoratePreventDefault/<@http://localhost:4200/vendor.js:66878:50
invokeTask@http://localhost:4200/polyfills.js:9664:35
onInvokeTask@http://localhost:4200/vendor.js:60948:33
invokeTask@http://localhost:4200/polyfills.js:9663:40
runTask@http://localhost:4200/polyfills.js:9432:51
invokeTask@http://localhost:4200/polyfills.js:9745:38
invokeTask@http://localhost:4200/polyfills.js:10886:18
globalZoneAwareCallback@http://localhost:4200/polyfills.js:10912:31
EventListener.handleEvent*customScheduleGlobal@http://localhost:4200/polyfills.js:11038:47
scheduleTask@http://localhost:4200/polyfills.js:9650:30
onScheduleTask@http://localhost:4200/polyfills.js:9537:69
scheduleTask@http://localhost:4200/polyfills.js:9643:55
scheduleTask@http://localhost:4200/polyfills.js:9475:47
scheduleEventTask@http://localhost:4200/polyfills.js:9501:29
makeAddListener/<@http://localhost:4200/polyfills.js:11193:39
addEventListener@http://localhost:4200/vendor.js:67146:17
addEventListener@http://localhost:4200/vendor.js:66691:23
listen@http://localhost:4200/vendor.js:67067:34
listen@http://localhost:4200/vendor.js:24058:30
listenerInternal@http://localhost:4200/vendor.js:47608:44
ɵɵlistener@http://localhost:4200/vendor.js:47488:21
NavBarComponent_button_6_Template@http://localhost:4200/main.js:552:48
executeTemplate@http://localhost:4200/vendor.js:41982:19
renderView@http://localhost:4200/vendor.js:41789:28
createEmbeddedView@http://localhost:4200/vendor.js:55409:19
createEmbeddedView@http://localhost:4200/vendor.js:55540:37
_updateView@http://localhost:4200/vendor.js:80564:45
set ngIf@http://localhost:4200/vendor.js:80537:14
setInputsForProperty@http://localhost:4200/vendor.js:43341:13
elementPropertyInternal@http://localhost:4200/vendor.js:42385:29
ɵɵproperty@http://localhost:4200/vendor.js:47137:32
NavBarComponent_Template@http://localhost:4200/main.js:637:52
executeTemplate@http://localhost:4200/vendor.js:41982:19
refreshView@http://localhost:4200/vendor.js:41851:28
refreshComponent@http://localhost:4200/vendor.js:43017:24
refreshChildComponents@http://localhost:4200/vendor.js:41648:25
refreshView@http://localhost:4200/vendor.js:41901:35
refreshComponent@http://localhost:4200/vendor.js:43017:24
refreshChildComponents@http://localhost:4200/vendor.js:41648:25
refreshView@http://localhost:4200/vendor.js:41901:35
renderComponentOrTemplate@http://localhost:4200/vendor.js:41965:20
tickRootContext@http://localhost:4200/vendor.js:43191:34
detectChangesInRootView@http://localhost:4200/vendor.js:43216:20
detectChanges@http://localhost:4200/vendor.js:55228:32
tick@http://localhost:4200/vendor.js:61931:22
_loadComponent@http://localhost:4200/vendor.js:61969:14
bootstrap@http://localhost:4200/vendor.js:61908:14
_moduleDoBootstrap/<@http://localhost:4200/vendor.js:61607:64
_moduleDoBootstrap@http://localhost:4200/vendor.js:61607:44
bootstrapModuleFactory/</</<@http://localhost:4200/vendor.js:61577:26
invoke@http://localhost:4200/polyfills.js:9629:30
onInvoke@http://localhost:4200/vendor.js:60960:33
invoke@http://localhost:4200/polyfills.js:9628:36
run@http://localhost:4200/polyfills.js:9388:47
scheduleResolveOrReject/<@http://localhost:4200/polyfills.js:10122:40
invokeTask@http://localhost:4200/polyfills.js:9664:35
onInvokeTask@http://localhost:4200/vendor.js:60948:33
invokeTask@http://localhost:4200/polyfills.js:9663:40
runTask@http://localhost:4200/polyfills.js:9432:51
drainMicroTaskQueue@http://localhost:4200/polyfills.js:9834:39

Security

  • Is this issue security related?

Regression

  • Did this behavior work before?

Version:
"@azure/msal-angular": "^2.0.0-alpha.5",
"@azure/msal-browser": "^2.11.1",

MSAL Configuration

Please see description.

Reproduction steps

Please see description.

Expected behavior

I believe this flow should happen: press login -> pop up -> login with microsoft account -> sent to redirect url (localhost:4200 in my case locally).

Browsers/Environment

  • Chrome
  • Firefox
  • Edge
  • Safari
  • IE
  • Other (Please add browser name here)

error: "invalid_instance"

Library

"@azure/msal-angular": "^1.1.1"

Framework

Description

I clone the example project and then replace the configuration file in app-config.json with my own.
After compiling successfully, run the project. When I click the login button, the console prompts error: error: "invalid_instance".

Error Message

{"error":"invalid_instance","error_description":"AADSTS50049: Unknown or invalid instance.\r\nTrace ID: 7798ecd4-fabc-4eda-b5a4-693d0cd96a01\r\nCorrelation ID: 0250a443-5fe4-4741-beb0-4bce9754b2b6\r\nTimestamp: 2020-09-30 03:50:55Z","error_codes":[50049],"timestamp":"2020-09-30 03:50:55Z","trace_id":"7798ecd4-fabc-4eda-b5a4-693d0cd96a01","correlation_id":"0250a443-5fe4-4741-beb0-4bce9754b2b6","error_uri":"https://login.microsoftonline.com/error?code=50049"}

Security

Regression

NO

MSAL Configuration

{
"auth": {
"clientId": "92f23179-1bc8-41b0-a4af-d935b25c2e2b",
"authority": "https://smarthomedev.b2clogin.cn/smarthomedev.partner.onmschina.cn/B2C_1_signupsignin1/",
"validateAuthority": true,
"redirectUri": "http://localhost:4200",
"postLogoutRedirectUri": "http://localhost:4200",
"navigateToLoginRequestUrl": true
},
"cache": {
"cacheLocation": "localStorage"
},
"scopes": {
"loginRequest": ["openid", "profile", "https://smarthomedev.partner.onmschina.cn/smarthome/user_impersonation"]
},
"resources": {
"todoListApi": {
"resourceUri": "http://localhost:15838/api",
"resourceScope": "https://smarthomedev.partner.onmschina.cn/smarthome/user_impersonation"
}
}
}

Reproduction steps

Expected behavior

Browsers/Environment

Chrome

CORS blocking

Please follow the issue template below. Failure to do so will result in a delay in answering your question.

Library

  • @azure/msal-angular": "^2.0.0-alpha.3"
  • Node V.14.15.4
  • Dotnet 3.1

Description

After i configure follow with repo tutorial, i Can't login because CORS.
api: https://login.microsoftonline.com/a763cc2f-0823-4a5a-8547-0bd7a28c378f/oauth2/v2.0/token
Error: localhost/:1 Access to fetch at 'https://login.microsoftonline.com/a763cc2f-0823-4a5a-8547-0bd7a28c378f/oauth2/v2.0/token' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Examples:

"How i can resolve this problem?"

The Frame attempting navigation of the top level window is sandboxed, but the flag of 'allow-top-navigation' or 'allow-top-navigation-by-user-activation' is not set.

Library

Framework

Angular SPA

Description

Trying to access FHIR API using MSAL authentication, able to successfully authenticate but failed in redirection,,,

image

I went through 1199 but still not able to resolve in angular....

However it is working for sample application given with todolist, Error occurred while trying to call another API from ToDoListSPA,,,,

image

Error Message

The Frame attempting navigation of the top level window is sandboxed, but the flag of 'allow-top-navigation' or 'allow-top-navigation-by-user-activation' is not set.

Security

Authorization

Regression

Nope

MSAL Configuration

Reproduction steps

Expected behavior

Browsers/Environment

  • Chrome

Issue running NPM start on SPA

Please follow the issue template below. Failure to do so will result in a delay in answering your question.

Library

@azure/[email protected]

Description

I have walked through the steps outlined in the documentation.
https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi

I have created the WebAPI App Registration
I have created the SPA App Registration

I have updated the WebAPI project with all of the necessary client id / tenant id's
I have updated the auth-config.json file in the SPA with all of the necessary client id / tenant id's

When I try and run the SPA using npm start.

I get the following error message:

Error: src/app/app.component.ts:50:37 - error TS2345: Argument of type '{ prompt?: string | undefined; state?: string | undefined; authority?: string | undefined; correlationId?: string |
undefined; claims?: string | undefined; resourceRequestMethod?: string | undefined; ... 10 more ...; scopes?: string[] | undefined; } | { ...; }' is not assignable to parameter of type 'PopupRequest | undefined'.

Please advise

Logout is not working properly

Packages Used:
"msal": "^1.3.4",
"@azure/msal-angular": "^1.0.0",
issue:
User cannot logout it struct at logout session page:
image

Code to reproduce:
appsetting.json

{
  "appsettings":{
     "authentication":{
      "authority": "https://login.microsoftonline.com/tenentId",
      "clientId":"1112222-2232-235456-21311",
      "cacheLocation": "localStorage"
      },
      "Service1":{
         "url" : "https://localhost:5001",
         "scope"  : ["https://{mytenent}.onmicrosoft.com/1231-321313-13233311/CRUD"]
      },
      "redirectUri":"http://localhost:4200/",
      "postLogoutRedirectUri": "http://localhost:4200/",
  }
}

msalConfig.ts


export function MSALConfigFactory(config: AppConfigService): Configuration {
  const appSettings = config.getConfig(config.APP_SETTINGS);
  const authentication = appSettings.authentication;
  const auth = {
      auth: {
          clientId: authentication.clientId,
          authority: authentication.authority,
          redirectUri: appSettings.redirectUri,
          postLogoutRedirectUri: appSettings.postLogoutRedirectUri,
          navigateToLoginRequestUrl: true,
          validateAuthority: true,
      },
      cache: {
         cacheLocation: 'localStorage'
      }
  };
  return (auth as Configuration);
}

logoutComponet.ts
logout() {
this.authService.logout();
}

app registration settings:

image

i am able to call web api but logout not working properly

FHIR API - Invalid token and audience is invalid

Library

Framework

Angular SPA

Description

Trying to access FHIR API using MSAL authentication, able to successfully authenticate but failed in case of authorization,,,

image

Error Message

Invalid token and audience is invalid

image

Security

Authorization

Regression

Nope

MSAL Configuration

Reproduction steps

Expected behavior

Browsers/Environment

  • Chrome

ms-identity-javascript-angular-spa-aspnetcore-webapi The request body must contain the following parameter: 'client_assertion' or 'client_secret'

Please follow the issue template below. Failure to do so will result in a delay in answering your question.

Library

Important: Please fill in your exact version number above, e.g. [email protected].

Framework

Core 3.1

Description

Using the ms-identity-javascript-angular-spa-aspnetcore-webapi sample, went through the sign in process with Azure, but error occurring after Login

Error Message

login.microsoftonline.com/b02e93d3-199f-4fe5-9a80-6e5f1d2486fe/oauth2/v2.0/token:1 Failed to load resource: the server responded with a status of 401 (Unauthorized)
home.component.ts:16
ServerError: invalid_client: 7000218 - [2021-04-20 00:11:09Z]: AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret'.
Trace ID: 662f5e8c-9665-4fdb-80cd-0b5cca932301
Correlation ID: 6f5a7798-79c3-4f20-9320-2f363e5300ce
Timestamp: 2021-04-20 00:11:09Z - Correlation ID: 6f5a7798-79c3-4f20-9320-2f363e5300ce - Trace ID: 662f5e8c-9665-4fdb-80cd-0b5cca932301

Security

  • Is this issue security related? Yes

Regression

  • Did this behavior work before? Not sure

Version:

MSAL Configuration

// Provide configuration values here.
// For Azure B2C issues, please include your policies.

Reproduction steps

// Provide relevant code snippets here.
// For Azure B2C issues, please include your policies.

Expected behavior

Browsers/Environment

  • Chrome
  • Firefox
  • Edge
  • Safari
  • [X ] IE
  • Other (Please add browser name here)

don's support the Azure AD in China

I found 2 issues about the sample, help clarify. I have registered 2 Apps for front-end and backend.

for the Front-end
it works well, this the app-config.json content
{ "auth": { "clientId": "83e967a2-4b87-4a5c-aad8-01897aeda929", "authority": "https://login.chinacloudapi.cn/a09fa999-f876-4f4f-88dd-8a1983c066da", "validateAuthority": true, "redirectUri": "http://localhost:4200", "postLogoutRedirectUri": "http://localhost:4200", "navigateToLoginRequestUrl": true }, "cache": { "cacheLocation": "localStorage" }, "scopes": { "loginRequest": ["openid", "profile"] }, "resources": { "todoListApi": { "resourceUri": "http://localhost:57984/api/TodoList", "resourceScope": "api://4bf9068a-6653-4550-920d-5fa61e332af3/backend.read" } } }

and I get the token below as expect and decode the token see below.
Untitled

for the backend
this is the appsettings.json
"AzureAd": { "Instance": "https://login.partner.microsoftonline.cn/", "ClientId": "4bf9068a-6653-4550-920d-5fa61e332af3", "Domain": "xxxxx.partner.onmschina.cn", "TenantId": "common" }

2 issues

  1. when call the backend api with above token, the response show "WWW-Authenticate: Bearer error="invalid_token", error_description="The signature key was not found"", it tell me like it can't find the open id configuration and public key.

  2. I created a new backend API based on old version .netcore 2.2, it show the different issue says like "the audience is not right", and then I changed the config like below, then it works well, but I don't know why need to add the prefix "api://" at clientid. but for my experience, the perfix should not be required.

"AzureAd": { "Instance": "https://login.partner.microsoftonline.cn/", "ClientId": "api://4bf9068a-6653-4550-920d-5fa61e332af3", "Domain": "xxxxx.partner.onmschina.cn", "TenantId": "common" }

How to make this example code works for AnyOrg + Personal Accounts

My project has

  1. Reactjs

  2. Asp.Net Core Web Api

to access user's emails from Hotmail. The Reactjs app and WebApi live on different servers.

The example is almost what I need, but it only accepts accounts within same organization, not accepts Personal accounts.

I thought I only need to change the Tenant ID from a specific ID to "common" in related configurations and it will work. I also registered the Supported account types on Azure for both Web Api and Reactjs to use the

AnyOrg + Personal Account
image

here is the config for Angular

{
  "auth": {
    "clientId": "28xxx12",
    "authority": "https://login.microsoftonline.com/common",
    "validateAuthority": true,
    "redirectUri": "http://localhost:4200",
    "postLogoutRedirectUri": "https://localhost:44321/signout-oidc",
    "navigateToLoginRequestUrl": true
  },
    "cache": {
        "cacheLocation": "localStorage"
    },
  "scopes": {
    "loginRequest": [ "openid", "profile", "Mail.Read", "offline_access", "user.read"]
  },
    "resources": {
      "todoListApi": {
        "resourceUri": "https://localhost:44351/api/todolist/",
        "resourceScope": "https://papayee008.onmicrosoft.com/papayee008/access_as_user"
      }
    }     
}

here is the config for Web Api:

{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "papayee008.onmicrosoft.com",
"TenantId": "common",
"ClientId": "28xxx12"
},
"https_port": 44351,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

But when I was trying to log in with my personal account, it throws me this error:
image

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.