You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP MVC项目:从Cookie获取用户并通过Identity登录的技术问询

好的,我来帮你梳理下怎么实现从Cookie获取用户信息,并用ASP.NET Identity完成自动登录的功能,结合你这个商品销售项目的场景,咱们一步步来:

1. 先把用户信息加密存储到Cookie里

首先,得在用户首次登录成功的时候,把加密后的用户ID存到Cookie中——绝对不能明文存敏感信息,不然很容易被篡改或窃取。你可以在登录Action里加这段代码:

// 用户登录验证通过后获取ID
var userId = User.Identity.GetUserId();
// 用MachineKey加密用户ID,确保安全性
var encryptedUserId = MachineKey.Encode(Encoding.UTF8.GetBytes(userId), MachineKeyProtection.All);
// 创建并写入Cookie
var userAuthCookie = new HttpCookie("UserAuth")
{
    Value = encryptedUserId,
    Expires = DateTime.Now.AddDays(7), // 可以根据需求调整过期时间
    HttpOnly = true, // 禁止前端JS读取,防XSS攻击
    Secure = Request.IsSecureConnection // 生产环境务必设为true,只在HTTPS下传输
};
Response.Cookies.Add(userAuthCookie);
2. 写一个自动登录的过滤器

接下来,我们写一个自定义的Action过滤器,用来在访问需要登录的页面/Action时,自动读取Cookie并完成登录。这样不用在每个Action里重复写逻辑:

public class AutoLoginFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var httpContext = filterContext.HttpContext;
        
        // 如果用户已经登录,直接跳过
        if (httpContext.User.Identity.IsAuthenticated)
        {
            base.OnActionExecuting(filterContext);
            return;
        }

        // 读取之前存的Cookie
        var userCookie = httpContext.Request.Cookies["UserAuth"];
        if (userCookie == null || string.IsNullOrWhiteSpace(userCookie.Value))
        {
            // 没有有效Cookie,跳转到登录页
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                { "controller", "Account" },
                { "action", "Login" }
            });
            return;
        }

        try
        {
            // 解密Cookie里的用户ID
            var decryptedBytes = MachineKey.Decode(userCookie.Value, MachineKeyProtection.All);
            var userId = Encoding.UTF8.GetString(decryptedBytes);

            // 通过Identity获取用户实例
            var userManager = httpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var targetUser = userManager.FindById(userId);

            if (targetUser != null)
            {
                // 创建身份验证票据,完成自动登录
                var identity = userManager.CreateIdentity(targetUser, DefaultAuthenticationTypes.ApplicationCookie);
                httpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties
                {
                    IsPersistent = true // 和Cookie过期时间保持一致
                }, identity);
            }
            else
            {
                // 用户不存在,删除无效Cookie并跳登录
                httpContext.Response.Cookies["UserAuth"].Expires = DateTime.Now.AddDays(-1);
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
                {
                    { "controller", "Account" },
                    { "action", "Login" }
                });
            }
        }
        catch
        {
            // 解密失败(比如Cookie被篡改),直接清理Cookie跳登录
            httpContext.Response.Cookies["UserAuth"].Expires = DateTime.Now.AddDays(-1);
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                { "controller", "Account" },
                { "action", "Login" }
            });
        }

        base.OnActionExecuting(filterContext);
    }
}
3. 在PaymentAction上应用过滤器

现在把这个过滤器加到你的PaymentAction上,这样用户访问这个Action时,会自动检查Cookie并完成登录,你就能正常获取User.Identity.GetUserId()了:

[AutoLoginFilter]
public string PaymentAction(TransAction Model)
{
    try
    {
        Payment ob = new Payment();
        Model.amount = 100000.ToString();
        // 现在用户已经自动登录,可以安全获取ID了
        string userId = User.Identity.GetUserId();
        string result = ob.pay(Model.amount, userId); 
        /* 变量result包含来自pay.ir/send的响应内容,包含status、transId、err等字段 */
        
        // 这里可以根据result处理后续逻辑,比如跳转银行网关
        return "Payment redirect initiated";
    }
    catch (Exception ex)
    {
        return $"Error: {ex.Message}";
    }
}
几个重要的安全提醒
  • 务必加密Cookie:用MachineKey加密是ASP.NET自带的安全机制,千万别图省事明文存用户ID。
  • 开启HttpOnly和Secure:HttpOnly防止前端脚本窃取Cookie,Secure确保Cookie只在HTTPS环境下传输(生产环境必须开)。
  • 验证用户有效性:从Cookie解密出ID后,一定要通过UserManager确认用户存在,避免无效或篡改的Cookie导致异常。

内容的提问来源于stack exchange,提问作者Xeta7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:51:20