【发布时间】:2020-10-28 03:44:53
【问题描述】:
我需要通过出示令牌从 Angular 9 应用程序调用安全 Web API。我将 Angular 与 .NET CORE 3.1 Web API 一起使用。我已成功生成 Azure B2C 令牌,但由于出现 CORS 错误,我坚持调用安全 Web api。
Angular 组件调用 Web API 端点
testAPI1(){
console.log("calling test API ...");
const myheaders = new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8',
'Authorization': this.authService.accessToken
});
this.http.get('https://localhost:5001/txn/v1/Dashboard/GetMessage', {headers: myheaders})
.subscribe((data)=>{
console.warn(data);
})
}
认证服务
@Injectable()
export class AuthService implements OnInit{
constructor(
private oauthService: OAuthService,
private router: Router
){// other code}
public get accessToken() {
return this.oauthService.getAccessToken();
}
Web API 控制器和端点
[Authorize]
[Route("txn/v1/[controller]/[action]")]
[EnableCors("CorsPolicy")]
[ApiController]
public class DashboardController : ControllerBase
{
[HttpGet]
public ActionResult<HelloMessage> GetMessage()
{
var result = new HelloMessage()
{
GivenName = "james",
ReturnMessage = "Dashboard@ Hello, Welcome to Digital tech"
};
return result;
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//JWT Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(jwtConfig =>
{
jwtConfig.Audience = Configuration["AzureAdB2C:ResourceId"];
jwtConfig.Authority = $"{Configuration["AzureAdB2C:Instance"]}{Configuration["AzureAdB2C:TanantId"]}";
jwtConfig.RequireHttpsMetadata = false;
jwtConfig.SaveToken = true;
jwtConfig.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer =true,
ValidateAudience = true,
ValidateLifetime = true
};
});
//CORS policy
services.AddCors(options =>
options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin()));
错误
【问题讨论】:
-
got CORS error请分享详细的错误信息,以便我们更好地解决问题。此外,不建议同时配置 AllowAnyOrigin 和 AllowCredentials 方法。您可以尝试使用 WithOrigins 方法指定允许的来源。 -
我更新问题有错误,还粘贴了 JWT 认证方法,不知道是不是我弄错了?
标签: azure-active-directory asp.net-core-webapi angular9 .net-core-3.1 .net-core-authorization