System.Security.Cryptography.CryptographicException: Error occurred during a cryptographic operation - asp.net

I've recently installed stackify on my dev API server and I have this error coming in on the stackify error dashboard but I cannot reproduce the error. I believe there is an error logged for almost every request made to the API, eventhough all the requests are OK(200) and none have responded with ServerError(5XX).
This is the error message:
System.Security.Cryptography.CryptographicException: System.Security.Cryptography.CryptographicException: Error occurred during a cryptographic operation.
at System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input)
Error Document:
{
"id": "1266b838-a261-4bde-9220-ff7993d72c0e",
"env": "dev",
"host": "raidsrv3",
"appname": "environment.appname.com",
"version": null,
"apploc": "D:\\StageApplications\\environment.appname.com",
"message": "System.NullReferenceException: Object reference not set to an instance of an object.\r\nSystem.NullReferenceException: System.NullReferenceException: Object reference not set to an instance of an object.\r\n at lambda_method(Closure , LoginViewModel )\r\n",
"json": null,
"jsonPreview": null,
"thread": "40",
"threadOs": null,
"transid": "7af3de61-9bf1-43d8-b60c-ff9850a35490",
"timestamp": "2021-01-20T14:21:41.247Z",
"inserted": "2021-01-20T14:22:11.8261135Z",
"level": "ERROR",
"logType": "app-dotnet",
"logger": null,
"urlRoute": "Home.Login",
"urlFull": null,
"sourcemethod": "lambda_method(Closure , LoginViewModel )",
"sourceline": null,
"stackify": {
"CdWebAppId": null,
"CdId": 1,
"CdAppId": 215,
"Error": 1,
"WebLogUrlId": null,
"Queued": "2021-01-20T14:21:47.0806791Z",
"Tooksecs": 24.745,
"QueuedPartition": "Jan201400p1",
"Trace": null,
"FromApm": null,
"Order": 1,
"InvalidEpochStr": null,
"IsWebLog": false,
"AppNameId": "23f72352-2d5a-eb11-a607-0003ffcfb91b",
"AppEnvId": "43f72352-2d5a-eb11-a607-0003ffcfb91b",
"EnvId": 2,
"Timestamp1M": "2021-01-20T14:21:00Z",
"Timestamp5M": "2021-01-20T14:20:00Z",
"Timestamp1H": "2021-01-20T14:00:00Z",
"Timestamp1D": "2021-01-20T00:00:00Z",
"IsProd": true,
"Expiration1D": "2021-02-05T00:00:00Z",
"DeploymentId": null
},
"error": {
"StackifyErrorID": "1266b838-a261-4bde-9220-ff7993d72c0e",
"OccurredEpochMillis": 1611152501247,
"Error": {
"InnerError": null,
"StackTrace": [
{
"LineNum": null,
"Method": "lambda_method(Closure , LoginViewModel )",
"CodeFileName": null
}
],
"Message": "System.NullReferenceException: Object reference not set to an instance of an object.",
"ErrorType": "System.NullReferenceException",
"ErrorTypeCode": "-2147467261",
"Data": null,
"SourceMethod": "lambda_method(Closure , LoginViewModel )"
},
"data": {},
"EnvironmentDetail": {
"DeviceName": "RAIDSRV3",
"AppLocation": "D:\\StageApplications\\environment.appname.com",
"AppName": "environment.appname.com",
"WebAppID": null,
"ConfiguredAppName": null,
"ConfiguredEnvironmentName": null,
"ConfiguredLocationName": null,
"IsAzureWorkerRole": false
},
"WebRequestDetail": {
"UserIPAddress": null,
"HttpMethod": "GET",
"RequestProtocol": null,
"WebLogUrl": "Home.Login",
"RequestDomain": "environment.appname.com",
"ReportingUrl": "Home.Login",
"UrlKey": "get-home.login",
"RequestUrl": "https://environment.appname.com/",
"RequestUrlRoot": null,
"RequestRoute": null,
"ReferralUrl": null,
"UserAgent": null,
"Headers": {},
"Cookies": {},
"QueryString": {},
"PostData": {},
"SessionData": {},
"PostDataRaw": null,
"MvcAction": null,
"MvcController": null,
"MvcArea": null
},
"ApiClient": {
"Name": null,
"Platform": ".net"
},
"ServerVariables": {},
"CustomerName": null,
"UserName": null,
"errorGroupId": "b772fbd6-db5a-eb11-a607-0003ffcfb91b",
"errorGroupInstanceId": "bf72fbd6-db5a-eb11-a607-0003ffcfb91b",
"displayMethodId": "d65c87ef-ca5a-eb11-a607-0003ffcfb91b",
"errorSourceMethodId": "d65c87ef-ca5a-eb11-a607-0003ffcfb91b",
"errorTypeMessageId": "2-df28da1c-715a-eb11-a607-0003ffcfb91b-0e8ec107143a2e3d04bfee99e49c20a5",
"errorUniqueId": "d75c87ef-ca5a-eb11-a607-0003ffcfb91b",
"errorPlatformTypeId": 2,
"errorStateId": 0,
"errorTypeId": "df28da1c-715a-eb11-a607-0003ffcfb91b",
"message": "System.NullReferenceException: Object reference not set to an instance of an object.",
"errorType": "System.NullReferenceException",
"errorTypeClass": "NullReferenceException",
"errorTypeCode": "-2147467261",
"sourceMethodName": "lambda_method(Closure , LoginViewModel )",
"sourceMethodShort": "lambda_method(Closure , LoginViewModel )",
"errorGroupCreatedUtc": "2021-01-20T04:55:18.767",
"displayMethodName": "lambda_method(Closure , LoginViewModel )",
"displayMethodShort": "lambda_method(Closure , LoginViewModel )",
"stackTraceHash": "858F2DB7DA4C81444B39BA60C9CC5B65",
"stackTrace": "System.NullReferenceException: System.NullReferenceException: Object reference not set to an instance of an object.\n\tat lambda_method(Closure , LoginViewModel )\n",
"appended": "2021-01-20T14:22:22.5880117Z"
},
"winevent": null,
"weblog": null,
"tag": [
"fromapm"
],
"container": null,
"kubernetes": null
}
I have searched all over but I can't find an explanation for this error.
Here's some background info about my dev environment:
The API is .net Framework 4.7.2
I updated all the nuget packages and libries to their latest supported version
The machine key is already configured and I have verified the same key exists in both API servers web.config files. eg: <machineKey validationKey="***" decryptionKey="***" />
API is deployed on 2 servers, with nginx inbetween the client and the servers.
Ocotopus Deploy is used to deploy the API
DFS is used to sync the application files from the main server to the sister server
Any help will be greatly appreciated!

Turns out this exception that was being caught by stackify was a First Chance exception that is handled inside the .net framework.
More on first chance exceptions at this answer here
And if you're like me and your organization is concerned about all the exceptions being captured by Stackify, you can go to the environment settings > Editing Environment > Automatic collection & viewing of app errors via APM and change the setting from
Upload all errors to error module to Upload unhandled errors to error module.
That will make sure that only unhandled exceptions bubble up into stackify.

Related

Identity Server Random "invalid_grant"

Hello I have an issue with IdentityServer 4.
When we intiate a cal to IDP with Swagger for the first time I can get a token
[12:36:21 DBG] Getting claims for identity token for subject: 3680d5aa-4b35-4e39-a1ce-cfbc6961f4c3 and client: Idp.UserIdentitySwagger
[12:36:21 DBG] In addition to an id_token, an access_token was requested. No claims other than sub are included in the id_token. To obtain more user claims, either use the user info endpoint or set AlwaysIncludeUserClaimsInIdToken on the client configuration.
[12:36:21 VRB] Creating JWT identity token
[12:36:21 INF] {"ClientId": "Idp.UserIdentitySwagger", "ClientName": "Idp.UserIdentity Swagger", "RedirectUri": null, "Endpoint": "Token", "SubjectId": "3680d5aa-4b35-4e39-a1ce-cfbc6961f4c3", "Scopes": "openid profile email", "GrantType": "authorization_code", "Tokens": [{"TokenType": "id_token", "TokenValue": "****dlrQ", "$type": "Token"}, {"TokenType": "access_token", "TokenValue": "****g_rw", "$type": "Token"}], "Category": "Token", "Name": "Token Issued Success", "EventType": "Success", "Id": 2000, "Message": null, "ActivityId": "0HMJ7TTLK79RA:0000000E", "TimeStamp": "2022-07-17T12:36:21.0000000Z", "ProcessId": 1, "LocalIpAddress": "10.244.1.16:443", "RemoteIpAddress": "10.244.0.9", "$type": "TokenIssuedSuccessEvent"}
[12:36:21 VRB] Identity token issued for Idp.UserIdentitySwagger (Idp.UserIdentity Swagger) / 3680d5aa-4b35-4e39-a1ce-cfbc6961f4c3: eyJhbGciOiJSUzI1NiIsImtpZCI6IjIzNTJFMjcwQkFDQjUwMDAwNjM1NkY3RjIwRDM0MEIwQjk3NDRCRThSUzI1NiIsInR5cCI6IkpXVCIsIng1dCI6IkkxTGljTHJMVUFBR05XOV9JTk5Bc0xsMFMtZyJ9.eyJuYmYiOjE2NTgwNjEzODEsImV4cCI6MTY1ODA2NDk4MSwiaXNzIjoiaHR0cHM6Ly9pZHAub3Vpb3VpZGlzY291bnQuY29tIiwiYXVkIjoiSWRwLlVzZXJJZGVudGl0eVN3YWdnZXIiLCJpYXQiOjE2NTgwNjEzODEsImF0X2hhc2giOiJFWWRZYWtpb0ZFUTN6Z19qeHZ1Umd3Iiwic19oYXNoIjoiMUxYeTNQMXpaOTZiU2lDWjBrRmNBZyIsInNpZCI6IjYzREQ4OEQ5QTQ0NEEyRDQzRDU1QUNBMjYyQTM1MTc3Iiwic3ViIjoiMzY4MGQ1YWEtNGIzNS00ZTM5LWExY2UtY2ZiYzY5NjFmNGMzIiwiYXV0aF90aW1lIjoxNjU4MDYxMzczLCJpZHAiOiJsb2NhbCIsImFtciI6WyJwd2QiXX0.kyOSEob49JTd10Wmz3YMgg48MB-RRWmSJ6JB2dZeu-0r8WPOK69XXlq74bGAoyV6DwytsyTOmwb7h5Wnu5zcgbHFJ_ycGAi5PwOiO1clyDIpYW5ql__SZ2JH31ppuRg616eDaX0M2p9PFfW4MBSM1d4p69aWrbqAmuj8g833VjtZOFkZcgS6OZotqbM_zxOGLhfkzwJQtDjHdh1_imJp80fa4uv_0KOpWc62hclOXcBS8oKvgQYyeeS8AIXGrIBoNII8ZQ8yK-BrqOAjm4f1PVyyhQa8P19gXWoASQL6EHb-zCUo5VUXAu7bukBb4JNNzk8jUTCWvSUo9z4_rDdlrQ
[12:36:21 VRB] Access token issued for Idp.UserIdentitySwagger (Idp.UserIdentity Swagger) / 3680d5aa-4b35-4e39-a1ce-cfbc6961f4c3: eyJhbGciOiJSUzI1NiIsImtpZCI6IjIzNTJFMjcwQkFDQjUwMDAwNjM1NkY3RjIwRDM0MEIwQjk3NDRCRThSUzI1NiIsInR5cCI6ImF0K2p3dCIsIng1dCI6IkkxTGljTHJMVUFBR05XOV9JTk5Bc0xsMFMtZyJ9.eyJuYmYiOjE2NTgwNjEzODEsImV4cCI6MTY1ODA2NDk4MSwiaXNzIjoiaHR0cHM6Ly9pZHAub3Vpb3VpZGlzY291bnQuY29tIiwiY2xpZW50X2lkIjoiSWRwLlVzZXJJZGVudGl0eVN3YWdnZXIiLCJzdWIiOiIzNjgwZDVhYS00YjM1LTRlMzktYTFjZS1jZmJjNjk2MWY0YzMiLCJhdXRoX3RpbWUiOjE2NTgwNjEzNzMsImlkcCI6ImxvY2FsIiwic2lkIjoiNjNERDg4RDlBNDQ0QTJENDNENTVBQ0EyNjJBMzUxNzciLCJpYXQiOjE2NTgwNjEzODEsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJlbWFpbCJdLCJhbXIiOlsicHdkIl19.BXtDlQKqw8rGmgnLjJuWJicF2BIHPzpp48NC-aP9cpzy7dqYY2a8kI1x07vTnhX2rcEjdfqhfMIfyJuqZJBhXVtfI7R60QyfuAj3Ozpa4KGE2Y28d9Xntizf4ctwUXFLZVboH8MrXflcIiDL8s5h_c6P6W2NafYK_1m7xpU68Qq0NsxqXsaG2SZT_nph-bl_hEvfR_AfXbkDI12Z606hSqAhjP5v_TQfc6_0zveCVTiFRUMCzTzndtRSVtNrP3WPGXalOTtOaeOIUFssDvqNYeF6nch245vjw5NQQu3zUgETOSJfeO_d0c7VCeEvp_s_yCEFCVOIl2_xvWd3Hig_rw
I disconnect and try to login again and a “invalid_grant” is raised. I clear the cache and try again and it does not work. After several retries I can login. I think it is random error. I cannot figure out the reason behind this error. Here is the error message and the IDP configuration and the client configuration. I hope that it can help.
[12:42:06 DBG] A data reader was disposed.
[12:42:06 DBG] Closing connection to database 'IdpDb' on server 'tcp://XXXXXXXXXXX:5432'.
[12:42:06 DBG] Closed connection to database 'IdpDb' on server ''.
[12:42:06 DBG] tJc155MKnmvPDXowrLH4laE8GBDyxFtEveiaB/ONE4w= found in database: False
[12:42:06 DBG] authorization_code grant with value: E3661868CE07773D4612B6A32A5D10B9B0A48D00E616718C795D9ED5F6827348 not found in store.
[12:42:06 ERR] Invalid authorization code{"code": "E3661868CE07773D4612B6A32A5D10B9B0A48D00E616718C795D9ED5F6827348"}, details: {"ClientId": "Idp.UserIdentitySwagger", "ClientName": "Idp.UserIdentity Swagger", "GrantType": "authorization_code", "Scopes": null, "AuthorizationCode": "****7348", "RefreshToken": "********", "UserName": null, "AuthenticationContextReferenceClasses": null, "Tenant": null, "IdP": null, "Raw": {"grant_type": "authorization_code", "code": "E3661868CE07773D4612B6A32A5D10B9B0A48D00E616718C795D9ED5F6827348", "client_id": "Idp.UserIdentitySwagger", "client_secret": "***REDACTED***", "redirect_uri": "https://identity.*******.com/swagger/oauth2-redirect.html", "code_verifier": "eMCIRwHDzhTf1YrRr651Uaqi_COopBhc7ZfOGyjRiAc"}, "$type": "TokenRequestValidationLog"}
[12:42:06 INF] {"ClientId": "Idp.UserIdentitySwagger", "ClientName": "Idp.UserIdentity Swagger", "RedirectUri": null, "Endpoint": "Token", "SubjectId": null, "Scopes": null, "GrantType": "authorization_code", "Error": "invalid_grant", "ErrorDescription": null, "Category": "Token", "Name": "Token Issued Failure", "EventType": "Failure", "Id": 2001, "Message": null, "ActivityId": "0HMJ7TTLK79RH:00000008", "TimeStamp": "2022-07-17T12:42:06.0000000Z", "ProcessId": 1, "LocalIpAddress": "10.244.1.16:443", "RemoteIpAddress": "10.244.0.9", "$type": "TokenIssuedFailureEvent"}
[12:42:06 VRB] Invoking result: IdentityServer4.Endpoints.Results.TokenErrorResult
IdpConfiguration
services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = (t) =>
{
t.UseNpgsql(configuration.GetConnectionString("IdpDb"),
b => b.MigrationsAssembly(migrationsAssembly));
t.EnableSensitiveDataLogging();
};
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = (t) =>
{
t.UseNpgsql(configuration.GetConnectionString("IdpDb"),
b => b.MigrationsAssembly(migrationsAssembly));
t.EnableSensitiveDataLogging();
};
})
.AddProfileService<BrandeeUserProfileService>()
.AddSigningCredential(LoadCertificate(configuration));
DataProtection Code:
services.AddDataProtection()
.SetApplicationName("TAASe")
.UseCryptographicAlgorithms(
new AuthenticatedEncryptorConfiguration()
{
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256,
}
)
.ProtectKeysWithCertificate(new X509Certificate2(configuration["Certificate:Path"],
configuration["Certificate:Password"]))
.PersistKeysToDbContext<AppDataProtectionDbContext>()
.SetDefaultKeyLifetime(TimeSpan.FromDays(14));
Client Definition:
{
"clientId": "Idp.UserIdentity Swagger",
"clientName": "Idp.UserIdentity Swagger",
"requireConsent": true,
"accessTokenLifetime": 3600,
"identityTokenLifetime": 3600,
"allowOfflineAccess": true,
"alwaysSendClientClaims": true,
"secrets": [
"secret"
],
"scopes": [
"openid","profile","email"
],
"allowedGrantType": [
"authorization_code"
],
"redirectUris": [
"https://identity.XXXXXXXXXX.com/swagger/oauth2-redirect.html"
],
"corsOrigins": [
"https://identity.XXXXXXX.com"
],
"postLogoutRedirectUri": []
}
and in Swagger
services.AddSwaggerGen(options =>
{
var oauthSecuritySchema = new OpenApiSecurityScheme()
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
AuthorizationCode = new OpenApiOAuthFlow()
{
AuthorizationUrl = new Uri(configuration["Idp:AuthorizationUrl"]),
Scopes = new Dictionary<string, string>()
{
// {"Idp.UserManagement","Identity"},
{"openid","openid"},
{"profile","profile"},
{"email","email"}
},
TokenUrl = new Uri(configuration["Idp:TokenUrl"]),
}
},
Name = configuration["Swagger:Name"],
};
options.SwaggerDoc("v1", new OpenApiInfo {Title = "Protected API", Version = "v1"});
options.AddSecurityDefinition("oauth2", oauthSecuritySchema);
options.OperationFilter<AuthorizeCheckOperationFilter>();
options.EnableAnnotations();
});
When the user logs in, the Idp saves the code in the PersistedGrants table with the key formed by (code + ":" + "authorization_code").Sha256(). For your code E3661868CE07773D4612B6A32A5D10B9B0A48D00E616718C795D9ED5F6827348 the key is tJc155MKnmvPDXowrLH4laE8GBDyxFtEveiaB/ONE4w=. That is correct according to the logs. Then, the Idp returns this code to the caller.
Then, the client can change this code for the tokens in the token endpoint. The Idp try to recover this record by forming the key again, retrieving it from the database and checking if the passed code match with the stored previously.
It seems the persistence in the operational store is not working properly. Either this record is not saved in the first part, or the query to get it in the second part is not working. Whatever the reason the service returns a generic invalid_grant error message.
Check if the record is saved in the PersistedGrants table. You can use my Fiddle to form the key and test with other codes.
Check the previous logs if you have any EF exception when SaveAsync is called.

