2017-03-27 20 views
1

CookieAuthenticationを使用して、自分の.netコアサイトの現在のユーザーを認証しようとしています。 ログインした後、私はどんなURLにもリダイレクトされていません。私はまだログインフォームにいます。デバッグするとき、私は私の "authtorized"コントローラに移動すると、私のUserがまだ認証されていないことを知り、私は '302 found'(?)を取得します。ASP.NETコアでのCookieによる認証

私はstartup.csに以下の設定をしています。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
     { 
      loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
      loggerFactory.AddDebug(); 

      if (env.IsDevelopment()) 
      { 
       app.UseDeveloperExceptionPage(); 
       app.UseBrowserLink(); 
      } 
      else 
      { 
       app.UseExceptionHandler("/Home/Error"); 
      } 

      app.UseStaticFiles(new StaticFileOptions 
      { 
       OnPrepareResponse = ctx => 
       { 
        const int durationInSeconds = 60 * 60 * 24; 
        ctx.Context.Response.Headers[HeaderNames.CacheControl] = 
         "public,max-age=" + durationInSeconds; 
       } 
      }); 
      app.UseCookieAuthentication(new CookieAuthenticationOptions() 
      { 
       AuthenticationScheme = "myCustomScheme", 
       LoginPath = new PathString("/Account/Unauthorized/"), 
       AccessDeniedPath = new PathString("/Account/Forbidden/"), 
       AutomaticAuthenticate = true, 
       AutomaticChallenge = true, 
       CookieSecure = env.IsDevelopment() ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always 
      }); 
      app.UseMvc(routes => 
      { 

       routes.MapRoute(
        name: "default", 
        template: "{controller=Home}/{action=Index}/{id?}"); 
      }); 
     } 

AdminController.cs マイ保護コントローラ(私はスキームを指定する必要がある場合はわからないイム)

[Authorize(ActiveAuthenticationSchemes = "myCustomScheme")] 
    public class AdminController : Controller 
    { 
     public IActionResult Index() 
     { 
      return View(); 
     } 
    } 

AccountController:

[HttpPost] 
     public async Task<IActionResult> Unauthorized(LoginModel model, string ReturnUrl) 
     { 
      if (ModelState.IsValid) 
      { 
       if (model.Username.ToLower() == "test" && model.Password == "test") 
       { 
        var principal = User as ClaimsPrincipal; 
        await HttpContext.Authentication.SignInAsync("myCustomScheme", principal, new AuthenticationProperties 
        { 
         IsPersistent = true, 
        }); 

        return RedirectToAction(nameof(AdminController.Index)); 

       } 
       return View(model); 
      } 
      return View(model); 

     } 

答えて

3

Unauthorizedアクションメソッドで使用しますにクレームがありません。代わりに

var principal = User as ClaimsPrincipal; 

のあなたは、自分の主張を持つ新しいアイデンティティを作成し、SignIn方法にそれを渡す必要があります。aspnet/Securityレポで見つけることができクッキーを使用する方法について

var principal = new ClaimsPrincipal(new ClaimsIdentity(
      new[] { new Claim(ClaimTypes.Name, model.Username) }, 
      "myCustomScheme")); 

await HttpContext.Authentication.SignInAsync("myCustomScheme", principal, new AuthenticationProperties 
       { 
        IsPersistent = true, 
       }); 

良い簡単なサンプル

0

またConfigureServicesの下であなたのStartup.cs内のすべてのポリシーを設定する必要があります:

 public void ConfigureServices(IServiceCollection services) 
     { 
      // Add framework services. 
      services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

      services.AddIdentity<ApplicationUser, IdentityRole>() 
       .AddEntityFrameworkStores<ApplicationDbContext>() 
       .AddDefaultTokenProviders(); 

      services.AddMvc(); 

      // some samples (this section must contain all the authorization policies used anywhere in the application) 
      services.AddAuthorization(options => { 
       options.AddPolicy("EmployeeOnly", policy => policy.RequireClaim("CompanyName", "YourCompany")); 
       options.AddPolicy("SalesOnly", policy => { policy.RequireClaim("department", "sales"); }); 
       options.AddPolicy("HumanResources", policy => { policy.RequireClaim("department", "HR"); }); 
       options.AddPolicy("FinanceSupervisor", policy => { 
        policy.RequireClaim("department", "finance"); 
        policy.RequireClaim("jobTitle", "supervisor"); 
       }); 
      }); 


      // Add application services. 
      services.AddTransient<IEmailSender, AuthMessageSender>(); 
      services.AddTransient<ISmsSender, AuthMessageSender>(); 
     } 

残りは(それは上記で動作させるためにここにあるサンプル)ほとんど同じです:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     app.UseCookieAuthentication(new CookieAuthenticationOptions() 
     { 
      AuthenticationScheme = "yourcookiename",      
      CookieName = "YourCookieName", 
      LoginPath = new PathString("/Account/Login"), 
      AccessDeniedPath = new PathString("/Account/AccessDenied"), 
      AutomaticAuthenticate = true, 
      AutomaticChallenge = true 
     }); 

     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     if (env.IsDevelopment()) { 
      app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); 
     } else { app.UseExceptionHandler("/Home/Error"); } 

     app.UseStaticFiles(); 
     app.UseIdentity(); 

     // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715 

     app.UseMvc(routes => { 
      routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); 
     }); 

    } 

をごAccountController.cs下で、コンストラクタでデータベースからポリシーを引っ張って、あなたのデシベルのコンテキストを追加

ログインの下
private readonly YourDB_Context _yourDB_context; 

    public AccountController(YourDB_Context context) 
    { 
     _yourDB_context = context; 
    } 

はrespetiveのセクションで、あなたのコントローラの下に続いて

[HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) 
    { 
     ViewData["ReturnUrl"] = returnUrl; 
     if (ModelState.IsValid) 
     {     
      // modify below to match your user table structure to pull user info 
      userTable vUser = _yourDB_Context.userTable.SingleOrDefault(m => m.Email == model.Email && m.password == model.Password); 
      const string Issuer = "optional: company name/issuer name"; 
      List<Claim> claims = new List<Claim> { 
       new Claim("CompanyName", "YourCompany"), // hardcoded to authorize EmployeeOnly 
       //new Claim("department", "HR"), 
       //new Claim(ClaimTypes.Name, vUser.Name, ClaimValueTypes.String, Issuer), 
       new Claim(ClaimTypes.Email, vUser.Email, ClaimValueTypes.String, Issuer), 
       //new Claim(ClaimTypes.Role, vUser.Roles, ClaimValueTypes.String, Issuer) 
      }; 
      var userIdentity = new ClaimsIdentity(claims, "local", "name", "role"); 
      var userPrincipal = new ClaimsPrincipal(userIdentity); 
      await HttpContext.Authentication.SignInAsync("yourcookiename", userPrincipal, 
       new AuthenticationProperties { 
        ExpiresUtc = DateTime.UtcNow.AddMinutes(30), 
        IsPersistent = false, 
        AllowRefresh = false 
       }); 
      return RedirectToLocal(returnUrl);     
     } 

     return View(model); 
    } 

を追加承認を必要と

[Authorize(Policy = "EmployeeOnly")] 
public class HomeController : Controller 
{ 
    public IActionResult Index() 
    { 
     return View(); 
    } 

    [Authorize(Policy = "HumanResources")] 
    public IActionResult Contact() 
    { 
     ViewData["Message"] = "Your contact page."; 

     return View(); 
    } 

} 
関連する問題