可以在针对.net标准2.0的类库中使用System.Web

问题描述 投票:0回答:1

我有一个使用表单身份验证的Asp.net应用程序。我正在构建一个asp.net核心API,该API将接收JWT令牌,该令牌的有效负载中包含用户信息。该API需要调用asp.net应用程序来满足用户请求。为了使asp.net应用程序能够处理此请求,它需要表单身份验证cookie才能将其识别为有效的登录用户。

换句话说,API需要在实际用户发出请求的刺激请求转发的情况下生成并发送认证cookie。

注意:创建该API的目的是将asp.net应用程序的功能公开为公共API,而用户不必先直接登录asp.net应用程序UI。

我正在创建一个针对.net标准2.0的类库,该类库可在我的api中使用,它负责创建cookie部分,并将其添加到请求中,然后再将请求转发到我的asp.net应用程序。如何在我的类库中创建FormAuthenication cookie?我发现以下代码,并且想知道如何在我的库中执行类似的操作?

string userData = string.Join("|",GetCustomUserRoles());

  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1,                                     // ticket version
    username,                              // authenticated username
    DateTime.Now,                          // issueDate
    DateTime.Now.AddMinutes(30),           // expiryDate
    isPersistent,                          // true to persist across browser sessions
    userData,                              // can be used to store additional user data
    FormsAuthentication.FormsCookiePath);  // the path for the cookie

  // Encrypt the ticket using the machine key
  string encryptedTicket = FormsAuthentication.Encrypt(ticket);

  // Add the cookie to the request to save it
  HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
  cookie.HttpOnly = true; 
asp.net-core forms-authentication .net-standard-2.0
1个回答
1
投票

没有System.Web仅是.NET Framework。它不包括也不与.NET Standard任何版本兼容。另外,一般不建议使用Forms Auth(作为ASP.NET成员资格的一部分),因此,除了ASP.NET(.NET Framework)之外,什么都无法使用。

接下来,如果您需要共享身份​​验证,则必须切换到ASP.NET(核心)身份并使用数据保护API,而不是Forms Auth所依赖的旧式机器密钥加密。

尽管值得,但API不应使用Cookie身份验证。 Cookies是客户端与API交互的非标准方式,也是一种状态形式,而API应该是无状态的(REST)。相反,您应该执行基本身份验证或承载身份验证之类的操作,使用Authorization标头通过用户/通过(基本)或令牌(承载)授权每个请求。

© www.soinside.com 2019 - 2024. All rights reserved.