我创建了.Net Core API并配置了Windows身份验证。在我的角度应用程序中,我必须在每个请求中添加此选项withCredentials : true
。我做了一个put请求,但它返回给我:
我也尝试发帖请求,它不起作用只是获取请求工作。
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
})
}
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"))
}
.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);
}
}
即使我在控制器的顶部添加[AllowAnonymous]
它也不起作用。
更新:我的项目中有Cors,ConfigureServices
中的startup.cs:
services.AddCors(options =>
{
options.AddPolicy("AnyOrigin", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
在Configure
:
app.UseCors("AnyOrigin");
此外,如果我想测试邮递员我有这个错误(也在获取请求但在我的项目得到请求工作)
401 - 未授权:由于凭据无效,访问被拒绝。您无权使用您提供的凭据查看此目录或页面。
当我在我的api网站上(我使用招摇),我有这个:
你的连接不是私人的
首先要做的事情是:您可以使用像Postman这样的工具制作授权请求吗?如果是,则查看正确的请求标头(以及可能的有效负载),并找出Angular发送的请求中缺少的内容。
此外,您在控制台中有一个CORS错误(除其他外)。一个快速(和肮脏)的修复将是启用CORS用户端(对于Firefox有一个插件CORS Anywhere,以及Chrome的一些命令行选项),然后再次检查。
试试吧。