您好我正在使用现有的MVC应用程序,正在测试使用http.get进行ajax调用登录并在Angular 4应用程序中发布(我无法在服务器端进行更改)。我在MVC.net端创建了一个LoginClint,如果用户已登录,则返回一个简单的JsonResult(这仅用于测试)。我使用ng服务代理方法(https://github.com/angular/angular-cli/wiki/stories-proxy)设置了Angular 6外部应用程序。 它将在同一个IIS站点下运行,因此同一个域。
为了能够登录我基本上在登录页面上获取读取html并使用JavaScript取出__RequestVerificationToken并将其存储为变量(因为我在get中设置了“withCredentials:true”,所以会自动设置cookie呼叫)。然后我在帖子中使用它来登录用户。
它有效,但我有点不确定我正在做的什么事情会破坏安全性?我发现的大多数示例都是使用安全令牌。
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult LoginClient(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (((SomethingMembershipProvider)Membership.Provider).ValidateUser(model.UserName, model.Password, ServiceType.Something))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return new JsonResult { Data = new { status = "ok" } };
}
else
{
ModelState.AddModelError("", "Feil brukernavn og/eller passord");
}
}
return new JsonResult();
}
角度代码
username: string;
password: string;
constructor(private http: HttpClient, private router: Router) { }
verificationToken:string;
ngOnInit() {
this.onGetTokenClicked(); // I have a button inital for testing
}
onLoginClicked(): void {
let loginHeaders = new HttpHeaders({
"Content-Type": "application/x-www-form-urlencoded"
});
const body = new window.URLSearchParams();
body.set("UserName", this.username);
body.set("Password", this.password);
body.set("__RequestVerificationToken", this.verificationToken);
this.http.post(`http://localhost:4200/Account/Home/LoginClient`, body.toString(), {
headers: loginHeaders,
withCredentials: true
}).subscribe(s => {
this.router.navigate(["/"]);
});
}
onGetTokenClicked(): void {
this.http.get(`http://localhost:4200/Account/Home/Login`, {responseType: "text", withCredentials: true}).subscribe(t => {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(t, "text/html");
var e:HTMLInputElement = xmlDoc.getElementsByName("__RequestVerificationToken").item(0) as HTMLInputElement;
this.verificationToken = e.value;
});
}