3

단일 페이지 앱을 구현하려고합니다. 나는 인증을 구현하기 위해 다른 프로젝트 (MVC4)에서 작업 코드 일부를 가져왔다. 지금은 쿠키가 설정되어 있지만, WebSecurity/User.Identity은 어떤 이유로 작동하지 않는 것 같습니다. 로그인 한 후 요청은 WebSecurity.IsAuthenticated 또는 User.Identity.IsAuthenticated을 통해이 인증 된 것으로 확인하지 않습니다. 왜 이런 일이 일어나는 지 아는 사람이 있습니까?WebAPI + SimpleMembership + WebSecurity - 인증 할 수 없습니까?

컨트롤러 코드 :

public class AccountController : ApiController { 

    private readonly UserService _userService; 

    public AccountController() {} 

    public AccountController(UserService userService) { 
     _userService = userService; 
    } 

    [AllowAnonymous] 
    [HttpGet] 
    [Route("api/authpayload")] 
    // This gets called when the app loads. Always, User.Identity.IsAuthenticated is false. 
    public HttpResponseMessage AuthPayload() { 
     var payload = new AuthPayloadDto(); 
     try { 
      var userId = WebSecurity.GetUserId(User.Identity.Name); 
      if (User.Identity.IsAuthenticated && userId > 0) { 
       payload.Username = User.Identity.Name; 
      } else { 
       LogOut(); 
       payload.IsAuthenticated = false; 
      } 
      return Request.CreateResponse(HttpStatusCode.OK, payload); 
     } catch (Exception e) { 
      return Request.CreateResponse(HttpStatusCode.InternalServerError, e); 
     } 
    } 

    [HttpPost] 
    [Route("api/login")] 
    [AllowAnonymous] 
    public HttpResponseMessage LogIn(LoginModel model) { 
     if (!ModelState.IsValid) 
      return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); 
     try { 
      if (WebSecurity.IsAuthenticated) 
       return Request.CreateResponse(HttpStatusCode.Conflict, "already logged in."); 
      if (!WebSecurity.UserExists(model.Username)) 
       return Request.CreateResponse(HttpStatusCode.Conflict, "User does not exist."); 
      if (WebSecurity.Login(model.Username, model.Password, persistCookie: model.RememberMe)) { 
       // This code always gets hit when I log in, no problems. I see a new cookie get sent down as well, using Chrome debugger. 
       var payload = new AuthPayloadDto(); 
       return Request.CreateResponse(HttpStatusCode.OK, payload); 
      } 
      LogOut(); 
      return Request.CreateResponse(HttpStatusCode.Forbidden, "Login Failed."); 
     } catch (Exception e) { 
      return Request.CreateResponse(HttpStatusCode.InternalServerError, e); 
     } 
    } 

의 Web.config가 :

<system.web> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" /> 
    <authentication mode="Forms"> 
     <forms loginUrl="~/" timeout="2880" /> 
    </authentication> 
    <roleManager enabled="true" defaultProvider="simple"> 
     <providers> 
     <clear /> 
     <add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" /> 
     </providers> 
    </roleManager> 
    <membership defaultProvider="simple"> 
     <providers> 
     <clear /> 
     <add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" /> 
     </providers> 
    </membership> 
    <!-- 
      If you are deploying to a cloud environment that has multiple web server instances, 
      you should change session state mode from "InProc" to "Custom". In addition, 
      change the connection string named "DefaultConnection" to connect to an instance 
      of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express. 
     --> 
    <sessionState mode="InProc" customProvider="DefaultSessionProvider"> 
     <providers> 
     <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" /> 
     </providers> 
    </sessionState> 

    </system.web> 

만료되지 않았 로그인 후 보내지는 쿠키, 그리고 후속 요청을 다시 전송받을 않지만, IsAuthenticated는 항상 그릇된. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

는 업데이트

:

나는이 모든 작업을 진행하기 위해 다음과 같은 내 Web.config의 업데이트 :

<system.web> 
    <authentication mode="None" /> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" /> 
    <roleManager enabled="true" defaultProvider="SimpleRoleProvider"> 
     <providers> 
     <clear /> 
     <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" /> 
     </providers> 
    </roleManager> 
    <membership defaultProvider="SimpleMembershipProvider"> 
     <providers> 
     <clear /> 
     <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" /> 
     </providers> 
    </membership> 
    </system.web> 

하지만이 경우 사람이 열어두고 싶은 이유는이 작품에 대한 설명이있다 ; 나는 꽤 길을 잃었다. MSSQL 내 현재 MVC 4 프로젝트에서

+0

을 추가하여 일부 컨트롤러 또는 작업에 대한 액세스를 제한했다 만들어 내 개인적인 경험으로는 MVC의 웹 API (MVC 4와 5 사용)를 통해 인증을받을 수 없었습니다. 사용자가 MVC의 소셜 로그인을 통해 로그인하면 현재 사용자가 웹 API를 통해 로그인했는지 여부를 확인할 수 있습니다. 그러나 실제로 사용자 로그인을 시도하는 것은 항상 어려움을 겪고 있습니다. 이 문제를 해결하기 위해 MVC와 함께 작동하는 타사 인증 서비스 (예 : auth0.com)가 있습니다. –

+0

문제를 해결 했습니까? 나도 같은 문제에 직면하고있다. 그것은 사용자를 성공적으로 확인하지만 isauthenticated는 여전히 거짓이다. – UmarKashmiri

답변

0

, 의 난 그래서 난 그냥

[Authorize] 
//[InitializeSimpleMembership] 
public partial class AccountController : Controller 

에 의해 내가 InitializeSimpleMembershipAttribute

를 비활성화 매우 간단 memmbership 제공 를 원하고 세계에이 코드를 추가하는 간단한 하나 .asax에서 Application_Start

WebSecurity.InitializeDatabaseConnection(
      connectionStringName: "DefaultConnection", 
      userTableName: "UserProfile", 
      userIdColumn: "UserID", 
      userNameColumn: "UserName", 
      autoCreateTables: true); 

내 SQL 데이터베이스 응용 프로그램은 그들 중 몇 가지 테이블 역할 및 UserInRoles는 그냥 관리자, 고객, 등 ... 처럼 필요한 역할을 추가하고 난에서이 코드

[Authorize(Roles = "Admin")] 
public class MessagesController : Controller