我正在尝试建立一个ASP.NET Core webapi + Angular网站,用户可以在其中使用Microsoft个人或工作或学校的电子邮件进行登录。我遵循此处描述的说明:https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/README.md
但是请解决这个问题,
我看到以下错误
在'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id = ...'处访问XMLHttpRequest(从'https:// localhost:44321 / Environment / GetUserInfo'重定向)来自起源“ https:// localhost:44321”的信息已被CORS策略阻止:对预检请求的响应未通过访问控制检查:所请求的资源上没有“ Access-Control-Allow-Origin”标头。
[当使用Visual Studio 2019 16.4.2和Chrome 79.0.3945.88进行本地调试时
有什么想法吗?谢谢
我使用]创建了我的项目>
dotnet new angular -o myapp
并在Azure.Portal中创建了应用注册使用以下重定向URI进行身份验证
检查了所有“公共客户端的建议重定向URI”注销URL:https:// localhost:44321 / signout-callback-oidc隐式授予:访问令牌和ID令牌Live SDK支持:是默认客户端类型:否
证书和秘密我创建了一个客户端密码,因为我尝试使用Microsoft提供程序(请参阅下面的注释代码),然后尝试使用AzureAd
API权限Microsoft.Graph User.Read
公开API范围= [应用程序ID URI] / access_as_user,仅管理员客户端应用程序= [CLIENT_ID_FROM_AZURE_PORTAL],上面的范围
服务器端
appsettings.json"AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "[Application ID URI]", "ClientId": "[CLIENT_ID_FROM_AZURE_PORTAL]", "TenantId": "common", "CallbackPath": "/signin-oidc" },
Startup.cs
app.module.tspublic void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder .AllowAnyMethod() .AllowAnyHeader() .AllowAnyOrigin(); }); }); services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); //services // .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) // .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme) // .AddMicrosoftAccount(microsoftOptions => //{ // microsoftOptions.ClientId = "[CLIENT_ID_FROM_AZURE_PORTAL]"; // microsoftOptions.ClientSecret = "[CLIENT_SECRET_FROM_AZURE_PORTAL]"; //}); services.AddAuthentication(AzureADDefaults.AuthenticationScheme) .AddAzureAD(options => Configuration.Bind("AzureAd", options)); services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => { options.Authority = options.Authority + "/v2.0/"; options.TokenValidationParameters.ValidateIssuer = false; }); services.AddControllers(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseCors("AllowAllOrigins"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseCookiePolicy(); app.UseStaticFiles(); if (!env.IsDevelopment()) { app.UseSpaStaticFiles(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); }
客户端
... import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { MsalModule, MsalGuard, MsalInterceptor } from '@azure/msal-angular'; ... export const protectedResourceMap: [string, string[]][] = [ ['https://localhost:44321/Environment/GetUserInfo', ['[Application ID URI]/access_as_user']], ['https://localhost:44321/api/Environment/GetUserInfo', ['[Application ID URI]/access_as_user']], ['https://graph.microsoft.com/v1.0/me', ['user.read']], ['https://login.microsoftonline.com/common', ['user.read']] ]; @NgModule({ declarations: [ AppComponent, NavMenuComponent, HomeComponent, CounterComponent, EntitySignoffComponent ], imports: [ BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }), HttpClientModule, FormsModule, AgGridModule.withComponents([]), MsalModule.forRoot({ clientID: [CLIENT_ID_FROM_AZURE_PORTAL], authority: "https://login.microsoftonline.com/common", redirectUri: "https://localhost:44321/", validateAuthority: true, cacheLocation: "localStorage", storeAuthStateInCookie: false, // dynamically set to true when IE11 postLogoutRedirectUri: "https://localhost:44321/", navigateToLoginRequestUrl: true, popUp: false, unprotectedResources: [ "https://login.microsoftonline.com/common" ], protectedResourceMap: protectedResourceMap } ), RouterModule.forRoot([ { path: '', component: HomeComponent, pathMatch: 'full', canActivate: [MsalGuard] } { path: 'counter', component: CounterComponent, canActivate: [MsalGuard] }, ]) ], providers: [NavMenuComponent, { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true }],
package.json
{
"name": "myapp",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"build:ssr": "ng run myapp:server:dev",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "8.2.14",
"@angular/common": "^8.2.14",
"@angular/compiler": "8.2.14",
"@angular/core": "^8.2.14",
"@angular/forms": "8.2.14",
"@angular/platform-browser": "8.2.14",
"@angular/platform-browser-dynamic": "8.2.14",
"@angular/platform-server": "8.2.14",
"@angular/router": "8.2.14",
"@azure/msal-angular": "^0.1.4",
"@nguniversal/module-map-ngfactory-loader": "8.2.6",
"aspnet-prerendering": "^3.0.1",
"bootstrap": "^4.4.1",
"core-js": "^3.6.1",
"jquery": "3.4.1",
"oidc-client": "^1.10.1",
"popper.js": "^1.16.0",
"rxjs": "^6.5.4",
"rxjs-compat": "^6.5.4",
"zone.js": "0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.803.21",
"@angular/cli": "8.3.21",
"@angular/compiler-cli": "8.2.14",
"@angular/language-service": "8.2.14",
"@types/jasmine": "^3.5.0",
"@types/jasminewd2": "~2.0.8",
"@types/node": "~13.1.2",
"codelyzer": "^5.2.1",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^4.4.1",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "^2.1.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.5.1",
"typescript": "3.5.3"
},
"optionalDependencies": {
"node-sass": "^4.13.0",
"protractor": "~5.4.2",
"ts-node": "~8.5.4",
"tslint": "~5.20.1"
}
}
我正在尝试建立一个ASP.NET Core webapi + Angular网站,用户可以在其中使用Microsoft个人或工作或学校的电子邮件进行登录。我遵循此处描述的说明:https://github.com / ...
据我了解,这两个官方样本将完全满足您的要求: