gpt4 book ai didi

c# - 针对外部 Web 服务的 ASP.NET MVC 表单例份验证

转载 作者:IT王子 更新时间:2023-10-29 04:24:19 24 4
gpt4 key购买 nike

我正在尝试编写一个 ASP.NET MVC 应用程序,它是我们具有 SOAP Web 服务的 CRM 的前端。我希望用户使用他们的 CRM 用户名和密码登录到我的 Web 应用程序,然后针对 CRM 进行身份验证,在页面上进行 Web 服务调用等。

我开始考虑使用 Forms Authentication 和实现自定义成员身份提供程序 - 我可以实现我需要的所有方法,比如 ValidateUser(),但我遇到的问题是登录到在 CRM Web 服务中,您将获得一个 token ,必须在每次后续 Web 服务调用时传递该 token ,但我不确定可以将其存储在哪里。

所以我的问题是:

  • Forms Authentication 是这里的方法,还是自己处理所有身份验证并将 token 存储在 Session 中会更直接?
  • 如果表单例份验证是可行的方法,那么我应该在哪里以及如何存储像这样的附加信息。它似乎喜欢使用 Forms 身份验证,但随后将大量附加信息(与身份验证相关)塞入 Cookie 或 session 之外会有点困惑吗?

如有任何建议,我们将不胜感激

最佳答案

您可以将身份验证 token 存储在表单例份验证 cookie 的 userData 部分。这样,它将在每次请求时可用。

因此,例如,一旦您验证了用户的凭据,您就可以查询网络服务以获取 token 并手动创建和发出表单例份验证 cookie:

[HttpPost]
public ActionResult LogOn(string username, string password)
{
// TODO: verify username/password, obtain token, ...
// and if everything is OK generate the authentication cookie like this:

var authTicket = new FormsAuthenticationTicket(
2,
username,
DateTime.Now,
DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
false,
"some token that will be used to access the web service and that you have fetched"
);
var authCookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket)
)
{
HttpOnly = true
};
Response.AppendCookie(authCookie);

// ... redirect
}

然后您可以编写一个自定义授权属性,它将读取此信息并设置一个自定义通用标识:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthenticated = base.AuthorizeCore(httpContext);
if (isAuthenticated)
{
string cookieName = FormsAuthentication.FormsCookieName;
if (!httpContext.User.Identity.IsAuthenticated ||
httpContext.Request.Cookies == null ||
httpContext.Request.Cookies[cookieName] == null)
{
return false;
}

var authCookie = httpContext.Request.Cookies[cookieName];
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);

// This is where you can read the userData part of the authentication
// cookie and fetch the token
string webServiceToken = authTicket.UserData;

IPrincipal userPrincipal = ... create some custom implementation
and store the web service token as property

// Inject the custom principal in the HttpContext
httpContext.User = userPrincipal;
}
return isAuthenticated;
}
}

最后装饰需要使用此属性进行身份验证的 Controller /操作:

[MyAuthorize]
public ActionResult Foo()
{
// HttpContext.User will represent the custom principal you created
// and it will contain the web service token that you could use to
// query the remote service
...
}

关于c# - 针对外部 Web 服务的 ASP.NET MVC 表单例份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5633137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com