如何解决 401 角度未经授权的问题?

use*_*293 6 put windows-authentication angular asp.net-core-2.1

我创建了 .Net Core API 并配置了 Windows 身份验证。在我的 angular 应用程序中,我必须在每个请求中添加此选项withCredentials : true。我做了一个放置请求,但它返回给我:

401(未授权) 401未授权 401网络

我也尝试发布请求,但它不起作用,只能获取请求工作。

auth.service.ts :

updateUser(id,lastlogin,ac,lastlogoff,picture){
  return this.http.put(`${this.config.catchApiUrl()}User/`+ id , {
    id : id ,
    picture : picture,
    lastLogin : lastlogin ,
    lastLogoff : lastlogoff ,
    ac: ac
  },{
    headers : this.header,
    withCredentials : true
  })
}
Run Code Online (Sandbox Code Playgroud)

auth.component.ts :

constructor(
private authService : AuthenticationService
) { }

loginToApplication(username :string){
    this.authService.updateUser(e["id"],lastLogin,e["ac"],e["lastLogoff"],e["picture"]).subscribe(
        console.log("enter"))
}
Run Code Online (Sandbox Code Playgroud)

.Net Core API 更新用户控制器:

[AllowAnonymous] // Even if I do this it doesn't work
[HttpPut("{id}")]
public async Task<ActionResult<User>> UpdateUser(int id, User user)
{
   try { 

        var ldapPath = Environment.GetEnvironmentVariable("path");
        var ldapUsername = Environment.GetEnvironmentVariable("user");
        var ldapPassword = Environment.GetEnvironmentVariable("psw");

        DirectoryEntry Ldap = new DirectoryEntry(ldapPath, ldapUsername, ldapPassword);

        DirectorySearcher searcher = new DirectorySearcher(Ldap);

        var users = await _context.Users.Include(t => t.Access).FirstOrDefaultAsync(t => t.Id == id);
        if (users == null)
        {
            return StatusCode(204);
        }

        if(users.Ac== 1 && user.Ac!= 1)
        {
            return BadRequest("You can't change an administrator profile");
        }

        searcher.Filter = "(SAMAccountName=" + users.Login.ToLower() + ")";

        SearchResult result = searcher.FindOne();

        if (result == null)
        {
            return NoContent();
        }

        DirectoryEntry DirEntry = result.GetDirectoryEntry();
        user.Lastname = DirEntry.Properties["sn"].Value.ToString();
        user.Fullname = DirEntry.Properties["cn"].Value.ToString();
        user.Firstname = DirEntry.Properties["givenname"].Value.ToString();
        user.Login = DirEntry.Properties["samaccountname"].Value.ToString().ToLower();
        user.Email = DirEntry.Properties["mail"].Value == null ? "No mail" : DirEntry.Properties["mail"].Value.ToString(); ;

        _context.Entry(users).CurrentValues.SetValues(user);
        _context.SaveChanges();
        return users;
        }
    catch (Exception ex)
    {
       return StatusCode(204,ex.Message);
    }

}
Run Code Online (Sandbox Code Playgroud)

即使我[AllowAnonymous]在控制器顶部添加它也不起作用。

更新: 我的项目中有 Cors,startup.csConfigureServices

services.AddCors(options =>
{
    options.AddPolicy("AnyOrigin", builder =>
    {
        builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();
    });
});
Run Code Online (Sandbox Code Playgroud)

Configure

app.UseCors("AnyOrigin");
Run Code Online (Sandbox Code Playgroud)

此外,如果我想对邮递员进行测试,我会遇到此错误(也在获取请求中,但在我的项目中获取请求工作)

401 - 未经授权:由于凭据无效,访问被拒绝。您无权使用您提供的凭据查看此目录或页面。

当我在我的 api 网站上时(我使用 swagger),我有这个:

你的连接不是私人的

mbo*_*jko 0

首先,您可以使用 Postman 这样的工具发出授权请求吗?如果是,则查看正确的请求标头(可能还有负载),并找出 Angular 发送的请求标头中缺少的内容。

此外,控制台中出现 CORS 错误(除其他外)。一个快速(&dirty)修复将是启用 CORS 用户端(Firefox 有一个插件 CORS Anywhere,以及 Chrome 的一些命令行选项),然后再次检查。

尝试一下。