【问题标题】:Combine server-side and client-side authentication with WebAPI将服务器端和客户端身份验证与 WebAPI 相结合
【发布时间】:2017-10-28 05:37:27
【问题描述】:

我有一个旧的 ASP.NET webforms 应用程序,用户通过在服务器端处理的表单登录。如果输入的用户名 + 密码与数据库中的凭据匹配,我会在会话中设置一些值(例如,当前用户 ID),然后执行Response.Redirect。我还在为“下次访问时自动重新登录”功能创建一个 HttpCookie。

目前,我还在该 Web 应用程序中添加 WebApi 支持。我已经成功实现了令牌身份验证,允许我在客户端登录。

如何结合使用这两种身份验证方法?我希望用户输入他的凭据一次,在服务器端进行身份验证,在客户端进行身份验证后将用户重定向到另一个页面。

【问题讨论】:

  • 您能否详细说明您想要实现的目标?用户将使用哪种身份验证方法进行一次身份验证,这与另一种方法有什么关系?您是否希望您的用户通过表单进行身份验证,然后能够使用基于令牌的 webAPI? (还有用于自动重新登录的 cookie 是如何工作的?这对我来说听起来像是一个漏洞,但显然我不知道细节。)

标签: c# asp.net session authentication asp.net-web-api


【解决方案1】:

您可以使用 Angular JS 在 webapi 中使用基于令牌的身份验证。访问以下链接 http://www.dotnetcurry.com/aspnet/1223/secure-aspnet-web-api-using-tokens-owin-angularjs

【讨论】:

    【解决方案2】:

    以下代码将创建一个 cookie 以保持用户登录。

    // login etc
            if (chkRemember.Checked)
            {
                // calculate the total number of minutes in 20 days to use as the time out.
                int timeout = (int)TimeSpan.FromDays(30).TotalMinutes;
    
                // create an authentication ticket
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(txtUserName.Text, true, timeout);
    
                // Encrypt the ticket
                string encrptedTicked = FormsAuthentication.Encrypt(ticket);
    
                // create the cookie for the ticket, and put the ticket inside
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrptedTicked);
    
                // give cookie and ticket same expiration
                cookie.Expires = ticket.Expiration;
    
                // Attach cookie to current response. it will now to the client and then back to the webserver with every request
                HttpContext.Current.Response.Cookies.Set(cookie);
    
                // send the user to the originally requested page.
                string requestedPage = FormsAuthentication.GetRedirectUrl(txtUserName.Text, false);
                Response.Redirect(requestedPage, true);
            }
            else
            {
                // login without saving cookie to client
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-04
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      相关资源
      最近更新 更多