【问题标题】:Authentication using API .net core使用 API .net 核心进行身份验证
【发布时间】:2016-11-04 18:33:29
【问题描述】:

我有以下设置。一个使用身份和令牌授权的 Web API,包含整个用户管理,当然还有一些额外的 API 调用。

此外,我正在构建一个 FE 以再次使用 .net 核心来使用 API。我有我的登录表单并发布到 FE,它使用 RestSharp 执行 API 请求,提供我从表单中获得的凭据。我收到了一些用户数据和身份 Cookie/令牌。 我将 cookie/token 设置为响应,现在我的 FE 可以使用它来使用 ajax 进行其他 API 调用。

但我的问题是,我怎么知道他在 X 分钟后仍然登录?如果 Cookie/令牌过期,API 调用将被拒绝,但我的 FE-BE 如何知道它们不再有效?我会检查每个请求的到期日期吗?

我要求这主要是为了挑战我构建系统的方式以避免任何巨大的安全漏洞。

【问题讨论】:

  • 稍微偏离主题:我推荐 HttpClient 而不是 RestSharp。它完全建立在异步调用之上,对单元测试有很好的支持,而 RestSharp 依赖于旧的WebClient 和同步调用;至少直到最近它才这样做。
  • @thoean 谢谢你的提示,我会看看 HttpClient,我发现 RestSharp 更容易使用。 PostMan 还可以自动翻译成 RestSharp :)

标签: asp.net api cookies asp.net-core


【解决方案1】:

在与朋友交谈后,更合适的解决方案(在我看来)如下。 (代码可以清理)

        //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
        if (ModelState.IsValid)
        {
            // Do a rest call to the API
            Uri _baseUri = new Uri("http://localhost:8000/");
            var client = new RestClient(_baseUri + "api/Account/login");
            var request = new RestRequest(Method.POST);
            request.AddHeader("postman-token", "7ee2a21b-70d5-8a68-f0dd-518b8a61ddbf");
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddParameter("application/x-www-form-urlencoded", "Email=blah%40gmail.com&password=a1Aa1Aa1A!&=", ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            // Check the response
            if (response.StatusCode == HttpStatusCode.OK) {
                // Grab the cookie for the Identity
                // this can be replaced by a token in the future
                String cookie = response.Cookies.Where(c => c.Name == ".AspNetCore.Identity.Application").First().Value;
                // Store the cookie value to use it in sub-sequent requests                
                HttpContext.Session.SetString("IdentityCookieId", cookie);


                // Add claims to our new user, an example Name and an example Role 
                const string Issuer = "http://blah.com";
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Name, "AnonymUser", ClaimValueTypes.String, Issuer));
                claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));

                var userIdentity = new ClaimsIdentity("SecuredLoggedIn");
                userIdentity.AddClaims(claims);
                var userPrincipal = new ClaimsPrincipal(userIdentity);

                // Sign in the user creating a cookie with X ammount of Expiry
                await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal,
                    new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.UtcNow.AddMinutes(1),
                        IsPersistent = false,
                        AllowRefresh = false
                    });

                // Move back to the ReturnUrl or for me always to the dashboard
                return RedirectToLocal("/dashboard");
            }
        }

        return View(model);
    }

当然你必须编辑ConfigureServices下的Startup.cs文件,在AddMvc()之前添加services.AddAuthorization();

并在Configure下添加

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookie",
            LoginPath = new PathString("/account/login/"),
            AccessDeniedPath = new PathString("/Account/Forbidden/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true
        });

【讨论】:

  • @ShaunLuttin 如果你有时间看看。
【解决方案2】:

如果 Cookie/令牌过期,API 调用将被拒绝,但我的 FE-BE 如何知道它们不再有效?我会检查每个请求的到期日期吗?

要确定授权访问是否已过期,请检查optionally comes with an OpenID Connect implicit flow response.expires_in 时间范围。

  • access_token
  • token_type
  • id_token
  • state
  • expires_in 可选。自响应生成以来访问令牌的过期时间(以秒为单位)。

由于 access_token 通常对客户端来说是不透明的,唯一能确定访问是否过期的方法是询问 access_token 的颁发者。

但我的问题是,我怎么知道他在 X 分钟后仍然登录?

要确定您的用户是否仍处于登录状态,请使用id_token 而不是access_token

【讨论】:

  • thnx 我现在开始工作了,我会把我的解决方案作为答案,如果你看看答案,那就太好了。 (希望能尽快清理代码)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 2019-02-23
  • 2021-09-17
  • 2021-12-23
  • 2023-03-11
  • 2021-02-18
  • 1970-01-01
相关资源
最近更新 更多