【问题标题】:Pass JWT token from angular HttpClient to access secure .NET Core Web API从 Angular HttpClient 传递 JWT 令牌以访问安全的 .NET Core Web API
【发布时间】: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 请分享详细的错误信息,以便我们更好地解决问题。此外,不建议同时配置 AllowAnyOriginAllowCredentials 方法。您可以尝试使用 WithOrigins 方法指定允许的来源。
  • 我更新问题有错误,还粘贴了 JWT 认证方法,不知道是不是我弄错了?

标签: azure-active-directory asp.net-core-webapi angular9 .net-core-3.1 .net-core-authorization


【解决方案1】:

CORS 的政策可能有点挑剔。因此,我建议您尝试一个相当开放的 CORS 策略(考虑到您使用的是标头身份验证而不是 cookie,这并不太危险)。

所以你的配置服务方法应该是这样的:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

然后你的配置方法应该是这样的:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors( options => options.WithOrigins("http://example.com").AllowAnyMethod() );

    app.UseMvc();
}

请注意,Configure 方法中的顺序很重要。如果不是管道中的第一个中间件,对 CORS 的调用必须相对较早。

如果可行,则向后工作以慢慢添加策略并查看哪个策略失效。 CORS 可能非常挑剔,因此在一个基本示例中允许所有内容然后慢慢添加内容会更好。

更多阅读:https://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/

【讨论】:

  • 我已经按照您的建议进行了尝试,但没有成功,抛出了我在底部上传的有问题的错误
  • 当您直接调用此 API(邮递员、在您的浏览器等)并检查标头时,您可以看到它返回了您期望的 CORS 标头?因为它说它没有返回 Access-Control-Origin 这意味着 CORS 设置不正确。
  • 我必须按以下方式更改 CORS 并设法运行和调用 Web API,但得到 401 未经授权的错误 services.AddCors(options => options.AddPolicy("CorsPolicy", builder => { builder . AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() ; }));
猜你喜欢
  • 2020-10-28
  • 2018-12-15
  • 2021-01-22
  • 2015-05-06
  • 2021-06-09
  • 2018-07-18
  • 2021-06-27
  • 2018-10-16
  • 2020-06-28
相关资源
最近更新 更多