3

かみそりのフォームを含むページで Web サイトを作成しました。ユーザーはこのフォームにログインしてから、別のページにリダイレクトできます。ログイン (およびログアウト) は、フォーム認証で正常に機能します。ただし、HttpContext.Current.User.Identity.Name を使用して (フォーム認証 Cookie に) 保存されているユーザー名を取得できないようです。空の文字列 "" を返します。

標準メンバーシップまたはロール プロバイダーなしで MVC 5 および ASP 4.5 を使用しています。

ログイン:

 [HttpPost]
        public ActionResult Login(User user)
        {
            if (ModelState.IsValid)
            {
                bool authenticated = userscontroller.isAuthorized(user.Email, user.Password);
                if (authenticated)
                {
                    if (userscontroller.isAuthenticated())
                    {
                        userscontroller.deAuthenticateUser();
                    }
                    userscontroller.authenticateUser(user);
                    return Redirect(Url.Action("Index", "Home"));
                }
            }
        }

ユーザーの認証:

 public void authenticateUser(User user)
    {
        FormsAuthentication.SetAuthCookie(user.Username, false);
    }

次に、ユーザーの名前を取得します。

public User userFromCookie()
{
    if (isAuthenticated())
    {
        return getUserByUsername(HttpContext.Current.User.Identity.Name);
    }
    else { return null; }
}

isauthenticated()

public bool isAuthenticated()
{
    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
    {
        return true;
    }
    else
    {
        return false;
    }
}

ウェブ構成:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
 <authorization > <deny users="?"/> </authorization>

したがって、identity.name は "" を返します。

助けていただければ幸いです。

4

1 に答える 1

8

機能しない考えられる理由。

  1. あなたはそれを間違って呼んでいるだけです。試すthis.User.Identity.Name
  2. Cookie は Response オブジェクトに保持されていないため、ユーザーは実際には次のリクエストで認証されません。
  3. Cookie を使用したフォーム認証を使用するように web.config が構成されていません。

これは、私が作成した完全に機能する例です。このすべてが機能します。唯一の依存関係は Newtonsoft ライブラリですが、それを削除して、必要なものをユーザー データに入れることができます。

ここにユーザーコントローラーがあります

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace TestAuth.Controllers
{
    public class UserModel
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        public bool RememberMe { get; set; }
    }

    public class UserInfo
    {
        public string UserName { get; set; }
    }

    public class UserController : Controller
    {
        [AllowAnonymous]
        public ActionResult Login()
        {
            var model = new UserModel() {Password = "password",UserName = "ItsMe", RememberMe = true};
            var serializedUser = Newtonsoft.Json.JsonConvert.SerializeObject(model);

            var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddHours(3), model.RememberMe, serializedUser);
            var encryptedTicket = FormsAuthentication.Encrypt(ticket);
            var isSsl = Request.IsSecureConnection; // if we are running in SSL mode then make the cookie secure only

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                HttpOnly = true, // always set this to true!
                Secure = isSsl,
            };

            if (model.RememberMe) // if the user needs to persist the cookie. Otherwise it is a session cookie
                cookie.Expires = DateTime.Today.AddMonths(3); // currently hard coded to 3 months in the future

            Response.Cookies.Set(cookie);

            return View(); // return something
        }

        [Authorize]
        public ActionResult ShowUserName()
        {
            return View(new UserInfo() {UserName = this.User.Identity.Name});
        }
    }
}

ここにビューがあります。Login.cshtml を表示

Logged in
<br/>

@Html.ActionLink("Show the user their name", "ShowUserName", "User")

ShowUserName.cshtml を表示

@model TestAuth.Controllers.UserInfo

<h2>title</h2>
user name = @Model.UserName

web.config セクション キーは、Google 検索で表示された Web サイトから生成されたものであることに注意してください。私が使用したサイトはやや古いため、正しい暗号化タイプを使用して独自のものを入手することを検討する必要があります。

  <system.web>
        <authentication mode="Forms">
            <forms name="myAuthCookie" ticketCompatibilityMode="Framework40" cookieless="UseCookies" requireSSL="false" timeout="180" protection="Encryption" />
        </authentication>
        <machineKey
  validationKey="DA87693F33607268657E61BCF16D2EAFE339ECE0F6C9B94DFA0FE5BBCA0035EB320F81662A32D98F0A0D2A5DCBE3E678EDF216FBD45CB8BD6F13489D1548214C"
  decryptionKey="26F44FEF28C3466FAB261CEF4844535678578C6658F85C6ADAE17A99B0947468"
  validation="SHA1" decryption="AES"/>


        <compilation debug="true" targetFramework="4.6"/>
    <httpRuntime targetFramework="4.6"/>
  </system.web>
于 2015-09-17T10:38:12.943 に答える