在 .net core 2.1 中使用 cookie,授权属性,为应用程序创建会话
Use cookie, authorize attribute, create session for application in .net core 2.1
我不熟悉 .net core 2.1 授权、身份验证,cookies.I 正在尝试实现一个 Web 应用程序
1. 向带有令牌的用户发送电子邮件。
2. 用户点击电子邮件中提供的 link 以登录应用程序
3. 我们为用户创建一个 cookie/session ,只要浏览器 window 打开就有效。
3. authorize 属性必须用在控制器操作上,并且登录用户必须可以一起访问 linking 页面
4.在mvc视图中显示登录用户名
这是我目前的情况:
Startup.cs
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using VVF_Entity.Models;
using Prototype.Services;
using System;
namespace Prototype
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var AppSettingsSection = Configuration.GetSection("AppSettings");
services.AddHttpContextAccessor();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
//.AddCookie(options =>
//{
// options.LoginPath = "/User/Login/";
//});
services.AddMvc();
services.AddSingleton<IEmailSender, AuthMessageSender>();
services.AddDbContext<VVFContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
UserController.cs
public async Task<ActionResult> Login(Guid authcode)
{
if (authcode == null)
{
return NotFound();
}
var submitter = await _context.Submitters
.FirstOrDefaultAsync(m => m.Token == authcode);
if (submitter == null)
{
return NotFound();
}
else
{
if(submitter.ModifiedDate > DateTime.Now.AddHours(-1))
{
submitter.EmailConfirmed = true;
_context.Update(submitter);
await _context.SaveChangesAsync();
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, submitter.FirstName)
};
ClaimsIdentity userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(principal);
//return View(submitter);
return RedirectToAction("Index", "Vehicles");
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
VehiclesController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using VVF_Entity.Models;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace VVF_Web.Controllers
{
[Authorize]
public class VehiclesController : Controller
{
private readonly VVFContext _context;
public VehiclesController(VVFContext context)
{
_context = context;
}
// GET: Vehicles
public async Task<IActionResult> Index()
{
// TO DO: Where SubmitterId = Authenticated Submitter
var VVFContext = _context.Vehicles.Include(v => v.ExemptReason).Include(v => v.Submitter);
return View(await VVFContext.ToListAsync());
}
我得到一个 404 并被定向到这个 url:http://localhost:5036/Account/Login?ReturnUrl=%2FVehicles 而不是 vehicles/index 并且我也不确定是否设置了 cookie 或用户是否可以显示其他页面结果。
您需要在 services.AddAuthentication(...)
下面和配置 app.UseAuthentication();
添加 services.AddAuthorization();
退出:
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
您可以像这样获取用户详细信息:
public class YourControllerNameController : Controller
{
public IActionResult YourMethodName()
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value // will give the user's userId
var userName = User.FindFirst(ClaimTypes.Name).Value // will give the user's userName
var userEmail = User.FindFirst(ClaimTypes.Email).Value // will give the user's Email
}
}
我不熟悉 .net core 2.1 授权、身份验证,cookies.I 正在尝试实现一个 Web 应用程序 1. 向带有令牌的用户发送电子邮件。 2. 用户点击电子邮件中提供的 link 以登录应用程序 3. 我们为用户创建一个 cookie/session ,只要浏览器 window 打开就有效。 3. authorize 属性必须用在控制器操作上,并且登录用户必须可以一起访问 linking 页面 4.在mvc视图中显示登录用户名
这是我目前的情况: Startup.cs
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using VVF_Entity.Models;
using Prototype.Services;
using System;
namespace Prototype
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var AppSettingsSection = Configuration.GetSection("AppSettings");
services.AddHttpContextAccessor();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
//.AddCookie(options =>
//{
// options.LoginPath = "/User/Login/";
//});
services.AddMvc();
services.AddSingleton<IEmailSender, AuthMessageSender>();
services.AddDbContext<VVFContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
UserController.cs
public async Task<ActionResult> Login(Guid authcode)
{
if (authcode == null)
{
return NotFound();
}
var submitter = await _context.Submitters
.FirstOrDefaultAsync(m => m.Token == authcode);
if (submitter == null)
{
return NotFound();
}
else
{
if(submitter.ModifiedDate > DateTime.Now.AddHours(-1))
{
submitter.EmailConfirmed = true;
_context.Update(submitter);
await _context.SaveChangesAsync();
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, submitter.FirstName)
};
ClaimsIdentity userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(principal);
//return View(submitter);
return RedirectToAction("Index", "Vehicles");
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
VehiclesController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using VVF_Entity.Models;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace VVF_Web.Controllers
{
[Authorize]
public class VehiclesController : Controller
{
private readonly VVFContext _context;
public VehiclesController(VVFContext context)
{
_context = context;
}
// GET: Vehicles
public async Task<IActionResult> Index()
{
// TO DO: Where SubmitterId = Authenticated Submitter
var VVFContext = _context.Vehicles.Include(v => v.ExemptReason).Include(v => v.Submitter);
return View(await VVFContext.ToListAsync());
}
我得到一个 404 并被定向到这个 url:http://localhost:5036/Account/Login?ReturnUrl=%2FVehicles 而不是 vehicles/index 并且我也不确定是否设置了 cookie 或用户是否可以显示其他页面结果。
您需要在 services.AddAuthentication(...)
下面和配置 app.UseAuthentication();
services.AddAuthorization();
退出:
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
您可以像这样获取用户详细信息:
public class YourControllerNameController : Controller
{
public IActionResult YourMethodName()
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value // will give the user's userId
var userName = User.FindFirst(ClaimTypes.Name).Value // will give the user's userName
var userEmail = User.FindFirst(ClaimTypes.Email).Value // will give the user's Email
}
}