I am trying to get push notifications / firebase messaging to work with react native - I have gotten as far as checking / requesting permission, and I implemented onMessage, but I don't get any of my test messages (sent from the firebase developer console online, in the cloud messaging section). One thing that is odd is when I check the status of a completed message, it says no messages were sent (0 sent), so I don't even know if my app is getting the chance to receive a test message. Here is my code:
HomeScreen.js (the default route of the root navigator)
export default class HomeScreen extends React.Component {
....
componentDidMount() {
firebase.messaging()
.hasPermission()
.then(enabled => {
if (!enabled) {
this._getPermission();
}
firebase.messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
// user has a device token
} else {
alert("User doesn't have a token yet");
}
}).catch((error) => {
alert(error);
});
firebase.messaging().subscribeToTopic('all').catch((error) => {alert(error)});
this.onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
// Process your token as required
});
this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
// Process your message as required
alert(message);
});
}).catch((error) => {alert(error)});
}
_getPermission = () => {
firebase.messaging()
.requestPermission()
.catch(error => {
// User has rejected permissions
this._getPermission();
});
};
....
componentWillUnmount() {
this.onTokenRefreshListener();
this.messageListener();
firebase.messaging().unsubscribeFromTopic('all');
}
....
AppDelegate.h
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <UIKit/UIKit.h>
#import UserNotifications;
#interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>
#property (nonatomic, strong) UIWindow *window;
#end
AppDelegate.m
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"
#import <Firebase.h>
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[RNFirebaseNotifications configure];
NSURL *jsCodeLocation;
for (NSString* family in [UIFont familyNames])
{
NSLog(#"%#", family);
for (NSString* name in [UIFont fontNamesForFamilyName: family])
{
NSLog(#" %#", name);
}
}
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:#"snagit"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
return YES;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}
#end
My BUNDLE_ID's all appear to be correct. Why aren't the messages being sent in the first place and/or, why am I not receiving them?
UPDATE
Would trying FCM help? https://github.com/evollu/react-native-fcm
UPDATE
My request was bad, I got a curl try to work with:
curl -i -H 'Content-type: application/json' -H 'Authorization:
key=server-key'
-XPOST https://fcm.googleapis.com/fcm/send -d '{"to": "/topics/all","data": {"message": "This is a Firebase Cloud Messaging
Topic Message!"}}'
I received:
HTTP/2 200
content-type: application/json; charset=UTF-8
date: Tue, 18 Sep 2018 21:38:21 GMT
expires: Tue, 18 Sep 2018 21:38:21 GMT
cache-control: private, max-age=0
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
server: GSE
alt-svc: quic=":443"; ma=2592000; v="44,43,39,35"
accept-ranges: none
vary: Accept-Encoding
{"message_id":5323681878653027379}
So why doesn't it work coming from the firebase web console? Could this be an issue that needs to be resolved by firebase?
UPDATE
To further test whether or not this is on the firebase side of things I wrote a cloud function that should send a notification when a certain document is updated/created/deleted:
exports.sendMessageNotification = functions.firestore().document('conversations/{conversationID}/messages/{messageID}').onWrite((change, context) => {
// Get an object representing the document
// e.g. {'name': 'Marie', 'age': 66}
const newValue = change.after.data();
// ...or the previous value before this update
const previousValue = change.before.data();
// access a particular field as you would any JS property
//const name = newValue.name;
var topic = 'all';
var payload = {
notification: {
title: "You got a new Message",
body: newValue.notification.body,
}
};
admin.messaging().sendToTopic(topic, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
});
Here is my code which successfully writes an object to the above firestore location:
....
constructor() {
super();
this.onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
// Process your token as required
});
this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
// Process your message as required
alert(message);
});
//this.ref = firebase.firestore().collection('items');
//this.authSubscription = null;
}
....
componentDidMount() {
firebase.messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
console.log(fcmToken);
// Add a new document with a generated id.
const addMessage = firebase.firestore().collection('conversations').doc('1234567').collection('messages').doc('1234567');
data = {
notification: {
title: "You got a new Message",
body: "You got a new message",
}
}
// Set the 'capital' field of the city
const updateMessage = addMessage.update(data).catch((error) => {
alert(error);
addMessage.set(data).catch((error) => {
alert(error);
});
});
} else {
alert("User doesn't have a token yet");
}
}).catch((error) => {
alert(error);
});
....
}
For output I see the console.log(fcmToken) message. When I check the firebase functions log, I see Successfully sent message: { messageId: 6994722519047563000 }. When I check firestore, the document was created (or updated) correctly and it is in the correct place to be noticed (and it is on the firebase side according to the firebase function logs) - but I still never receive an actual notification on my iPhone.
Why am I not receiving the message if it is being sent?
UPDATE
I am now receiving notifications from the logic I created with firebase functions, the firebase web console just seems like it isn't working - the notifications still never get sent.
Solution
First of all, you need to get push notification in your device (not simulators).
I recommend to test with iOS and Android devices from firebase web console first. This process is not required codes on your delegate files handling push notifications except checking permission.
Anyway, suppose you do not have any android device and it is not working on your iOS device,
check bundle ids and GoogleService-Info.plist in firebase and XCode.
check your target capabilities on XCode. Push Notifications and Background Mode
Check app's permission of notification on iOS's setting
Why?
I am not sure how you set your firebase and XCode, but problems of push notifications from firebase web console are related in permissions, XCode setting and other settings normally.
In my case, typos of the bundle id in firebase settings was the problem.
If you can, you would test on Android also.
Related
How the registration is handled with a custom credential provider ( email + password)?
Currently my [...nextauth].js looks like this:
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import axios from 'axios'
import jwt from "next-auth/jwt";
const YOUR_API_ENDPOINT = process.env.NEXT_PUBLIC_API_ROOT + 'auth/store'
const providers = [
Providers.Credentials({
name: 'Credentials',
authorize: async (credentials) => {
try {
const user = await axios.post(YOUR_API_ENDPOINT,
{
password: credentials.password,
username: credentials.email
},
{
headers: {
accept: '*/*',
'Content-Type': 'application/json'
}
})
console.log('ACCESS TOKEN ----> ' + JSON.stringify(user.data.access_token, null, 2));
if (user) {
return {status: 'success', data: user.data}
}
} catch (e) {
const errorMessage = e.response.data.message
// Redirecting to the login page with error messsage in the URL
throw new Error(errorMessage + '&email=' + credentials.email)
}
}
})
]
const callbacks = {
/*
|--------------------------------------------------------------------------
| Callback : JWT
|--------------------------------------------------------------------------
*/
async jwt(token, user, account, profile, isNewUser) {
if (user) {
token.accessToken = user.data.access_token
}
return token
},
/*
|--------------------------------------------------------------------------
| Callback : Session
|--------------------------------------------------------------------------
*/
async session(session, token) {
// Store Access Token to Session
session.accessToken = token.accessToken
/*
|--------------------------------------------------------------------------
| Get User Data
|--------------------------------------------------------------------------
*/
const API_URL = 'http://localhost:3000/api';
const config = {
headers: { Authorization: `Bearer ${token.accessToken}` }
};
let userData;
await axios.get(`${API_URL}/user`, config)
.then(response => {
userData = {
id: response.data.id,
uuid: response.data.uuid,
username: response.data.username,
avatar_location: response.data.avatar_location,
gender_id: response.data.gender_id,
date_of_birth: response.data.date_of_birth,
country_id: response.data.country_id,
location: response.data.location,
about_me: response.data.about_me,
interests: response.data.interests,
website: response.data.website,
timezone: response.data.timezone,
full_name: response.data.full_name,
formatted_created_at: response.data.formatted_created_at,
formatted_last_seen: response.data.formatted_last_seen,
album_count: response.data.album_count,
total_unread_message_count: response.data.total_unread_message_count,
};
// Store userData to Session
session.user = userData
}).catch((error) => {
// Error
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
console.log('error.response: ' + error.request);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the
// browser and an instance of
// http.ClientRequest in node.js
console.log('error.request: ' + error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
return session
}
}
const options = {
providers,
callbacks,
session: {
// Use JSON Web Tokens for session instead of database sessions.
// This option can be used with or without a database for users/accounts.
// Note: `jwt` is automatically set to `true` if no database is specified.
jwt: true,
// Seconds - How long until an idle session expires and is no longer valid.
maxAge: 30 * 24 * 60 * 60, // 30 days
// Seconds - Throttle how frequently to write to database to extend a session.
// Use it to limit write operations. Set to 0 to always update the database.
// Note: This option is ignored if using JSON Web Tokens
updateAge: 24 * 60 * 60, // 24 hours
},
secret: process.env.SECRET,
jwt: {
// signingKey: process.env.JWT_SIGNING_PRIVATE_KEY,
//
// // You can also specify a public key for verification if using public/private key (but private only is fine)
// verificationKey: process.env.JWT_SIGNING_PUBLIC_KEY,
//
// // If you want to use some key format other than HS512 you can specify custom options to use
// // when verifying (note: verificationOptions should include a value for maxTokenAge as well).
// // verificationOptions = {
// // maxTokenAge: `${maxAge}s`, // e.g. `${30 * 24 * 60 * 60}s` = 30 days
// // algorithms: ['HS512']
// // },
secret: process.env.JWT_SECRET,
},
pages: {
error: '/login' // Changing the error redirect page to our custom login page
}
}
export default (req, res) => NextAuth(req, res, options)
All tutorials I found online only shows the login/signIn without details on how to implement registration
Registration is the process of registering the user, saving new users' credentials into the database. It is independent of next-auth. You create a form, submit the form and save the form data properly into the database.
next-auth takes over when you are logged in, in other words, you are authenticated meaning that you are already a registered, genuine user. Once you pass the security checks and successfully logged in, next-auth creates a session for the user.
You can view the set up demo for v4: next-auth 4 session returns null, next.js
next-auth only supports Sign In, Sign Up and Sign Out. When a user creates an account for the first time, It registers them automatically without the need for a new set of registration process.
I'm sending message to my bot using Microsoft BotConnector but they are not being logged as normal messages. For logging messages to the DB I wrote custom logger :
class CustomLogger {
/**
* Log an activity to the transcript file.
* #param activity Activity being logged.
*/
constructor() {
this.conversations = {};
}
logActivity(activity) {
if (activity) {
console.log("Log information")
}
if (!activity) {
throw new Error("Activity is required.");
}
if (activity.conversation) {
var id = activity.conversation.id;
if (id.indexOf("|" !== -1)) {
id = activity.conversation.id.replace(/\|.*/, "");
}
}
if (activity.type === "message") {
Conv.create({
text: activity.text,
conv_id: activity.conversation.id,
from_type: activity.from.role,
message_id: activity.id || activity.replyToId
}).then(() => {
console.log("logged");
});
delete this.conversations[id];
}
}
}
it works great with normal messages but it is no working with the messages that are sent to
POST /v3/conversations/{conversationId}/activities
via microsoft bot connector.
When I send message using the the bot connector it doesn't log the request via activity.
Code that I'm using to send proactive msg:
/**
* Send message to the user.
*/
function sendMessage(token, conversation, name) {
var config = {
headers: { "Authorization": "Bearer " + token }
};
var bodyParameters = {
"type": "message",
"text": name
}
axios.post(
'https://smba.trafficmanager.net/apis/v3/conversations/29:XXXXXXXXXXXXXXX/activities',
bodyParameters,
config
).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
}
let name = "Hey, How was your week?";
let conversation = "29:XXXXXXXXXXXXXXX";
run(conversation, name);
Instead of using the REST API to send proactive messages to users, I would recommend using the BotFramework Adapter to continue the conversation with the user. When you send the proactive message from the adapter, the activity passes through the logger middleware and gets saved to storage. If you would like to initiate the proactive message from an Azure Function, you can set up another messaging endpoint in the index file that you call from the function. Take a look at the code snippets below.
index.js
// Listen for incoming notifications and send proactive messages to user.
server.get('/api/notify/:conversationID', async (req, res) => {
const { conversationID } = req.params;
const conversationReference = conversationReferences[conversationID];
await adapter.continueConversation(conversationReference, async turnContext => {
await turnContext.sendActivity('proactive hello');
});
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write('<html><body><h1>Proactive messages have been sent.</h1></body></html>');
res.end();
});
For more details I would take a look at this Proactive Messages Sample. It is in the samples-work-in-progress branch and might change slightly, but it is a great example of how to configure your project to send a proactive message from a Restify endpoint.
Hope this helps!
I have an Outlook add-ins using React + TypeScript, debugging locally with Node.js. I'm using the office-js-helpers library to authenticate and the msgraph-sdk-javascript Graph client library. As a POC I'm simply trying to verify that I can successfully call Graph, by retrieving details of the current email by its id. I can successfully use the office-js-helpers Authenticator to authorize the app, and successfully retrieve a token.
However, when I use the Graph client to make a call to v1/me/messages/{ID}, I get:
"401 InvalidAuthenticationToken: Access token validation failure"
I'm not sure whether this is a problem with the way I'm using the Authenticator, or a problem with my add-in or app's manifests. My add-in is using these for AppDomains:
<AppDomains>
<AppDomain>https://localhost:3000</AppDomain>
<AppDomain>https://login.microsoftonline.com</AppDomain>
</AppDomains>
I am using https://localhost:3000 as my app's redirect URI, with implicit auth enabled.
If I use the force option with the authenticate method, I also get this error:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://login.microsoftonline.com') does not match the recipient window's origin ('https://localhost:3000').
However, I am able to retrieve a token.
What am I doing wrong? I'm not certain about the flow for the Authenticator, in terms of when to use authenticator.tokens.get and authenticator.authenticate. For the first run I assume always authenticate and no need to use tokens.get, and for second run I assume just use tokens.get, but if I try either of those or always both it doesn't seem to change the result of an invalid token.
import * as React from "react";
import { Button, ButtonType, TextField } from "office-ui-fabric-react";
import { Authenticator, Utilities, DefaultEndpoints } from "#microsoft/office-js-helpers";
import * as Graph from "#microsoft/microsoft-graph-client";
export default class GetItemOJSHelpers extends React.Component<any, any> {
constructor(props) {
super(props);
this.getEmail = this.getEmail.bind(this);
this.callGraph = this.callGraph.bind(this);
this.getItemRestId = this.getItemRestId.bind(this);
this.state = { graphResponse: "", accessToken: "" };
console.log("====GetItemOJSHelpers loaded");
}
getEmail() {
console.log("====getEmail(): Entered ");
//debugger;
// Get the access token and create a Microsoft Graph client
let authenticator = new Authenticator();
// register Microsoft (Azure AD 2.0 Converged auth) endpoint
authenticator.endpoints.registerMicrosoftAuth("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", {
redirectUrl: "https://localhost:3000/index.html",
scope: "Mail.ReadWrite User.Read User.ReadBasic.All"
});
console.log("====getEmail(): Getting token");
let authObject = authenticator.tokens.get("Microsoft");
let accessToken = authObject.access_token;
if (accessToken !== null) {
console.log(`====getEmail(): Current cached token: ${accessToken}`);
this.callGraph(accessToken);
return;
} else {
// for the default Microsoft endpoint
//If the user, rejects the grant to the application then you will receive an error in the catch function.
authenticator
.authenticate(DefaultEndpoints.Microsoft)
.then(function(token) {
/* Microsoft Token */
console.log(`====getEmail(): Authenticated; auth token: ${token.access_token}`);
accessToken = token.access_token;
})
.catch(function(error) {
//debugger;
console.log("====getEmail(): authenticate error");
Utilities.log(error);
throw new Error("Failed to login using your Office 365 Account");
});
}
console.log(`====getEmail(): Current token: ${accessToken}`);
this.callGraph(accessToken);
}
callGraph(token) {
// Get the item's REST ID
let itemId = this.getItemRestId();
console.log(`====callGraph(): itemId ${itemId}`);
const client = Graph.Client.init({
authProvider: done => {
done(null, token); //first parameter takes an error if you can't get an access token
},
debugLogging: true
});
client
.api("me/messages/" + itemId)
.version("v1.0")
.get()
.then(function(item) {
//debugger;
console.log("Email " + item.Subject + " retrieved!!!");
})
.then(function() {
console.log("====callGraph(): complete");
//debugger;
})
.catch(err => {
//debugger;
//403 Forbidden! code: "ErrorAccessDenied", message: "Access is denied. Check credentials and try again."
//Also 401 InvalidAuthenticationToken: Access token validation failure.
console.log(`====callGraph(): error! ${err.statusCode}:'${err.code}': ${err.message}`);
});
}
getItemRestId() {
if (Office.context.mailbox.diagnostics.hostName === "OutlookIOS") {
// itemId is already REST-formatted
return Office.context.mailbox.item.itemId;
} else {
// Convert to an item ID for API v2.0
return Office.context.mailbox.convertToRestId(
Office.context.mailbox.item.itemId,
Office.MailboxEnums.RestVersion.v2_0
);
}
}
render() {
return (
<div>
<Button
id="getEmailButton"
className="ms-welcome__action ms-bgColor-red"
buttonType={ButtonType.primary}
onClick={this.getEmail}
>
Call Graph
</Button>
<div>
<h3> Access Token </h3>
<TextField id="accessToken" />
</div>
<div>
<h3>Graph API Call Response</h3>
<TextField id="graphResponse" />
</div>
</div>
);
}
}
I'm using AWS for my website. After 1 hour the token expires and the user pretty much can't do anything.
For now i'm trying to refresh the credentials like this:
function getTokens(session) {
return {
accessToken: session.getAccessToken().getJwtToken(),
idToken: session.getIdToken().getJwtToken(),
refreshToken: session.getRefreshToken().getToken()
};
};
function getCognitoIdentityCredentials(tokens) {
const loginInfo = {};
loginInfo[`cognito-idp.eu-central-1.amazonaws.com/eu-central-1_XXX`] = tokens.idToken;
const params = {
IdentityPoolId: AWSConfiguration.IdPoolId
Logins: loginInfo
};
return new AWS.CognitoIdentityCredentials(params);
};
if(AWS.config.credentials.needsRefresh()) {
clearInterval(messwerte_updaten);
cognitoUser.refreshSession(cognitoUser.signInUserSession.refreshToken, (err, session) => {
if (err) {
console.log(err);
}
else {
var tokens = getTokens(session);
AWS.config.credentials = getCognitoIdentityCredentials(tokens);
AWS.config.credentials.get(function (err) {
if (err) {
console.log(err);
}
else {
callLambda();
}
});
}
});
}
the thing is, after 1hour, the login token gets refreshed without a problem, but after 2hrs i can't refresh the login token anymore.
i also tried using AWS.config.credentials.get(), AWS.config.credentials.getCredentials() and AWS.config.credentials.refresh()
which doesn't work either.
The error messages i'm getting are:
Missing credentials in config
Invalid login token. Token expired: 1446742058 >= 1446727732
After almost 2 weeks i finally solved it.
You need the Refresh Token to receive a new Id Token. Once the Refreshed Token is acquired, update the AWS.config.credentials object with the new Id Token.
here is an example on how to set this up, runs smoothly!
refresh_token = session.getRefreshToken(); // you'll get session from calling cognitoUser.getSession()
if (AWS.config.credentials.needsRefresh()) {
cognitoUser.refreshSession(refresh_token, (err, session) => {
if(err) {
console.log(err);
}
else {
AWS.config.credentials.params.Logins['cognito-idp.<YOUR-REGION>.amazonaws.com/<YOUR_USER_POOL_ID>'] = session.getIdToken().getJwtToken();
AWS.config.credentials.refresh((err)=> {
if(err) {
console.log(err);
}
else{
console.log("TOKEN SUCCESSFULLY UPDATED");
}
});
}
});
}
Usually it's solved by intercepting http requests with additional logic.
function authenticationExpiryInterceptor() {
// check if token expired, if yes refresh
}
function authenticationHeadersInterceptor() {
// include headers, or no
}}
then with use of HttpService layer
return HttpService.get(url, params, opts) {
return authenticationExpiryInterceptor(...)
.then((...) => authenticationHeadersInterceptor(...))
.then((...) => makeRequest(...))
}
It could be solved by proxy as well http://2ality.com/2015/10/intercepting-method-calls.html
In relation to AWS:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html
You're interested in:
getPromise()
refreshPromise()
Here is how I implemented this:
First you need to authorize the user to the service and grant permissions:
Sample request:
Here is how I implemented this:
First you need to authorize the user to the service and grant permissions:
Sample request:
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token&
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic aSdxd892iujendek328uedj
grant_type=authorization_code&
client_id={your client_id}
code=AUTHORIZATION_CODE&
redirect_uri={your rediect uri}
This will return a Json something like:
HTTP/1.1 200 OK
Content-Type: application/json
{"access_token":"eyJz9sdfsdfsdfsd", "refresh_token":"dn43ud8uj32nk2je","id_token":"dmcxd329ujdmkemkd349r", "token_type":"Bearer", "expires_in":3600}
Now you need to get an access token depending on your scope:
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic aSdxd892iujendek328uedj
grant_type=client_credentials&
scope={resourceServerIdentifier1}/{scope1} {resourceServerIdentifier2}/{scope2}
Json would be:
HTTP/1.1 200 OK
Content-Type: application/json
{"access_token":"eyJz9sdfsdfsdfsd", "token_type":"Bearer", "expires_in":3600}
Now this access_token is only valid for 3600 secs, after which you need to exchange this to get a new access token. To do this,
To get new access token from refresh Token:
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token >
Content-Type='application/x-www-form-urlencoded'
Authorization=Basic aSdxd892iujendek328uedj
grant_type=refresh_token&
client_id={client_id}
refresh_token=REFRESH_TOKEN
Response:
HTTP/1.1 200 OK
Content-Type: application/json
{"access_token":"eyJz9sdfsdfsdfsd", "refresh_token":"dn43ud8uj32nk2je", "id_token":"dmcxd329ujdmkemkd349r","token_type":"Bearer", "expires_in":3600}
You get the picture right.
If you need more details go here.
This is how you can refresh access token using AWS Amplify library:
import Amplify, { Auth } from "aws-amplify";
Amplify.configure({
Auth: {
userPoolId: <USER_POOL_ID>,
userPoolWebClientId: <USER_POOL_WEB_CLIENT_ID>
}
});
try {
const currentUser = await Auth.currentAuthenticatedUser();
const currentSession = currentUser.signInUserSession;
currentUser.refreshSession(currentSession.refreshToken, (err, session) => {
// do something with the new session
});
} catch (e) {
// whatever
}
};
More discussion here: https://github.com/aws-amplify/amplify-js/issues/2560.
I am having trouble using the Parse Server JS SDK to edit and save a user.
I am signing in, logging in and retrieving the user just fine, I can call without exception user.set and add/edit any field I want, but when I try to save, even when using the masterKey, I get Error 206: Can t modify user <id>.
I also have tried to use save to direcly set the fields, same result.
A interesting thing is that in the DB, the User's Schema get updated with the new fields and types.
Here is my update function:
function login(user, callback) {
let username = user.email,
password = user.password;
Parse.User.logIn(username, password).then(
(user) => {
if(!user) {
callback('No user found');
} else {
callback(null, user);
}
},
(error) => {
callback(error.message, null);
}
);
}
function update(user, callback) {
login(user, (error, user) => {
if(error) {
callback('Can t find user');
} else {
console.log('save');
console.log('Session token: ' + user.getSessionToken());
console.log('Master key: ' + Parse.masterKey);
user.set('user', 'set');
user.save({key: 'test'}, {useMasterKey: true}).then(
(test) => {
console.log('OK - ' + test);
callback();
}, (err) => {
console.log('ERR - ' + require('util').inspect(err));
callback(error.message);
}
);
}
});
}
And a exemple of the error:
update
save
Session token: r:c29b35a48d144f146838638f6cbed091
Master key: <my master key>
ERR- ParseError { code: 206, message: 'cannot modify user NPubttVAYv' }
How can I save correctly my edited user?
I had the exact same problem when using Parse Server with migrated data from an existing app.
The app was created before March 2015 when the new Enhanced Sessions was introduced. The app was still using legacy session tokens and the migration to the new revocable sessions system was never made. Parse Server requires revocable sessions tokens and will fail when encountering legacy session tokens.
In the app settings panel, the Require revocable sessions setting was not enabled before the migration and users sessions were not migrated to the new system when switching to Parse Server. The result when trying to edit a user was a 400 Bad Request with the message cannot modify user xxxxx (Code: 206).
To fix the issue, I followed the Session Migration Tutorial provided by Parse which explain how to upgrade from legacy session tokens to revocable sessions. Multiple methods are described depending on your needs like enableRevocableSession() to enable these sessions on a mobile app, if you're only having a web app, you can enforce that any API requests with a legacy session token to return an invalid session token error, etc.
You should also check if you're handling invalid session token error correctly during the migration to prompt the user to login again and therefore obtain a new session token.
I had the same error and neither useMasterKey nor sessionToken worked for me either. :(
Here's my code:
console.log("### attempt 1 sessionToken: " + request.user.getSessionToken());
var p1 = plan.save();
var p2 = request.user.save(null, {sessionToken: request.user.getSessionToken()});
return Parse.Promise.when([p1, p2]).then(function(savedPlan) {
...
}
I see the matching session token in log output:
2016-08-21T00:19:03.318662+00:00 app[web.1]: ### attempt 1 sessionToken: r:506deaeecf8a0299c9a4678ccac47126
my user object has the correct ACL values:
"ACL":{"*":{"read":true},"PC7AuAVDLY":{"read":true,"write":true}}
I also see a bunch of beforeSave and afterSave logs with user being "undefined". not sure whether that's related.
beforeSave triggered for _User for user undefined:
I'm running latest parser-server version 2.2.18 on Heroku (tried it on AWS and results are the same)
function login(logInfo, callback) {
let username = logInfo.email,
password = logInfo.password;
Parse.User.logIn(username, password).then(
(user) => {
if(!user) {
callback('No user found');
} else {
callback(null, user);
}
},
(error) => {
callback(error.message, null);
}
);
}
function update(userInfo, data, callback) {
login(userInfo, (error, user) => {
if(error) {
callback('Can t find user');
} else {
getUpdatedData(user.get('data'), data, (error, updateData) => {
if(error) {
callback(error);
} else {
user.save({data: updateData}, /*{useMasterKey: true}*/ {sessionToken: user.get("sessionToken")}).then(
(test) => {
callback();
}, (err) => {
callback(error.message);
}
);
}
});
}
});
}
For some reason, retrying to use sessionToken worked.
This is not how asynchronous functions work in JavaScript. When createUser returns, the user has not yet been created. Calling user.save kicks off the save process, but it isn't finished until the success or error callback has been executed. You should have createUser take another callback as an argument, and call it from the user.save success callback.
Also, you can't create a user with save. You need to use Parse.User.signUp.
The function returns long before success or error is called.