Cannot add Json Object into Azure Cosmos DB with using LogicApps action

I'm trying to adding Json Object into Azure Cosmos DB with using LogicApps Azure Cosmos DB Action (Patch an Item)
When I try to adding it(Json Object) with Serialized string, it works but when I try to adding as Json Object directly, Exception has occurred like below :
[2022-05-05T18:40:58.485Z] Error message: correlationId='36c1252c-9b2f-452c-8b86-026144567708', operationName='/serviceProviders/AzureCosmosDB.CosmosDBServiceOperationsProvider.HandleException', message='Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken.', exception='System.InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken.
[2022-05-05T18:40:58.488Z] at Newtonsoft.Json.Linq.Extensions.Convert[T,U](T token)
[2022-05-05T18:40:58.490Z] at Newtonsoft.Json.Linq.Extensions.Value[T,U](IEnumerable1 value) [2022-05-05T18:40:58.493Z] at Microsoft.Azure.Workflows.ServiceProviders.CosmosDB.Utilities.CosmosDBUtilities.GetPatchOperations(InsensitiveDictionary1 parameters, String serviceId, CosmosDBOperationType operationType)
[2022-05-05T18:40:58.496Z] at Microsoft.Azure.Workflows.ServiceProviders.CosmosDB.Operations.PatchItemOperation.ExecuteAsync(Container container, String serviceId, InsensitiveDictionary1 parameters) [2022-05-05T18:40:58.498Z] at Microsoft.Azure.Workflows.ServiceProviders.CosmosDB.Providers.CosmosDBServiceOperationsProvider.InvokeOperation(String operationId, InsensitiveDictionary1 connectionParameters, ServiceOperationRequest serviceOperationRequest)
[2022-05-05T18:40:58.500Z] at Microsoft.Azure.Workflows.ServiceProviders.CosmosDB.Providers.CosmosDBServiceOperationsProvider.InvokeOperation(String operationId, InsensitiveDictionary`1 connectionParameters, ServiceOperationRequest serviceOperationRequest)', organizationId='', activityVector='IN.04', additionalProperties='', extensionVersion='1.0.0.0', siteName='UNDEFINED_SITE_NAME', slotName='', activityId='471d1082-cf81-4065-9783-28c61319e7c9'.
below is the Cosmos DB action for patchOperations :
"parameters": {
"databaseId": "messages",
"containerId": "espcreation",
"itemId": "#body('Parse_JSON')?['id']",
"partitionKey": "#body('Parse_JSON')?['recipient']",
"patchOperations": [
{
"type": "Set",
"path": "/currentstatus",
"value": "#body('Parse_JSON')?['type']"
},
{
"type": "Add",
"path": "/steps/-",
"value": "#body('Parse_JSON_2')"
}
]
},
I need to add Json object into array field in Azure Cosmos DB but I stuck on this issue.
Is there anybody can show me how to figure it out?
thanks,
-DB

Unable to get graph api user groups using access token using MSALjs

I am using msaljs in angular with .net. I am able to get a v2 oauth token but in .net, the GetMyMemberOfGroupsAsyncmethod returns a 401 with invalid compact token error. I tried changing the scopes in the application but to no use.
Here's the angular config file
{
"msalConfig": {
"clientId": "CLIENT_ID",
"authority": "https://login.microsoftonline.com/TENANT_ID/",
"validateAuthority": true,
"redirectUri": "http://localhost:3000/",
"postLogoutRedirectUri": "http://localhost:3000/"
},
"angular": {
"popUp": false,
"consentScopes": [
"user.read.all",
"directory.Read.all"
]
}
}
Below is the token parsed via JWT.io
{
"aud": "AUD",
"iss": "https://login.microsoftonline.com/TENANT_ID/v2.0",
"iat": 1592242137,
"nbf": 1592242137,
"exp": 1592246037,
"aio": "",
"email": "",
"family_name": "",
"given_name": "",
"name": "",
"nonce": "",
"oid": "",
"preferred_username": "USERNAME",
"sub": "",
"tid": "",
"uti": "",
"ver": "2.0"
}
The exception occurs in the last line of the below code segment:
public async Task<List<Group>> GetMyMemberOfGroupsAsync(string accessToken)
{
List<Group> groups = new List<Group>();
PrepareAuthenticatedClient(accessToken);
// Get groups the current user is a direct member of.
IUserMemberOfCollectionWithReferencesPage memberOfGroups = await graphServiceClient.Me.MemberOf.Request().GetAsync();
I get the following exception on my .net backend
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
Status Code: Unauthorized
Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken
Message: CompactToken parsing failed with error code: 80049217
Inner error:
AdditionalData:
date: 2020-06-16T12:44:50
request-id: ce0a83bf-3e33-4510-b4f6-9840dfb85a8a
ClientRequestId: ce0a83bf-3e33-4510-b4f6-9840dfb85a8a
The endpoints use v2.0. Also, i tried adding protected resource maps like the following in the config file but the token seems to be unaffected:
protectedResourceMap: [
['https://graph.microsoft.com/v1.0/me', ['user.read']]
];

How to use generated accessToken upon Firebase account creation?

After I create user with email and password as below,
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
firebase returns me created user object like this:
{
"uid": "huuX6OwdbfNvthORiDzNV6seo3D3",
"displayName": null,
"photoURL": null,
"email": "qqq2#yahoo.com",
"emailVerified": false,
"phoneNumber": null,
"isAnonymous": false,
"providerData": [
{
"uid": "qqq2#yahoo.com",
"displayName": null,
"photoURL": null,
"email": "qqq2#yahoo.com",
"phoneNumber": null,
"providerId": "password"
}
],
"apiKey": "qqqwwweee",
"appName": "[DEFAULT]",
"authDomain": null,
"stsTokenManager": {
"apiKey": "qqqwwweee",
"refreshToken": "AGdpqewb4UYbr5Uo5",
"accessToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImI4OWY",
"expirationTime": 1532487232918
},
"redirectEventId": null,
"lastLoginAt": "1532483591000",
"createdAt": "1532482346000"
}
Then every time I use signInWithEmailAndPassword method it generates new accessToken and refreshToken.
But I would like to use accessToken until it expires for created user, what method I can use to validate user with this token. So, I do not need to make user sign-in every time.
And method provided for this?
You are accessing internals of a user. These are subject to change. You should rely on the officially documented API. accessToken is basically the internal name of Firebase ID token. The correct way to get it is by calling user.getIdToken(). This will return the cached token if not expired or will refresh the token under the hood for you.

DynamoDb documentClient.update or delete StringSet throws ValidationException

I successfully update and delete an item from a StringSet in a dynamoDb table when called from my test app running on localhost.
I then upload the app to LightSail but now when I call the same function to update or delete an item it throws a ValidationException!:
{
"message": "Invalid UpdateExpression: Incorrect operand type for operator or
function; operator: DELETE, operand type: MAP",
"code": "ValidationException",
"time": "2018-01-03T13:20:14.919Z",
"requestId": "9HCQMH5RAUBRK1K7BNESNBUD5BVV4KQNSO5AEMVJF66Q9ASUAAJG",
"statusCode": 400,
"retryable": false,
"retryDelay": 10.381373865940402
}
Why? I have not made any changes to my code so why does this happen and how to solve it?
Here's the relevant code:
var documentClient = getDocumentClient();
var paramsSET = {
ExpressionAttributeNames:
{
"#StringSet": "Packages"
},
ExpressionAttributeValues:
{
":value": documentClient.createSet(['filler as SET cannot be empty',
app.packageName
])
},
Key:
{
"EmailAddress": app.emailAddress
},
ReturnValues: "ALL_NEW",
TableName: "Developers",
UpdateExpression: "ADD #StringSet :value"
// UpdateExpression: "DELETE #StringSet :value" ------ to delete value
};
// adds packagename to Packages SET in developers table - creates set if not exist
documentClient.update(paramsSET, function (err, data){}
I could not get it to work using the documentclient api.
finally used the old api and got it to work using dynamodb.updateItem see docs here
still have no idea why it works on localhost (accessing the same dynamodb tables) and not when live on LightSail!

Resources