Angular 11 application not getting authenticated by Microsoft Azure Active Directory - azure-active-directory

I'm a beginner in Azure Active Directory Authentication concept.
I'm trying to implement Azure Active Directory Authentication in an existing "Angular - Web API Core" application (Multi-tenant).
I've implemented everything as per instructions from Microsoft Azure Active Directory Docs.
Still the "AuthenticationResult" is getting returned as NULL on the Angular Client side of the application after the "loginRedirect" method is getting invoked. (No application specific Web API call is getting invoked here).
Issue: Application Login Page => On clicking the "Login" button user is navigated to Microsoft Azure Login Page => Providing the credential and user is getting re-directed back to the application Login page and NOT to the registered RedirectURI
Providing below the structure of the application:
authService => instance of MsalService.
msalBroadCastService => instance of MsalBroadcastService.
msalGuardConfig => instance of MsalGuardConfiguration.
isUserLoggedIn: boolean = false;
app.component.ts
ngOnInit(): void {
this.authService.handleRedirectObservable().subscribe({
next: (result: AuthenticationResult) => { // few console log code snippet },
error: (error) => console.log(error)
});
}
login.component.ts
ngOnInit() {
// have tried the following with "handleRedirectPromise" also, but it didn't work.
this.authService.handleRedirectObservable().subscribe({
next: (result: AuthenticationResult) => {
this.msalBroadCastService.inProgress$
.pipe(
filter((status: InteractionStatus) => status === InteractionStatus.None),
takeUntil(this.destroy$)
)
.subscribe((x) => {
// the component "redirect-path" is the redirectURI mentioned in the application configuration file and also in the Azure Active Directory redirectURI section.
if (result)
this.router.navigate(['redirect-path']);
})
},
error: (errorMsg) => {
debugger;
console.log(errorMsg)
}
});
....
....
// Existing logic to load the application "Login" page.
}
onLogin(){
this.authService.instance.handleRedirectPromise()
.then((tokenResponse) => {
if (!tokenResponse) {
this.isUserLoggedIn = this.authService.instance.getAllAccounts().length == 0;
if (this.isUserLoggedIn) {
this.authService.loginRedirect({ ...this.msalGuardConfig.authRequest } as RedirectRequest);
}
}
});
}
app.module.ts
MsalModule.forRoot(new PublicClientApplication(
{
auth: {
clientId: '<Client ID>',
redirectUri: 'http://localhost:4200/#/redirect-path',
authority: 'https://login.microsoftonline.com/organizations'
// authority: 'https://login.microsoftonline.com/common' // Tried this also, but didn't work.
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: isIE
},
system: {
loggerOptions: {
loggerCallback: (level: LogLevel, message: string, containsPii: boolean): void => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
}
},
piiLoggingEnabled: false
},
windowHashTimeout: 60000,
iframeHashTimeout: 6000,
loadFrameTimeout: 0,
asyncPopups: false
}
}
),
{
interactionType: InteractionType.Redirect,
authRequest: {
scopes: ['user.read']
}
},
{
interactionType: InteractionType.Redirect,
protectedResourceMap: new Map(
[
['https://graph.microsoft.com/v1.0/me', ['user.read']]
]
)
}
)
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
}, MsalGuard
]
app-routing.module.ts
const routes: Routes = [
{ path: '', component: LoginComponent, pathMatch: 'full' },
// { path: '', component: LoginComponent, pathMatch: 'full', canActivate: [MsalGuard] },
{ path: 'redirect-path', component: RedirectPathComponent, pathMatch: 'full' },
// { path: 'redirect-path', component: RedirectPathComponent, pathMatch: 'full', canActivate: [MsalGuard] },
]
index.html
<body>
<app-root></app-root>
<app-redirect></app-redirect>
</body>
Please do let me know if any other configuration related information is required (that I might have missed).
Your guidance will be much appreciated.

Hi Debasmita you should not clear all data stored in localstorage while initializing LoginComponent. This is because PublicClientApplication is configured to use local storage (cacheLocation: 'localStorage')

Related

Error: `siteUrl` does not exist on `siteMetadata` in the data returned from the query. How to resolve?

