ASP . NETカスタム認証と認証の詳細ガイド.ネットMVC
36705 ワード
導入
このブログでは、認証アプリケーションの作り方を紹介します.あなたが知っているかもしれないように、認証と承認は彼らの役割に基づいてユーザーアクセスを与えるどんなウェブサイトプロジェクトのためにでも不可欠な局面です.カスタム認証を構築するには、メンバーシッププロバイダークラスを利用して、ユーザー資格情報(ユーザー名とパスワード)をチェックし、ロールプロバイダークラスを使用してロールに基づいてユーザー認証を検証します.
認証システムのシナリオは次のとおりです.
MVCアプリケーションの作成
まず、Visual Studioを開き、file ->新規プロジェクトを選択します
これは、新しいプロジェクトウィンドウをポップアップします.を選択します.NET Webアプリケーション(. NET Framework)をクリックし、[ OK ]をクリックします.
次に、CustommauthenticationMVCのようなプロジェクトの名前を付け、プロジェクトを保存したい場所を選択し、「プロジェクトを作成」ボタンをクリックします.
次に、MVCを選択し、「プロジェクト」をクリックしてプロジェクトを追加します.
プロジェクトが作成されると、Entity Framework(Code First Application)を使用してデータベースを確立します.
SQLデータベース部
Entity Frameworkでは、データベースを最初に、モデルを最初に、そしてコードを最初に含むデータベースをマップするためのさまざまなアプローチをとります.
データベースを構築するには、次の手順に従います.まず、データアクセスと呼ばれるフォルダを確立します.
これを実行するには、ソリューションエクスプローラー>「ADD >>新しいフォルダのプロジェクト名を右クリックします.
次に、ユーザとロールエンティティを追加します.
例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CustomAuthenticationMVC.DataAccess
{
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool IsActive { get; set; }
public Guid ActivationCode { get; set; }
public virtual ICollection<role> Roles { get; set; }
}
}
</role>
例using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CustomAuthenticationMVC.DataAccess
{
public class Role
{
public int RoleId { get; set; }
public string RoleName { get; set; }
public virtual ICollection<user> Users { get; set; }
}
}
</user>
最後のステップとして、AuthenticationDBコンテキストを追加してデータベースデータにアクセスできるようにします.通常、コンテキストクラスはDBContextクラスから派生します.例
using CustomAuthenticationMVC.DataAccess;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Configuration;
namespace CustomAuthenticationMVC.DataAccess
{
public class AuthenticationDB : DbContext
{
public AuthenticationDB()
:base("AuthenticationDB")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<user>()
.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(m =>
{
m.ToTable("UserRoles");
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
});
}
public DbSet<user> Users { get; set; }
public DbSet<role> Roles { get; set; }
}
}
</role></user></user>
では、次のコマンドをパッケージマネージャコンソールに入力します.続きを読む:Generate Thumbnail Using Asp.net Mvc
移行を可能にする
上記の側面を実行した後、今私たちのデータベースを構築を開始する準備が整いました.以下の順序でコマンドを実行します.
移行の初期化
データベースの更新
ご覧のように、すべてのテーブルが正常に追加されている.
メンバーシッププロバイダーとロールプロバイダーの実装
カスタムメンバーシッププロバイダーから始めましょう.
まず最初に、CustomshipProviderから継承するCustomMembershipクラスを構築します.
その後、以下のメソッドを要求します.
例
using CustomAuthenticationMVC.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace CustomAuthenticationMVC.CustomAuthentication
{
public class CustomMembership : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
if(string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
return false;
}
using (AuthenticationDB dbContext = new AuthenticationDB())
{
var user = (from us in dbContext.Users
where string.Compare(username, us.Username, StringComparison.OrdinalIgnoreCase) == 0
&& string.Compare(password, us.Password, StringComparison.OrdinalIgnoreCase) == 0
&& us.IsActive == true
select us).FirstOrDefault();
return (user != null) ? true : false;
}
}
password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
using (AuthenticationDB dbContext = new AuthenticationDB())
{
var user = (from us in dbContext.Users
where string.Compare(username, us.Username, StringComparison.OrdinalIgnoreCase) == 0
select us).FirstOrDefault();
if(user == null)
{
return null;
}
var selectedUser = new CustomMembershipUser(user);
return selectedUser;
}
}
public override string GetUserNameByEmail(string email)
{
using (AuthenticationDB dbContext = new DataAccess.AuthenticationDB())
{
string username = (from u in dbContext.Users
where string.Compare(email, u.Email) == 0
select u.Username).FirstOrDefault();
return !string.IsNullOrEmpty(username) ? username : string.Empty;
}
}
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override bool EnablePasswordReset
{
get
{
throw new NotImplementedException();
}
}
public override bool EnablePasswordRetrieval
{
get
{
throw new NotImplementedException();
}
}
public override int MaxInvalidPasswordAttempts
{
get
{
throw new NotImplementedException();
}
}
public override int MinRequiredNonAlphanumericCharacters
{
get
{
throw new NotImplementedException();
}
}
public override int MinRequiredPasswordLength
{
get
{
throw new NotImplementedException();
}
}
public override int PasswordAttemptWindow
{
get
{
throw new NotImplementedException();
}
}
public override MembershipPasswordFormat PasswordFormat
{
get
{
throw new NotImplementedException();
}
}
public override string PasswordStrengthRegularExpression
{
get
{
throw new NotImplementedException();
}
}
public override bool RequiresQuestionAndAnswer
{
get
{
throw new NotImplementedException();
}
}
public override bool RequiresUniqueEmail
{
get
{
throw new NotImplementedException();
}
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotImplementedException();
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override int GetNumberOfUsersOnline()
{
throw new NotImplementedException();
}
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new NotImplementedException();
}
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override bool UnlockUser(string userName)
{
throw new NotImplementedException();
}
public override void UpdateUser(MembershipUser user)
{
throw new NotImplementedException();
}
}
}
ご覧のように、MembershipProviderはCreateユーザー、ChangePassword、GetPasswordなどの多くのメソッドを提供していますが、ValidateUser、GetUser、およびGetUserNameByEmailだけが必要です.ここでは、GetUserメソッドを使用してCustomMembershipUserクラスを使用して、ユーザーについて必要な情報のみを取得します.
例
using System;
using CustomAuthenticationMVC.DataAccess;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace CustomAuthenticationMVC.CustomAuthentication
{
public class CustomMembershipUser : MembershipUser
{
#region User Properties
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<role> Roles { get; set; }
#endregion
public CustomMembershipUser(User user):base("CustomMembership", user.Username, user.UserId, user.Email, string.Empty, string.Empty, true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now)
{
UserId = user.UserId;
FirstName = user.FirstName;
LastName = user.LastName;
Roles = user.Roles;
}
}
}
</role>
番目のステップは、前述のように、WebのCustomerメンバーシップを含めることです.設定ファイル.今、我々はウェブを更新します.configファイルと次のコードのスニペットを追加します.<membership defaultprovider="CustomMembership">
<providers>
<clear>
<add name="CustomMembership" type="CustomAuthenticationMVC.CustomAuthentication.CustomMembership">
</add></clear></providers>
</membership>
これを実装するためにカスタムロールプロバイダーを使用します.この場合、roleProviderから継承したカスタムロールクラスを構築し、GetRoleForUserおよびIsUserInRoleメソッドをオーバーライドします.
例
using CustomAuthenticationMVC.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace CustomAuthenticationMVC.CustomAuthentication
{
public class CustomRole : RoleProvider
{
public override bool IsUserInRole(string username, string roleName)
{
var userRoles = GetRolesForUser(username);
return userRoles.Contains(roleName);
}
public override string[] GetRolesForUser(string username)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
return null;
}
var userRoles = new string[] { };
using (AuthenticationDB dbContext = new AuthenticationDB())
{
var selectedUser = (from us in dbContext.Users.Include("Roles")
where string.Compare(us.Username, username, StringComparison.OrdinalIgnoreCase) == 0
select us).FirstOrDefault();
if(selectedUser != null)
{
userRoles = new[] { selectedUser.Roles.Select(r=>r.RoleName).ToString() };
}
return userRoles.ToArray();
}
}
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
ノート
グローバル内に次のコードスニペットを追加します.ASAXは、HttpContextから既定のユーザープロパティを置換します.
例
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies["Cookie1"];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var serializeModel = JsonConvert.DeserializeObject<customserializemodel>(authTicket.UserData);
CustomPrincipal principal = new CustomPrincipal(authTicket.Name);
principal.UserId = serializeModel.UserId;
principal.FirstName = serializeModel.FirstName;
principal.LastName = serializeModel.LastName;
principal.Roles = serializeModel.RoleName.ToArray<string>();
HttpContext.Current.User = principal;
}
}
</string></customserializemodel>
コントローラを作る
カスタムメンバーシッププロバイダーとカスタムロールプロバイダーの実装の後で、私は、ユーザーを認証するのを援助するために必要なすべてのアクションでアカウントコントローラを設計するときであると思います.
今、コントローラーを作ります.コントローラフォルダを右クリックします.次の対話でコントローラ「AccountController」という名前を付け、「追加」をクリックしてコントローラを正常に追加します.
上記のコントローラから「MVC 5コントローラEmpty」を選んでください
上記のコントローラから「MVC 5コントローラEmpty」を選んでください
例
using CustomAuthenticationMVC.CustomAuthentication;
using CustomAuthenticationMVC.DataAccess;
using CustomAuthenticationMVC.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace CustomAuthenticationMVC.Controllers
{
[AllowAnonymous]
public class AccountController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Login(string ReturnUrl = "")
{
if (User.Identity.IsAuthenticated)
{
return LogOut();
}
ViewBag.ReturnUrl = ReturnUrl;
return View();
}
[HttpPost]
public ActionResult Login(LoginView loginView, string ReturnUrl = "")
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(loginView.UserName, loginView.Password))
{
var user = (CustomMembershipUser)Membership.GetUser(loginView.UserName, false);
if (user != null)
{
CustomSerializeModel userModel = new Models.CustomSerializeModel()
{
UserId = user.UserId,
FirstName = user.FirstName,
LastName = user.LastName,
RoleName = user.Roles.Select(r => r.RoleName).ToList()
};
string userData = JsonConvert.SerializeObject(userModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket
(
1, loginView.UserName, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData
);
string enTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie("Cookie1", enTicket);
Response.Cookies.Add(faCookie);
}
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
else
{
return RedirectToAction("Index");
}
}
}
ModelState.AddModelError("", "Something Wrong : Username or Password invalid ^_^ ");
return View(loginView);
}
[HttpGet]
public ActionResult Registration()
{
return View();
}
[HttpPost]
public ActionResult Registration(RegistrationView registrationView)
{
bool statusRegistration = false;
string messageRegistration = string.Empty;
if (ModelState.IsValid)
{
string userName = Membership.GetUserNameByEmail(registrationView.Email);
if (!string.IsNullOrEmpty(userName))
{
ModelState.AddModelError("Warning Email", "Sorry: Email already Exists");
return View(registrationView);
}
//Save User Data
using (AuthenticationDB dbContext = new AuthenticationDB())
{
var user = new User()
{
Username = registrationView.Username,
FirstName = registrationView.FirstName,
LastName = registrationView.LastName,
Email = registrationView.Email,
Password = registrationView.Password,
ActivationCode = Guid.NewGuid(),
};
dbContext.Users.Add(user);
dbContext.SaveChanges();
}
VerificationEmail(registrationView.Email, registrationView.ActivationCode.ToString());
messageRegistration = "Your account has been created successfully. ^_^";
statusRegistration = true;
}
else
{
messageRegistration = "Something Wrong!";
}
ViewBag.Message = messageRegistration;
ViewBag.Status = statusRegistration;
return View(registrationView);
}
[HttpGet]
public ActionResult ActivationAccount(string id)
{
bool statusAccount = false;
using (AuthenticationDB dbContext = new DataAccess.AuthenticationDB())
{
var userAccount = dbContext.Users.Where(u => u.ActivationCode.ToString().Equals(id)).FirstOrDefault();
if (userAccount != null)
{
userAccount.IsActive = true;
dbContext.SaveChanges();
statusAccount = true;
}
else
{
ViewBag.Message = "Something Wrong !!";
}
}
ViewBag.Status = statusAccount;
return View();
}
public ActionResult LogOut()
{
HttpCookie cookie = new HttpCookie("Cookie1", "");
cookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie);
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account", null);
}
[NonAction]
public void VerificationEmail(string email, string activationCode)
{
var url = string.Format("/Account/ActivationAccount/{0}", activationCode);
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, url);
var fromEmail = new MailAddress("[email protected]", "Activation Account - AKKA");
var toEmail = new MailAddress(email);
var fromEmailPassword = "******************";
string subject = "Activation Account !";
string body = "
Please click on the following link in order to activate your account" + "
<a href=""> Activation Account ! </a>";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
smtp.Send(message);
}
}
}
アカウントコントローラには、上記の3つの主要なアクションがあります.<xmp>
@model CustomAuthenticationMVC.Models.LoginView
@{
ViewBag.Title = "Login";
}<h2>Login</h2>
@using (Html.BeginForm(null, null, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal"><h4>LoginView</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })<div class="form-group">
@Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
@Html.LabelFor(model => model.RememberMe, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10"><div class="checkbox">
@Html.EditorFor(model => model.RememberMe)
@Html.ValidationMessageFor(model => model.RememberMe, "", new { @class = "text-danger" })</div></div></div>
<div class="form-group"><div class="col-md-offset-2 col-md-10">
<input class="btn btn-default" type="submit" value="Log In" /></div></div></div>
}
<div>
@Html.ActionLink("Back to List", "Index")</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
</xmp>
例<xmp>
@model CustomAuthenticationMVC.Models.RegistrationView
@{
ViewBag.Title = "Registration";
}<h2>Registration</h2>
@if (ViewBag.Status != null && Convert.ToBoolean(ViewBag.Status))
{
if (ViewBag.Message != null)
{
<div class="alert alert-success">
<strong>Success!</strong> @ViewBag.Message</div>
}
}
else
{
using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal"><h4>RegistrationView</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })<div class="form-group">
@Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
@Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
@Html.ValidationMessage("ErrorEmail", new { @class = "text-danger" })</div></div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
@Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
@Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })</div></div>
<div class="form-group"><div class="col-md-offset-2 col-md-10">
<input class="btn btn-default" type="submit" value="Create" /></div></div></div>
if(ViewBag.Message != null)
{
<div class="alert alert-danger">
<strong>Error!</strong> @ViewBag.Message</div>
}
}
}
<div>
@Html.ActionLink("Login", "Login")</div>
@section Scripts{
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
}
</xmp>
例<xmp>
@{
ViewBag.Title = "Activation Account ^_^";
}<h2>Activation Account</h2>
@if(ViewBag.Status != null && Convert.ToBoolean(ViewBag.Status))
{
<div class="alert alert-success">
<strong>Success!</strong> Your account has been activated successfully.</div>
}
else
{
<div class="alert alert-danger">
<strong>Error!</strong>@ViewBag.Message</div>
}
</xmp>
許可フィルタ
このセクションでカスタム承認フィルタを実装します.
接続されたユーザーがユーザーロールを持たない場合、ユーザーコントローラへのアクセスを拒否するフィルターを作成します.
一歩一歩やりましょう.
まず、AuthorizeAttributeから派生したCustomMuthorizeAttributeクラスを作成します.
例
using CustomAuthenticationMVC.CustomAuthentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace CustomAuthenticationMVC.CustomAuthentication
{
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected virtual CustomPrincipal CurrentUser
{
get { return HttpContext.Current.User as CustomPrincipal; }
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return ((CurrentUser != null && !CurrentUser.IsInRole(Roles)) || CurrentUser == null) ? false : true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
RedirectToRouteResult routeData = null;
if(CurrentUser == null)
{
routeData = new RedirectToRouteResult
(new System.Web.Routing.RouteValueDictionary
(new
{
controller = "Account",
action = "Login",
}
));
}
else
{
routeData = new RedirectToRouteResult
(new System.Web.Routing.RouteValueDictionary
(new
{
controller = "Error",
action = "AccessDenied"
}
));
}
filterContext.Result = routeData;
}
}
}
例using CustomAuthenticationMVC.CustomAuthentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CustomAuthenticationMVC.Controllers
{
[CustomAuthorize(Roles = "User")]
public class UserController : Controller
{
// GET: User
public ActionResult Index()
{
return View();
}
}
}
ユーザーが首尾よく認証されるが、ユーザ役割を持たないとき、我々は彼または彼女のアクセスが拒否されると彼に警告しなければなりません.HandleUnAuthorizedRequestメソッドでは、このようにしました.例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CustomAuthenticationMVC.Controllers
{
public class ErrorController : Controller
{
// GET: Error
public ActionResult AccessDenied()
{
return View();
}
}
}
例<xmp>
@{
ViewBag.Title = "AccessDenied";
}<h2>AccessDenied</h2>
</xmp>
結論
このブログでは、ASP . NETで認証と認証を学びました.NET MVCの例を使用します.それはあなたのウェブサイトの検証の重要性を理解を支援します.
Reference
この問題について(ASP . NETカスタム認証と認証の詳細ガイド.ネットMVC), 我々は、より多くの情報をここで見つけました https://dev.to/tarungurang/a-detailed-guide-on-custom-authentication-and-authorization-in-aspnet-mvc-1a5gテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol