针对Web API的网站身份验证

时间:2020-04-16 13:20:18

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

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

如何现在将我的Web用户设置为已认证?如何使用我从API令牌收到的声明来设置网络用户的声明?

是否有必要在启动类似服务时添加任何服务?

您能为我提供有关该操作方法的基本示例还是任何文档吗?

谢谢

2 个答案:

答案 0 :(得分: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);
    

答案 1 :(得分:0)

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

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

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

NPM SPA套餐 https://www.npmjs.com/package/jwt-decode

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

您可以使用收到的JWT来查看其中的值