When building my Gatsby website I get the below error.
I've tried to delete and reinstall npm, update the plugins, deleting (Gatsby) cache, playing around with the siteUrl and all kinds of settings in the Gatsby config. But I can't seem to get rid of the error. The development environment works fine.
github: https://github.com/bartfluitsma/gatsby-bart-fluitsma
**Error console log**
ERROR #11321 PLUGIN
"gatsby-plugin-sitemap" threw an error while running the onPostBuild lifecycle:
`siteUrl` does not exist on `siteMetadata` in the data returned from the query.
Add this to your `siteMetadata` object inside gatsby-config.js or add this to your custom query or provide a custom `resolveSiteUrl` function.
https://www.gatsbyjs.com/plugins/gatsby-plugin-sitemap/#api-reference
47 | errors = _yield$graphql.errors;
48 | _context.next = 9;
> 49 | return Promise.resolve(resolveSiteUrl(queryRecords)).catch(function (err) {
| ^
50 | return reporter.panic(_internals.REPORTER_PREFIX + " Error resolving Site URL", err);
51 | });
52 |
File: node_modules\gatsby-plugin-sitemap\gatsby-node.js:49:36
Error: `siteUrl` does not exist on `siteMetadata` in the data returned from the query.
Add this to your `siteMetadata` object inside gatsby-config.js or add this to your custom query or provide a custom `resolveSiteUrl` function.
https://www.gatsbyjs.com/plugins/gatsby-plugin-sitemap/#api-reference
- internals.js:62 resolveSiteUrl
[gatsby-bart-fluitsma]/[gatsby-plugin-sitemap]/internals.js:62:11
- gatsby-node.js:49 _callee$
[gatsby-bart-fluitsma]/[gatsby-plugin-sitemap]/gatsby-node.js:49:36
not finished onPostBuild - 0.480s
Gatsby-config.js
module.exports = {
siteMetadata: {
title: `Bart Fluitsma`,
description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
author: `#gatsbyjs`,
siteUrl: `http://bartfluitsma.com`,
},
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-plugin-image`,
'gatsby-plugin-postcss',
{
resolve: `gatsby-plugin-google-fonts-with-attributes`,
options: {
fonts: [
`montserrat\:300,400,400i,600,900`,
],
display: 'swap',
attributes: {
rel: "stylesheet preload prefetch",
},
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
}, {
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/locales`,
name: `locale`
}
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `Web development | Bart Fluitsma`,
short_name: `Bart develops`,
start_url: `/`,
background_color: `#663399`,
// This will impact how browsers show your PWA/website
// https://css-tricks.com/meta-theme-color-and-trickery/
// theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/logo-bart-fluitsma-web-design.svg`, // This path is relative to the root of the site.
},
},
{
resolve: `gatsby-plugin-react-i18next`,
options: {
localeJsonSourceName: `locale`, // name given to `gatsby-source-filesystem` plugin.
languages: [`en`, `nl`],
defaultLanguage: `en`,
// if you are using Helmet, you must include siteUrl, and make sure you add http:https
siteUrl: `https://bartfluitsma.com`,
// you can pass any i18next options
i18nextOptions: {
interpolation: {
escapeValue: false // not needed for react as it escapes by default
},
keySeparator: false,
nsSeparator: false
},
pages: [
{
matchPath: '/:lang?/blog/:uid',
getLanguageFromPath: true
},
]
}
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
{
resolve: 'gatsby-plugin-sitemap',
options: {
excludes: ['/**/404', '/**/404.html'],
query: `
{
site {
siteMetadata {
siteUrl
}
}
allSitePage(filter: {context: {i18n: {routed: {eq: false}}}}) {
edges {
node {
context {
i18n {
defaultLanguage
languages
originalPath
}
}
path
}
}
}
}
`,
serialize: ({ site, allSitePage }) => {
return allSitePage.edges.map((edge) => {
const { languages, originalPath, defaultLanguage } = edge.node.context.i18n;
const { siteUrl } = site.siteMetadata;
const url = siteUrl + originalPath;
const links = [
{ lang: defaultLanguage, url },
{ lang: 'x-default', url }
];
languages.forEach((lang) => {
if (lang === defaultLanguage) return;
links.push({ lang, url: `${siteUrl}/${lang}${originalPath}` });
});
return {
url,
changefreq: 'daily',
priority: originalPath === '/' ? 1.0 : 0.7,
links
};
});
}
}
},
],
}
The error is thrown by gatsby-plugin-sitemap. Try adding the resolveSiteUrl method in your configuration like:
const siteUrl = process.env.URL || `https://fallback.net`
resolveSiteUrl: () => siteUrl,
Applied to your code:
const siteUrl = process.env.URL || `https://fallback.net`
module.exports = {
plugins: [
{
resolve: "gatsby-plugin-sitemap",
options: {
excludes: ["/**/404", "/**/404.html"],
query: `
{
site {
siteMetadata {
siteUrl
}
}
allSitePage(filter: {context: {i18n: {routed: {eq: false}}}}) {
edges {
node {
context {
i18n {
defaultLanguage
languages
originalPath
}
}
path
}
}
}
}
`,
resolveSiteUrl: () => siteUrl,
serialize: ({ site, allSitePage }) => {
return allSitePage.edges.map((edge) => {
const { languages, originalPath, defaultLanguage } =
edge.node.context.i18n;
const { siteUrl } = site.siteMetadata;
const url = siteUrl + originalPath;
const links = [
{ lang: defaultLanguage, url },
{ lang: "x-default", url },
];
languages.forEach((lang) => {
if (lang === defaultLanguage) return;
links.push({ lang, url: `${siteUrl}/${lang}${originalPath}` });
});
return {
url,
changefreq: "daily",
priority: originalPath === "/" ? 1.0 : 0.7,
links,
};
});
},
},
},
],
};
Change the siteUrl and the fallback URL accordingly if you are not setting it in your environment file
The answer by Ferran Buireu ultimately was not the solution for OP. I had experienced the same issue and this solution would have solved his issue hadn't he abandoned it. Check this GitHub thread.
Your siteUrl issue just masks that the query was invalid, as the context is not available in gatsby >= 4 anymore, as you found out after fixing the siteUrl.
You may have used this query from the gatsby-plugin-react-i18next docs to support a sitemap.
In order to make it work, I found you have to 1. create the context yourself, and 2. adjust the queries
Create your context through gatsby-node.js (credit wilsonvolker)
/**
* Workaround for missing sitePage.context:
* Used for generating sitemap with `gatsby-plugin-react-i18next` and `gatsby-plugin-sitemap` plugins
* https://www.gatsbyjs.com/docs/reference/release-notes/migrating-from-v3-to-v4/#field-sitepagecontext-is-no-longer-available-in-graphql-queries
*/
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions
createTypes(`
type SitePage implements Node {
context: SitePageContext
}
type SitePageContext {
i18n: i18nContext
}
type i18nContext {
language: String,
languages: [String],
defaultLanguage: String,
originalPath: String
routed: Boolean
}
`)
}
It looks like the serialize function proposed in the i18next doesn't work as-is anymore since it apparently receives a single node, not the full graphql response. So, a few changes in gatsby-config.js to make it work again (this assumes you have a global siteUrl variable available):
query: `
{
site {
siteMetadata {
siteUrl
}
}
allSitePage(filter: {context: {i18n: {routed: {eq: false}}}}) {
nodes {
context {
i18n {
defaultLanguage
languages
originalPath
}
}
path
}
}
}
`,
serialize: (node) => {
const { languages, originalPath, defaultLanguage } = node.context.i18n
const url = siteUrl + originalPath
const links = [
{ lang: defaultLanguage, url },
{ lang: 'x-default', url },
]
languages.forEach((lang) => {
if (lang === defaultLanguage) return
links.push({ lang, url: `${siteUrl}/${lang}${originalPath}` })
})
return {
url,
changefreq: 'daily',
priority: originalPath === '/' ? 1.0 : 0.7,
links,
}
},
This worked for me without the need to create new types:
{
resolve: "gatsby-plugin-sitemap",
options: {
excludes: ["/**/404", "/**/404.html"],
resolveSiteUrl: () => siteUrl,
query: `
{
allSitePage {
edges {
node {
pageContext
}
}
}
}
`,
resolvePages: ({ allSitePage: { edges } }) => {
return edges
.filter(
({ node }) => !["/404/", "/404.html"].includes(node.pageContext.i18n.originalPath)
)
.map(({ node: { pageContext } }) => {
const { languages, originalPath, path, defaultLanguage } = pageContext.i18n;
const baseUrl = siteUrl + originalPath;
const links = [{ lang: "x-default", url: baseUrl }];
languages.forEach((lang) => {
const isDefaultLang = lang === defaultLanguage;
const isDefaultPath = path === originalPath;
const isLangSubDir = path.includes(`${lang}/`);
if (isDefaultLang && isDefaultPath) return;
if (!isDefaultLang && isLangSubDir) return;
links.push({
lang,
url: isDefaultLang ? baseUrl : `${siteUrl}/${lang}${originalPath}`,
});
});
return {
path,
url: path === "/" ? siteUrl : `${siteUrl}/${path}`,
changefreq: "daily",
priority: originalPath === "/" ? 1.0 : 0.7,
links,
};
});
},
serialize: (page) => page,
},
}
Versions:
Node: 18.13.0
"gatsby": "^5.3.3",
"gatsby-plugin-react-i18next": "^3.0.1",
"gatsby-plugin-sitemap": "^6.5.0",

