1.新建asp net core程序
2 在startup.cs中注册mvc服务,验证服务
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options=>
{
options.EnableEndpointRouting = false;
});
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = new PathString("/Account/Login");
options.Cookie.Name = "YourAppCookieName";
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.SlidingExpiration = true;
options.AccessDeniedPath = new PathString("/Account/Denied");
});
}
3.在Startup.cs里面应用服务
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
// Enable security
app.UseAuthentication();
// Add MVC
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
4 添加ViewModelBase和IndexViewModel
namespace Ch08.Autho.Models
{
public class ViewModelBase
{
public ViewModelBase(string title = "")
{
Title = title;
ErrorMessage = "";
StatusCode = 0;
}
public string Title { get; set; }
public string ErrorMessage { get; set; }
public int StatusCode { get; set; }
}
}
namespace Ch08.Autho.Models
{
public class IndexViewModel : ViewModelBase
{
public IndexViewModel(string title) : base(title)
{
}
}
}
5 修改home/index视图
@model Ch08.Autho.Models.IndexViewModel
<h1>
PUBLIC FRONTEND! *** COOKme
</h1>
<hr />
<a role="button" class="btn btn-danger" href="~/secret">
Take me to the PRIVATE area
</a>
6 新建LoginViewModel
namespace Ch08.Autho.Models
{
public class LoginViewModel : ViewModelBase
{
public LoginViewModel()
{
RememberMe = true;
}
public string UserName { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
public string ReturnUrl { get; set; }
}
}
7 修改AccountController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Ch08.Autho.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication11.Controllers
{
public class AccountController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Login(LoginViewModel input)
{
if (input == null)
input = new LoginViewModel();
var td = TempData["Login-Error"] as string;
if (td != null)
{
input.ErrorMessage = td;
}
return View(input);
}
[HttpPost]
[ActionName("login")]
public async Task<IActionResult> TryLogIn(LoginViewModel input)
{
// Validate credentials
if (!ValidateCredentials(input.UserName, input.Password))
{
TempData["Login-Error"] = "Invalid credentials";
return RedirectToAction("login", "account");
}
var actualRole = (input.UserName == "dino" ? "Admin" : "Guest");
// Create the authentication cookie
var claims = new []
{
new Claim("DogName", input.UserName),
new Claim(ClaimTypes.Role, actualRole),
new Claim("Picture", ""),
};
var identity = new ClaimsIdentity(claims,
CookieAuthenticationDefaults.AuthenticationScheme,
"DogName",
ClaimTypes.Role);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity));
return Redirect(input.ReturnUrl ?? "~/");
}
private bool ValidateCredentials(string username, string password)
{
if (string.IsNullOrWhiteSpace(username) ||
string.IsNullOrWhiteSpace(password))
return false;
return username.Equals(password, StringComparison.CurrentCultureIgnoreCase);
}
}
}
8.新建Login视图
@model Ch08.Autho.Models.LoginViewModel
<div class="alert alert-warning">
@Model.ErrorMessage
</div>
<a href="@Url.Action("t", "account")">Twitter</a>
<form class="form-horizontal" method="post" asp-controller="Account" asp-action="login">
<input type="hidden" name="returnurl" value="@Model.ReturnUrl" />
<div class="form-group">
<label asp-for="UserName" class="col-sm-2 control-label">User name</label>
<div class="col-sm-10">
<input type="text" class="form-control"
id="username" name="username"
placeholder="User name">
</div>
</div>
<div class="form-group">
<label asp-for="Password" class="col-sm-2 control-label"> </label>
<div class="col-sm-10">
<input type="password" class="form-control"
id="password" name="password"
placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input asp-for="RememberMe" /> Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit"
class="btn btn-danger text-uppercase">
Sign in
</button>
</div>
</div>
</form>
9.新建SecretController,并新建Secret/index视图
using Ch08.Autho.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Ch08.Autho.Controllers
{
[Authorize]
public class SecretController : Controller
{
// ACTIONS
public IActionResult Index()
{
var model = new IndexViewModel("");
return View(model);
}
[Authorize(Roles = "Admin")]
public IActionResult Admin1()
{
var model = new IndexViewModel("");
return View(model);
}
public IActionResult Guest1()
{
var model = new IndexViewModel("");
return View(model);
}
}
}
@model Ch08.Autho.Models.IndexViewModel
<h2>
Welcome to the secret page!
</h2>
<a role="button"
class="btn btn-primary"
asp-controller="Secret"
asp-action="admin1">
Try to perform an admin-only task
</a>
<a role="button"
class="btn btn-primary"
asp-controller="Secret"
asp-action="guest1">
Regular task
</a>
10 新建Sercet/下面得ndex视图,Admin1,Guest1视图
@model Ch08.Autho.Models.IndexViewModel
<h2 class="text-danger">
ADMIN1 task
</h2>
@model Ch08.Autho.Models.IndexViewModel
<h2>
GUEST1 task
</h2>
11 访问会发现只有Admin可以访问到Admin1,而所有人可以访问到guest页面