2013-09-11 1 views
0

MVC JQuery와 인증, 나는 형태로 기호를 단일 페이지 응용 프로그램

@if (@User.Identity.IsAuthenticated) 
{ 
    <div>Welcome @User.Identity.Name</div> 
} 
else 
{ 
    <input type="text" id="username" name="username" placeholder="" class="input-xlarge"> 
    <input type="password" id="password" name="password" placeholder="" class="input-xlarge"> 
    <button id="loginBtn" class="btn btn-success">Login</button> 
} 

일부 JQuery와

,

$("#loginBtn").click(function() { 
    Authenticate();    
}); 

function Authenticate() { 
    $.post("/Home/Authenticate", { username: "John", password: "test" }, function (data) { 
     $('#loginArea').replaceWith(data); 
    }); 
} 

작동하지 그리고 일부 서버 측 코드는 요청을 처리 할 수 ​​있습니다.

[HttpPost] 
    public ActionResult Authenticate(string username, string password) 
{ 

    var ticket = new FormsAuthenticationTicket(
     1, 
     username, 
     DateTime.Now, 
     DateTime.Now.AddDays(5), 
     true, 
     string.Empty, 
     FormsAuthentication.FormsCookiePath); 

    var encTicket = FormsAuthentication.Encrypt(ticket); 

    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); 

    return PartialView("_login"); 
} 

이상한 점은 초기 작동이 아니라 작동한다는 것입니다. 돌려 주어지는 View는, 유저가 인증 되어도 갱신되지 않습니다. 페이지를 새로 고치면 모든 것이 예상대로 작동합니다. 문제는 이것이 단일 페이지 응용 프로그램이므로 페이지 새로 고침을 강제하고 싶지 않습니다.

반환 된 PartialView가 "환영"텍스트를 렌더링하지 않는 이유가 있습니까?

+0

로그인 한 사용자를 설정했거나 수동으로 쿠키를 다시 클라이언트로 보내고 있습니까? –

+0

나의 이해는 쿠키를 추가하는 것이 "사용자를 로깅"하는 것이 었습니다. 서버 측에서해야 할 다른 사람이 있습니까? – Kye

+0

쿠키를 다시 보내면 서버가 수신하면 사용자를 기록하지만 쿠키는 요청에 대한 응답이 아니므로 * this * 요청을 위해 User.Identity는 채워지지 않습니다. 직접 대답은 확실치 않지만 두 가지 해결 방법은 1) "justAuthenticated"또는 무엇인가에 대한 모델의 속성을 사용하거나 2) 클라이언트에서 추가 AJAX 호출을 수행 한 다음 쿠키 –

답변

0

요청에 양식 인증 쿠키가 포함되어 있으므로 이후 요청 만 인증됩니다.

그래서 초기 호출시 현재 주체를 사용하지 않도록주의해야했습니다.