如何使用AWS Cognito保护.Net Core Web API应用程序 [英] How to use AWS Cognito to secure a .Net Core Web API applications

查看:28
本文介绍了如何使用AWS Cognito保护.Net Core Web API应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是AWS新手,需要使用Cognito保护对.NET Core Web API应用程序的访问。我在很大程度上关注了Les Jackson在YouTube上的精彩视频(https://www.youtube.com/watch?v=3PyUjOmuFic),但他使用的是Azure而不是AWS。

到目前为止,我有一个非常简单的API控制器操作,它只是从SQL Server提取一些记录并发送JSON响应。

        [HttpGet]
        public async Task<IEnumerable<TodoItem>> Get()
        {
            var items = await context.TodoItem.ToListAsync();
            return items;
        }

这在Visual Studio中本地运行良好,在使用Elastic Beanstrik部署到AWS实例时也是如此。

为了保护我添加到Startup.cs中的ConfigureServices方法的应用程序

    services.AddAuthentication("Bearer")
        .AddJwtBearer(options =>
        {
            options.Audience = "App client id";
            options.Authority = "https://cognito-idp.eu-west-2.amazonaws.com/Cognito User Pool id";
        });

和Configure方法中的

            app.UseAuthentication();

我向应用程序添加控制器只是为了向Cognito进行身份验证并取回访问令牌。

        private const string _clientId = "App client id";
        private readonly RegionEndpoint _region = RegionEndpoint.EUWest2;

        [HttpPost]
        [Route("/api/signin")]
        public async Task<ActionResult<string>> SignIn(User user)
        {
            var cognito = new AmazonCognitoIdentityProviderClient(_region);

            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = "Cognito User Pool id",
                ClientId = _clientId,
                AuthFlow = AuthFlowType.ADMIN_USER_PASSWORD_AUTH
            };

            request.AuthParameters.Add("USERNAME", user.Username);
            request.AuthParameters.Add("PASSWORD", user.Password);

            var response = await cognito.AdminInitiateAuthAsync(request);

            return Ok(response.AuthenticationResult);
        }

我在本地和AWS上都能正常工作,在使用Postman发布Cognito用户名和密码时返回令牌,例如

{
    "accessToken": ".....",
    "expiresIn": 3600,
    "idToken": "...",
    "newDeviceMetadata": null,
    "refreshToken": "...",
    "tokenType": "Bearer"
}

因此,我将[Authorize]属性添加到我的API方法中,使用signin方法获取访问令牌,并在Postman中构造一个请求,该请求包含Authorization HTTP头,值为";Beeller";+accessToken。

遗憾的是,这不起作用,我想不出其他方法可以尝试。

通过Visual Studio向IIS Express中本地运行的应用程序发出邮递员请求,我得到响应

System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
 ---> System.IO.IOException: IDX20807: Unable to retrieve document from: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. HttpResponseMessage: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]', HttpResponseMessage.Content: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.

使用弹性豆茎部署应用程序时,我只收到500内部服务器错误,没有其他消息。

我做错了什么?如有任何帮助/指点,我将不胜感激。

道格

推荐答案

我不太确定原因,但现在似乎工作正常!

我最终得到的最终代码是:

在ConfigureServices中,Startup.cs

            services.AddAuthentication("Bearer")
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false };
                    options.Authority = "https://cognito-idp.eu-west-2.amazonaws.com/eu-west-2_xxxxxxxxx";
                    options.RequireHttpsMetadata = false;
                });

在配置中,Startup.cs

            app.UseAuthentication();

在appsettings.json中

  "AWSCognito": {
    "Region": "{Region}",
    "PoolId": "{PoolId}",
    "AppClientId": "{AppClientId}"
  }

当Authorization HTTP标头中提供访问令牌时,对用[Authorization]属性修饰的API方法的调用会成功,并且User.Identity.Claims.其中(c=>;c.Type==";username";).FirstOrDefault()提供经过身份验证的用户的用户ID。

谢谢您的建议。

这篇关于如何使用AWS Cognito保护.Net Core Web API应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