【问题标题】:Angular 5 authenticate with web apiAngular 5 使用 web api 进行身份验证
【发布时间】:2018-01-02 20:35:18
【问题描述】:

我尝试将我的登录凭据发布到我的 asp.net 核心 web api。但每次我这样做时都会收到此消息。

选项 XHR http://localhost:64989/api/auth/login [HTTP/1.1 415 不支持的媒体类型 16ms]

ERROR Object { headers: Object, status: 0, statusText: "Unknown Error", url: null, ok: false, name: "HttpErrorResponse", message: "Http failure response for (unknown ...", error: error }

我的代码在 Angular 端看起来像这样:

login( email:string, password:string ) :Observable<boolean>{

  return this.http.post('http://localhost:64989/api/auth/login', {email, password}, {headers: new HttpHeaders().set('Content-Type', 'application/json')})
   .map(data => {
     let userAuth = data;
     if(userAuth){
       localStorage.setItem('currentUser', JSON.stringify(userAuth));
       return true;
     }else{
       return false;
     } 
   });
}

在服务器端,我有一个 web api,它应该检查登录凭据。这适用于邮递员,但不适用于角度。 Web Api 是用 Asp.net core 2 制作的。

 [AllowAnonymous]
    [HttpPost("CreateToken")]
    [Route("login")]
    public async Task<IActionResult> Login([FromBody] LoginDTO model)
    {
        try
        {
            var user = await _userManager.FindByNameAsync(model.Email);
            if (user == null)
            {
                return Unauthorized();
            }

            var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);

            if (signInResult.Succeeded)
            {
                var userClaims = await _userManager.GetClaimsAsync(user);

                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Email, user.Email)
                }.Union(userClaims);

                var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtToken:Key"]));
                var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);

                var jwtSecurityToken = new JwtSecurityToken(
                    issuer: _configuration["JwtToken:Issuer"],
                    audience: _configuration["JwtToken:Audience"],
                    claims: claims,
                    expires: DateTime.UtcNow.AddMinutes(60),
                    signingCredentials: signingCredentials
                    );
                return Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
                    expiration = jwtSecurityToken.ValidTo
                });
            }
            return Unauthorized();
        }
        catch (Exception ex)
        {
            _logger.LogError($"error while creating token: {ex}");
            return StatusCode((int)HttpStatusCode.InternalServerError, "error while creating token");
        }
    }

【问题讨论】:

    标签: asp.net angular authentication httpclient access-token


    【解决方案1】:

    我想我找到了一种在开发中对我有用的方法。不是生产。

    问题出在 Web API 上。如果您来自与您的 web api 不同的来源,它不会是 awnser。就我而言,如果我尝试从 http://localhost:4200/ 上的客户端应用程序调用我的 web api,并且我的 web api 正在 http://localhost:64989 上运行,我会遇到这个问题。如果您的客户端应用程序和服务器端应用程序在同一个域下,您将不会有任何问题。我将在生产中将它放在同一个域中。所以我仍然需要开发人员的解决方法。

    在我的 ASP.NET 核心应用程序中,我可以将 CORS(跨源资源共享)添加到 Startup。

      public void ConfigureServices(IServiceCollection services)
      {
            services.AddCors();
            //add cors bevor mvc
            services.AddMvc();
      }
    
     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
    
            loggerFactory.AddConsole();
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
    
                app.UseCors(builder =>
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader());
            }
    
    
            app.UseAuthentication();
    
    
            app.UseMvc();
        }
    

    在 IsDevelopment 中定义使用 cors。在这里,您可以定义允许哪些来源,哪些不允许。我允许任何用于开发,因为我不会在生产中遇到这个问题。

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 2017-06-02
      • 1970-01-01
      • 2016-06-17
      • 2018-03-19
      • 2015-01-12
      • 1970-01-01
      • 2018-07-16
      • 2013-11-16
      相关资源
      最近更新 更多