Angular 5使用web api进行身份验证

问题描述 投票:1回答:1

我尝试将我的登录凭据发布到我的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核心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个回答
1
投票

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

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

在我的ASP.NET核心应用程序中,我可以将CORS(Cross Origin资源共享)添加到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。在这里你可以定义哪个来源是允许的,哪个不是。我允许任何开发者,因为我不会在生产中遇到这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.