邮差的{.Net Core 2 Web Api和Angular 401错误200

时间:2018-06-18 04:07:48

标签: angular firebase firebase-authentication asp.net-core-2.0

我正在尝试使用简单的.Net Core 2 Web Api和Angular实现Firebase身份验证。我的问题是,每当我尝试在Angular OnInit上调用我的web api时,它就会抛出401状态错误。但是,当我尝试使用Postman时,它给了我200 OK的状态。我是否错过了有棱角的一面?

以下是我的代码。

Startup.cs

public void ConfigureServices(IServiceCollection services)
{


    // Using firebase authentication
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = "https://securetoken.google.com/{project-id}";
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = "https://securetoken.google.com/{project-id}",
                        ValidAudience = "{project-id}"/*,
                        IssuerSigningKeys = GetSigningKeys().Result*/
                    };
                });



    // Enable Any Cross-Origin Requests (CORS)
    // You may change AllowAnyOrigin() to WithOrigins
    services.AddCors(options =>
                    {
                        options.AddPolicy("CorsPolicy",
                                                    policy => policy.AllowAnyOrigin()
                                                                        .AllowAnyMethod()
                                                                        .AllowAnyHeader()
                                                                        .AllowCredentials()
                                                                    .Build());
                    }
                );

    );

}

控制器

[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<SampleValue> Get()
    {
        var currentUser = HttpContext.User;
        int userAge = 0;

        var sampleValues = new SampleValue[]
        {
            new SampleValue { Id = 1, Text = "Text 1" },
            new SampleValue { Id = 2, Text = "Text 2" }
        };

        return sampleValues;
    }
}

app.component.ts

export class AppComponent implements OnInit {
  title = 'app';
  requestToken: string;

  constructor(private _webApiService: AppService) { }

  ngOnInit() {
    const config = {
      apiKey: '{api key}',
      authDomain: '{project-id}.firebaseapp.com',
      databaseURL: 'https://{project-id}.firebaseio.com',
      projectId: '{project-id}',
      storageBucket: ''
    };

if (!config.apiKey || !config.authDomain) {
  console.error('Need to add your Api key and authDomain (from Firebase project settings)');
  return;
}

firebase.initializeApp(config);

// if user is going through a 3rd party login, like Google
firebase.auth().getRedirectResult().then((result) => {
    if (!result.user) {
      // No user, so redirect to provider for authentication
      firebase.auth().signInWithRedirect(new firebase.auth.GoogleAuthProvider());
      // firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider());
    } else {
      result.user.getIdToken(true)
                  .then(token => {
                    this.requestToken = token;

                    this._webApiService.getNetCoreWebApi(this.requestToken)
                          .subscribe(res => {
                            console.log('Response from web api: ' + JSON.stringify(res));
                          });
                  });
    }
});

} }

app.service.ts

@Injectable()
export class AppService {
  private _apiUrl = 'http://localhost:53639/api/values';

  constructor(private _http: HttpClient) { }

  getNetCoreWebApi(token: string): Observable<any[]> {
    const h = new HttpHeaders();
    h.append('Content-Type', 'application/json');
    h.append('Authorization', `Bearer ${token}`);

return this._http.get<any[]>(this._apiUrl, { headers: h })
            .pipe(
              tap(res => console.log('Web api response: ' + JSON.stringify(res))),
              catchError(this.handleError)
            );
}

  private handleError(err: HttpErrorResponse) {
    console.log('ArenaService: ' + err.message);
    return Observable.throw(err.message);
  }
}

以下是控制台中的错误

  

http://localhost:53639/api/values的Http失败响应:401未经授权   zone.js:192 Uncaught TypeError:rxjs__WEBPACK_IMPORTED_MODULE_2 __。Observable.throw不是函数       at CatchSubscriber.push ../ src / app / app.service.ts.AppService.handleError [as selector](app.service.ts:26)       在CatchSubscriber.push ../ node_modules / rxjs / _esm5 / internal / operators / catchError.js.CatchSubscriber.error(catchError.js:33)       在TapSubscriber.push ../ node_modules / rxjs / _esm5 / internal / operators / tap.js.TapSubscriber._error(tap.js:61)       在TapSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.error(Subscriber.js:60)       在MapSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber._error(Subscriber.js:80)       在MapSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.error(Subscriber.js:60)

0 个答案:

没有答案