如何从Cognito检索令牌?

时间:2019-01-29 14:29:44

标签: .net-core jwt access-token amazon-cognito oidc

我有一个简单的Dotnet核心API,该API获取value1,value2,方法为[Authorize]。 我正在尝试从Cognito idp取回令牌以访问结果,但是问题是我找不到一种方法(用户名,密码和电子邮件)发送给Cognito来取回令牌。

我一直收到以下错误:

SAML响应处理中的错误:无效的用户属性:电子邮件:该属性是必需的',error_uri:'error_uri为null' ¨ 在startup.cs中,我将其配置如下:

services.Configure<OpenIdConnectOptions>(Configuration.GetSection("Authentication:Cognito"));
        var serviceProvider = services.BuildServiceProvider();
        var authOptions = serviceProvider.GetService<IOptions<OpenIdConnectOptions>>();

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddOpenIdConnect(options =>
        {
            options.ResponseType = authOptions.Value.ResponseType;

            options.MetadataAddress = authOptions.Value.MetadataAddress;
            options.ClientId = authOptions.Value.ClientId;
            options.ClientSecret = authOptions.Value.ClientSecret;
            options.SaveTokens = authOptions.Value.SaveTokens;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = authOptions.Value.TokenValidationParameters.ValidateIssuer
            };
         });

我希望在将属性(用户名,密码和电子邮件)发送给Cognito idp之后将其取回,并将其提供给邮递员以获取值。

1 个答案:

答案 0 :(得分:0)

使用用户名和密码成功注册后,请使用以下代码检索访问令牌

 CognitoUserPool userPool=new CognitoUserPool(poolid,client_id,provider);
 CognitoUser user=new CognitoUser(username,client_id,userPool,provider);
            InitiateSrpAuthRequest authRequest=new InitiateSrpAuthRequest()
            {
                Password=password
            };
   Task<AuthFlowResponse> authFlowResponse=null;
   authFlowResponse=user.StartWithSrpAuthAsync(authRequest);
   string Token=authFlowResponse.Result.AuthenticationResult.AccessToken.ToString();