social login (nextauth) isn't working with after i add autoprefixer

does anyone know what this means, and how i can debug it - i've tried react dev tools - and the states and everything disappear as soon as this message pops up:
Server Error
TypeError: Cannot destructure property 'id' of 'undefined' as it is undefined.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
<unknown>
file:///home/abda_react/abdn2/node_modules/next-auth/server/lib/providers.js (29:5)
Array.find
<anonymous>
parseProviders
file:///home/abda_react/abdn2/node_modules/next-auth/server/lib/providers.js (28:30)
NextAuthHandler
file:///home/abda_react/abdn2/node_modules/next-auth/server/index.js (88:30)
<unknown>
file:///home/abda_react/abdn2/node_modules/next-auth/server/index.js (251:38)
Object.apiResolver
file:///home/abda_react/abdn2/node_modules/next/dist/server/api-utils.js (101:15)
runMicrotasks
<anonymous>
processTicksAndRejections
node:internal/process/task_queues (96:5)
async DevServer.handleApiRequest
file:///home/abda_react/abdn2/node_modules/next/dist/server/next-server.js (770:9)
async Object.fn
file:///home/abda_react/abdn2/node_modules/next/dist/server/next-server.js (661:37)
my nextauth config file:
import NextAuth from "next-auth"
import EmailProvider from 'next-auth/providers/email';
import GoogleProvider from "next-auth/providers/google";
export default NextAuth({
// Configure one or more authentication providers
providers: [
,EmailProvider({
server: process.env.EMAIL_SERVER,
from: process.env.EMAIL_FROM,
})
,GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
// ...add more providers here
],
jwt: {
encryption: true,
},
secret: process.env.secret,
//https://www.youtube.com/watch?v=QK24lEvRTI8
callback: {
// async jwt(token, account) {
// if (account?.accessToken) {
// token.accessToken = account.accessToken;
// }
// return token;
// },
// redirect: async (url, _baseUrl) => {
// if (url === '/') {
// return Promise.resolve('/index');
// }
// return Promise.resolve('/index');
// }
},
pages: {
// signIn: '/auth/signin',
// signOut: '/auth/signout',
// error: '/auth/error', // Error code passed in query string as ?error=
// verifyRequest: '/auth/verify-request', // (used for check email message)
// newUser: '/auth/new-user' // New users will be directed here on first sign in (leave the property out if not of interest)
}
})
// https://console.cloud.google.com/projectselector2/apis/credentials?authuser=1&pli=1&supportedpurview=project
//All requests to /api/auth/* (signIn, callback, signOut, etc.) will automatically be handled by NextAuth.js.
could it be something that's wrongly configured?? but i dont understand why it would work before i installed auto prefixer...
here is the providers file(i did not write a single code of it):
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = parseProviders;
var _merge = require("../../lib/merge");
function parseProviders(params) {
const {
base,
providerId
} = params;
const providers = params.providers.map(({
options,
...rest
}) => {
var _userOptions$id, _userOptions$id2;
const defaultOptions = normalizeProvider(rest);
const userOptions = normalizeProvider(options);
return (0, _merge.merge)(defaultOptions, { ...userOptions,
signinUrl: `${base}/signin/${(_userOptions$id = userOptions === null || userOptions === void 0 ? void 0 : userOptions.id) !== null && _userOptions$id !== void 0 ? _userOptions$id : rest.id}`,
callbackUrl: `${base}/callback/${(_userOptions$id2 = userOptions === null || userOptions === void 0 ? void 0 : userOptions.id) !== null && _userOptions$id2 !== void 0 ? _userOptions$id2 : rest.id}`
});
});
const provider = providers.find(({
id
}) => id === providerId);
return {
providers,
provider
};
}
function normalizeProvider(provider) {
var _provider$version;
if (!provider) return;
const normalizedProvider = Object.entries(provider).reduce((acc, [key, value]) => {
if (["authorization", "token", "userinfo"].includes(key) && typeof value === "string") {
var _url$searchParams;
const url = new URL(value);
acc[key] = {
url: `${url.origin}${url.pathname}`,
params: Object.fromEntries((_url$searchParams = url.searchParams) !== null && _url$searchParams !== void 0 ? _url$searchParams : [])
};
} else {
acc[key] = value;
}
return acc;
}, {});
if (provider.type === "oauth" && !((_provider$version = provider.version) !== null && _provider$version !== void 0 && _provider$version.startsWith("1.")) && !provider.checks) {
normalizedProvider.checks = ["state"];
}
return normalizedProvider;
}
so..from what i am guessing, there is no property id in there...but i have no idea why that would change after installing autoprefixer, and also i have no idea how to even consider adding id into this.
update
changed the providers variable to see maybe it's just google...and it seems i have another issue which i think might be related. here is the error:
./pages/api/auth/[...nextauth].js:3:0
Module not found: Package path ./providers is not exported from package /home/abda_react/abdn2/node_modules/next-auth (see exports field in /home/abda_react/abdn2/node_modules/next-auth/package.json)
1 | import NextAuth from "next-auth"
2 | import EmailProvider from 'next-auth/providers/email';
> 3 | import Providers from "next-auth/providers";
4 |
5 | export default NextAuth({
6 | // Configure one or more authentication providers
Import trace for requested module:
https://nextjs.org/docs/messages/module-not-found
here is what i changed:
import NextAuth from "next-auth"
import EmailProvider from 'next-auth/providers/email';
import Providers from "next-auth/providers";
export default NextAuth({
// Configure one or more authentication providers
providers: [
// ,EmailProvider({
// server: process.env.EMAIL_SERVER,
// from: process.env.EMAIL_FROM,
// })
,Providers.Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
// ...add more providers here
package.json:
"exports": {
".": "./index.js",
"./jwt": "./jwt/index.js",
"./react": "./react/index.js",
"./providers/*": "./providers/*.js"
},
ok two things:
my email provider credentials were placeholders - that's not good.
your signin page needs to be set
for completion, here's what i did:
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google";
export default NextAuth({
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
]
,callback: {
async jwt(token, account) {
if (account?.accessToken) {
token.accessToken = account.accessToken;
}
return token;
},
redirect: async (url, _baseUrl) => {
if (url === '/') {
return Promise.resolve('/index');
}
return Promise.resolve('/index');
}
,pages: {
signIn: '/index',
signOut: '/index',
}
,debug: false
}
})
even though i still cant import all providers - it works, so good enough for now
but again...not sure why it worked before autoprefix...

cloudconvert API NOT working with netlify Serverless function

I was using cloudconvert api from node JS, which was working fine when I hosted in heroku. But when I made netlify serverless function it is returning error. Is it because serverless function exits before completing the task?
try {
let job = await cloudConvert.jobs.create({
tasks: {
'const-1': {
operation: 'const/raw',
// file: file_string_output,
file: '<div>Welcome ... testing...</div>',
filename: `${fileName}.html`,
},
'task-1': {
operation: 'convert',
input_format: 'html',
output_format: 'pdf',
engine: 'chrome',
input: ['const-1'],
zoom: 1,
print_background: true,
display_header_footer: false,
wait_until: 'load',
wait_time: 0,
},
'export-1': {
operation: 'export/s3',
input: ['task-1'],
bucket: process.env.S3_BUCKET_NAME,
region: process.env.S3_BUCKET_REGION,
access_key_id: process.env.S3_ACCESS_KEY,
secret_access_key: process.env.S3_ACCESS_SECRETE,
key: `${process.env.S3_BUCKET_FOLDER}/${fileName}.pdf`,
},
},
})
cloudConvert.jobs.subscribeEvent(job.id, 'finished', (event) => {
console.log('cloud convert stages finished', event.job)
})
cloudConvert.jobs.subscribeEvent(job.id, 'error', (event) => {
console.log('error', event.job)
})
cloudConvert.jobs.subscribeTaskEvent(job.id, 'finished', async (event) => {
console.log('cloud convert Task stages finished', event.job)
})
cloudConvert.jobs.subscribeTaskEvent(job.id, 'error', (event) => {
console.log('Task on error', event.task)
})
} catch (error) {
console.log(' Cloud convert key is invalid??:', error)
}
I have figured out the problem. In below code, there was a typo.
operation: 'const/raw', ==>>>> operation: 'import/raw'
It was my bad. Since the netlify serverless did not support Es6, I have to change all import syntax to require() syntax and I had a global search and replace import==> const which effected here as well. So silly me...
'const-1': {
operation: 'const/raw', ==>>>>
// file: file_string_output,
file: '<div>Welcome ... testing...</div>',
filename: `${fileName}.html`,
},

How do I prevent Heroku from deleting my Postgress database when pushing to github?

Whenever I push changes to Github and my backend rebuilds itself on Heroku, it resets/deletes the Postgress database. How can I prevent this?
I fixed the problem. Before pushing my application to production, I was using Sqlite. It seems as though I was still using it. Once I turned sqlite of, the problem doesn't happen anymore!
The working code:
const parse = require('pg-connection-string').parse;
module.exports = ({ env }) => {
if(env('NODE_ENV') === 'production') {
const config = parse(process.env.DATABASE_URL)
return {
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'postgres',
host: config.host,
port: config.port,
database: config.database,
username: config.user,
password: config.password
},
options: {
ssl: false
}
}
}
}
}
return {
// defaultConnection: 'default',
// connections: {
// default: {
// connector: 'bookshelf',
// settings: {
// client: 'sqlite',
// filename: env('DATABASE_FILENAME', '.tmp/data.db'),
// },
// options: {
// useNullAsDefault: true,
// },
// },
// },
}
};

React nativ, aws-amplify storage, getting aws.cognito.identity-id

i am trying to get aws.cognito.identity-id with React-Native. After successeful sign-in i am getting CognitoUser, but storage variable is equal to [Function MemoryStorage], however with React in my web browser storage has some values. Code in React and React native exactly same.
Browser output:
...
storage: Storage
CognitoIdentityId-eu-central-1:...: "..."
CognitoIdentityServiceProvider.....LastAuthUser: "..."
CognitoIdentityServiceProvider.........accessToken: "..."
CognitoIdentityServiceProvider........clockDrift: "2"
...
Android device output:
...
"storage": [Function MemoryStorage],
...
Code
Amplify.configure({
...awsmobile
});
const client = new AWSAppSyncClient({
url: awsmobile.aws_appsync_graphqlEndpoint,
region: awsmobile.aws_appsync_region,
auth: {
type: AUTH_TYPE.AWS_IAM,
credentials: () => Auth.currentCredentials()
},
});
Auth.signIn(
'myemail#gmail.com',
'pass'
)
// .then(user => console.log('user',user))
.then(user => signInSuccess(user));
function getValueFromKey(myObject, string) {
const key = Object.keys(myObject).filter(k => k.includes(string));
return key.length ? myObject[key] : "";
}
function signInSuccess(user) {
console.log('another', user);
console.log(getValueFromKey(user.storage, 'aws.cognito.identity-id'))
}
export default class App extends React.Component {
render() {
return (
<Text>nice</Text>
);
}
}

Resources