2017-10-23 4 views
0

Asp.NET Core V2에 올바르게 로그인하는 방법에 대한 질문. ASP.NET ID를 사용하고 있습니다.Asp.NET Core 2에 로그인

내 OnPostAsync() 메소드가 아래에 있습니다. 내 코드는 성공적으로 사용자 이름과 암호를 가져 와서 signin manager를 호출하고 성공적으로 true를 반환합니다. 적절한 로그인 방법은 SigninPasswordAsync를 호출하는 것입니다. 성공한 결과가 다시 나타납니다.

따라서 리디렉션이 발생하면 LoggedIn 면도기 페이지로 리디렉션됩니다. PageModel의 내용은 다음과 같습니다. 문제는 [Authorize] 속성을 사용하면 페이지가로드되지 않고 [인증] 속성 조건이 충족 될 때 예상되는 로그인 페이지로 리디렉션됩니다. 권한 부여 조건이 충족되지 않습니다. 이것을 파고 들자면 HttpContext.User가 그 안에 많은 콘텐츠를 갖고 있지 않은 것 같습니다. SigninPasswordAsync 메서드 외에 다른 것을 호출하거나 다른 특성을 사용해야한다고 가정합니다. 생각? 다른 일을해야합니까? 나는이 시점에서해야 할 일에 대해 분실했기 때문에 어떤 생각을해도 좋습니다. 감사.

[Authorize] 
public class LoggedInModel : PageModel 
{ 
    public void OnGet() 
    { 
     var use = HttpContext.User; 
    } 
} 

**** 업데이트 ****************************


내 Startup.cs 파일에서 다음과 같은 내용을 추가하고있다 :

public static IConfigurationRoot Configuration { get; set; } 
    // This method gets called by the runtime. Use this method to add services to the container. 
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 
    public void ConfigureServices(IServiceCollection services) 
    { 
     var builder = new ConfigurationBuilder() 
     .SetBasePath(System.IO.Directory.GetCurrentDirectory()) 
     .AddJsonFile("appsettings.json"); 

     Configuration = builder.Build(); 
     services.AddDbContext<PooperAppDbContext>(options => 
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

     services.AddIdentity<ApplicationUser, ApplicationRole>() 
      .AddEntityFrameworkStores<PooperAppDbContext>() 
      .AddDefaultTokenProviders(); 

     services.AddScoped<SignInManager<ApplicationUser>>(); 

     services.Configure<IdentityOptions>(options => 
     { 
      // Password settings 
      options.Password.RequireDigit = true; 
      options.Password.RequiredLength = 8; 
      options.Password.RequireNonAlphanumeric = false; 
      options.Password.RequireUppercase = true; 
      options.Password.RequireLowercase = false; 
      options.Password.RequiredUniqueChars = 6; 

      // Lockout settings 
      options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); 
      options.Lockout.MaxFailedAccessAttempts = 10; 
      options.Lockout.AllowedForNewUsers = true; 

      // User settings 
      options.User.RequireUniqueEmail = true; 

     }); 

     services.ConfigureApplicationCookie(options => 
     { 
      // Cookie settings 
      options.Cookie.HttpOnly = true; 
      options.Cookie.Expiration = TimeSpan.FromDays(150); 
      options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login 
      options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout 
      options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied 
      options.SlidingExpiration = true; 
     }); 

     services.AddMvc().AddRazorPagesOptions(options => 
     { 
      //options.Conventions.AuthorizeFolder("/MembersOnly"); 
      options.Conventions.AuthorizePage("/Account/Logout"); 
      options.Conventions.AuthorizePage("/Account/LoggedIn", "PooperBasic, PooperPayer"); // with policy 
      //options.Conventions.AllowAnonymousToPage("/Pages/Admin/Login"); // excluded page 

      //options.Conventions.AllowAnonymousToFolder("/Public"); // just for completeness 
     }); 

     services.AddAuthorization(options => 
     { 
      options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator")); 
     }); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 
     if (env.IsDevelopment()) 
     { 
      //app.UseDeveloperExceptionPage(); 
     } 
     else 
     { 
      var options = new RewriteOptions() 
       .AddRedirectToHttps(); 
     } 
     app.UseMvc(); 
     app.UseAuthentication(); 
    } 
} 
+0

'Startup '에서'ConfigureServices'와'Configure' 내용을 모두 제공 할 수 있습니까? –

+0

그렇다면 시작시 인증을 설정하는 방법을 알아야합니다. 설정하지 않았다면, 인증 된 사용자는 없을 것입니다. – Geekn

+0

감사합니다. Startup.cs 파일의 내용을 추가했습니다. 나는 바보 같은 짓을하고 있다고 추측하지만 나는 그것을 알 수 없다. TIA. –

답변

2

당신은UseMvc 전에 UseAuthentication를 호출해야합니다. 모든 미들웨어는 파이프 라인의 일부로 실행되므로 사용자가 예상 할 경우 인증 미들웨어가 호출되지 않습니다.

미들웨어 파이프 라인에 대한 설명은 docs을 참조하십시오.

참고 : AddIdentity 항목이 처리하므로 services.AddScoped<SignInManager<ApplicationUser>>();으로 전화하지 않아도됩니다.

+0

완벽. 고마워 커크. –

관련 문제