public class AuthenticationAttribute : FilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
clearCookie(filterContext); // テスト用
string cookieValue = getUserIdFromCookie(filterContext);
string headerValue = getUserIdFromHttpHeader(filterContext);
if (string.IsNullOrEmpty(cookieValue))
{
if (string.IsNullOrEmpty(headerValue))
{
// Cookieとヘッダから取得できなければ認証エラー
filterContext.Result = new HttpUnauthorizedResult();
return;
}
// Cookieはないけどヘッダから取得できた場合
cookieValue = headerValue;
// todo
// DBを検索し取得できなければ認証エラー
}
// Cookieを更新
saveCookie(filterContext, cookieValue);
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
{
//Redirecting the user to the Login View of Account Controller
filterContext.Result = new RedirectResult("http://yahoo.co.jp");
}
}
private void clearCookie(AuthenticationContext filterContext)
{
filterContext.HttpContext.Request.Cookies.Clear();
filterContext.HttpContext.Response.Cookies.Clear();
}
private void saveCookie(AuthenticationContext filterContext, string cookieValue)
{
filterContext.HttpContext.Response.AppendCookie(new HttpCookie("UserId")
{
Value = cookieValue,
Expires = DateTime.Now.AddDays(30),
HttpOnly = true,
Secure = false
});
}
private string getUserIdFromCookie(AuthenticationContext filterContext)
{
return filterContext.HttpContext.Request.Cookies["UserId"]?.Value;
}
private string getUserIdFromHttpHeader(AuthenticationContext filterContext)
{
// Web.configにテストユーザIDが設定されていたらそれを使う(テスト用)
string testUserId = ConfigurationManager.AppSettings["TestUserId"];
if (string.IsNullOrEmpty(testUserId)){
// 設定されていなかったらHTTPヘッダから取得する
return filterContext.HttpContext.Request.Headers["UserId"];
}
return testUserId;
}
}
}