Angular 7和C#核心。为什么我要获取http:// localhost:5000 / Account / Login?ReturnUrl =%2Fapi%2Fimage?

时间:2019-05-16 08:09:30

标签: c# angular identity jwt-auth

我使用身份授权和JWT。

[HttpPost("/token")]
public async Task Token([FromBody] User user)
{
  var username = user.Login;
  var password = user.Password;

  var identity = await GetIdentityAsync(username, password);
  if (identity == null)
  {
    Response.StatusCode = 400;
    await Response.WriteAsync("Invalid username or password.");
    return;
  }

  var now = DateTime.UtcNow;
  var jwt = new JwtSecurityToken(
          issuer: AuthOptions.ISSUER,
          audience: AuthOptions.AUDIENCE,
          notBefore: now,
          claims: identity.Claims,
          expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
          signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(),
            SecurityAlgorithms.HmacSha256));

  var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

  var response = new
  {
    access_token = encodedJwt,
    user = new
    {
      login = user.Login,
      role = identity.FindFirst(ClaimsIdentity.DefaultRoleClaimType).Value
    }
  };

  Response.ContentType = "application/json";
  await Response.WriteAsync(JsonConvert.SerializeObject(response,
    new JsonSerializerSettings { Formatting = Formatting.Indented }));
}

async Task<ClaimsIdentity> GetIdentityAsync(string userName, string password)
{
  var result = await _signInManager.PasswordSignInAsync(userName, password, false, false);
  if (result.Succeeded)
  {
    var user = await _userManager.FindByNameAsync(userName);
    if (user != null)
    {
      var role = (await _userManager.GetRolesAsync(user)).SingleOrDefault();

      var claims = new List<Claim>
      {
        new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName),
        new Claim(ClaimsIdentity.DefaultRoleClaimType, role)
      };

      return new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
    }
  }

  return null;
}

授权成功。我在客户端应用程序上获得令牌。但是,然后我在服务器上发送了图像(URL:'/ api / image'),我收到错误消息“ http://localhost:5000/Account/Login?ReturnUrl=%2Fapi%2Fimage的Http故障响应:404未找到”。为什么我得到这个网址而不是http://localhost:5000/api/image?而如何解决这个问题?

发送图像:

add() {
    const id = uuid.v4();
    const formData = new FormData();
    formData.append('image', this.file, id);

    this.imageService.upload(formData).subscribe(() => {

    });
}

onSelectFile(event) {
    this.file = event.target.files[0];

    const reader = new FileReader();
    reader.readAsDataURL(this.file);
    reader.onload = (event) => {
        this.url = event.target['result'];
    };
}

ImageService:

url = 'api/image';
headers: HttpHeaders;

constructor(private httpService: HttpService, private authService: AuthService) {
    const token = localStorage.getItem(this.authService.tokenKey);
    this.headers = new HttpHeaders().set('Authorization', 'Bearer ' + token);
}

upload(image: FormData) {
    return this.httpService.postData(this.url, image, this.headers);
}

HttpService:

postData(url: string, body: any, headers?: HttpHeaders) {
    return this.http.post(`${environment.apiUrl}/${url}`, body, { headers });
}

0 个答案:

没有答案