public ActionResult Login(CredentialsModel model)
{
authenticator.Authenticate(model.Username, model.Password);
if (authenticator.Authenticated)
{
return Redirect();
}
}
...
public class Authenticator : IAuthenticator
{
public bool Authenticated
{
get { return HttpContext.Current.User.Identity.IsAuthenticated; }
}
public void Authenticate(string username, string password)
{
var authenticated = FormsAuthentication.Authenticate(username, password);
if (authenticated)
FormsAuthentication.SetAuthCookie(username, false);
}
public void Logout()
{
FormsAuthentication.SignOut();
}
}
앞서 언급 한 작업 메서드가 메서드에 유효한 자격 증명을 제공 Authenticate
하면 Authenticated
속성은 분명히 잘못된 false를 반환합니다.
작업 메서드가 두 번째로 일부 자격 증명을 제공 하면 Authenticated
속성이 true를 반환합니다.
컨텍스트가 즉시 업데이트되지 않는다는 사실과 관련이 있다고 생각합니다. 실제로 FormsAuthentication.Authenticate
액션 메서드에서의 즉각적인 반환 값을 사용하여이 버그를 해결 했지만 이 버그가 발생하는 이유 를 알고 싶습니다 .
HTTP 컨텍스트에서 첫 번째 호출과 함께 전송 된 사용자는 인증 되지 않았기 때문입니다 (그러나 후속 호출에서는 그 이후에 올 것입니다). 이 줄 뒤 :
var authenticated = FormsAuthentication.Authenticate(username, password);
당신은 그것을 볼 수 있습니다 authenticated != Authenticated
. 왜? 에서 MSDN :
[HttpContext] 개별 HTTP 요청에 대한 모든 HTTP 관련 정보를 캡슐화합니다.
이는 응답 이나 미래 상태 (출력)가 아닌 요청 (입력) 에 따라 작동 함을 의미합니다 . 컨트롤러의 메서드 내에서 수행 하면 여전히 .SignOut()
HttpContext.Current.User.Identity.IsAuthenticated
true
할 수있는 일은 다음에 대한 부울 반환 값을 추가하는 것입니다 Authenticate()
.
public bool Authenticate(string username, string password)
{
var authenticated = FormsAuthentication.Authenticate(username, password);
if (authenticated)
FormsAuthentication.SetAuthCookie(username, false);
return authenticated:
}
컨트롤러의 코드를 다음과 같이 변경합니다.
if (authenticator.Authenticate(model.Username, model.Password))
{
return Redirect();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다