【问题标题】:Web site Authentication against Web API针对 Web API 的网站身份验证
【发布时间】:2020-07-29 18:05:41
【问题描述】:

我有以下使用 net core 3 的场景。一个带有登录页面的网站。此登录页面将用户和密码发送到 Web API,如果凭据正确,该 Web API 会使用 JWT 令牌进行响应。

我现在如何将我的网络用户设置为已通过身份验证?如何使用从 API 令牌收到的声明设置网络用户的声明?

在启动类似的东西时是否需要添加任何服务?

您能否向我提供有关如何操作的任何基本示例或任何文档?

谢谢

【问题讨论】:

  • 您目前使用的是什么?你在使用 JWT 扩展吗?通常,您应该分享您的启动类的代码,以便我们了解需要填补哪些空白。
  • 我还没有启动。这就是我需要配置的。网站中的登录页面。登录页面调用返回 JWT 令牌的 API。当网站有令牌时,我想用令牌内的信息通知网络用户(IsAthenticated 应该是真的,声明已填写,...)我想知道是否有任何提供者或自动执行此操作的东西。我认为它类似于 services.AddAuthentication().AddMicrosoftAccount(microsoftOptions => { ... }) 但使用我的 API 的身份验证。

标签: asp.net-core asp.net-identity asp.net-core-webapi jwt-auth


【解决方案1】:

你可以使用cookie authentication

  1. Startup.ConfigureServices 方法中,使用AddAuthenticationAddCookie 方法创建身份验证中间件服务:

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Account/Login";
            });
    

    并在Configure 中启用中间件:

    app.UseAuthentication();
    app.UseAuthorization();
    
  2. 在用户发布凭据的操作中,您可以使用凭据向 Web api 发送 http 请求,Web api 将验证凭据并返回 jwt 令牌,然后您的 Web 应用程序解码令牌并像这样登录用户:

    var stream = "[token]";
    var handler = new JwtSecurityTokenHandler();
    
    var tokenS = handler.ReadToken(stream) as JwtSecurityToken;
    
    
    var claimsIdentity = new ClaimsIdentity(
        tokenS.Claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
    var authProperties = new AuthenticationProperties
    {
    
        RedirectUri = "/Home/Privacy",
    
    };
    
    await HttpContext.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme,
        new ClaimsPrincipal(claimsIdentity),
        authProperties);
    

【讨论】:

    【解决方案2】:

    根据您的前端解决方案,您需要弄清楚如何解码您收到的 JWT 以检索您需要的值。

    这里有几件事,同样取决于您在前端使用的内容

    C# https://developer.okta.com/blog/2019/06/26/decode-jwt-in-csharp-for-authorization

    SPA 的 NPM 包 https://www.npmjs.com/package/jwt-decode

    这是 JWT 的另一个好资源 https://jwt.io/

    你可以拿你收到的JWT来查看里面的值

    【讨论】:

      猜你喜欢
      • 2019-04-28
      • 1970-01-01
      • 2015-03-30
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 2016-01-17
      • 2011-05-09
      相关资源
      最近更新 更多