I am trying to send push notifications (iOS, Android, Web) to specific users when certain events happen in my app.
I am using the firebase_admin python plugin with Django, working properly for authentication and verifying jwt, but it is giving me this error when trying to send a Message/Notification from Django:
firebase_admin.exceptions.InvalidArgumentError: The registration token is not a valid FCM registration token
I am getting the token directly from my Flutter instance and sending it in the request body from Flutter to Django.
My method for getting the token from Flutter:
await FirebaseMessaging.instance.getToken().then((token) async {
fcm_token = token!;
}).catchError((e) {
print(e);
});
My python code that sends notification:
registration_token = self.context['request'].data["token"],
# See documentation on defining a message payload.
message = Message(
notification=Notification(
title='New Product Added',
body='A new product called ' + validated_data['name'] + ' has been added to your account.',
),
token=str(registration_token)
)
# Send a message to the device corresponding to the provided
# registration token.
response = send(message)
I have verified that the token being passed to Django is correct, by comparing it to what I am getting from Flutter
The problem was that registration_token was a tuple generated by Django, I just indexed into the first item in the tuple and the FCM error went away.
Related
I am building an application. The client is built with Next.js and the backend with Django and Django REST framework.
In this application, I would like to have social login.
So far, my situation is this.
I have set up the OAuth on the Google dashboard
On the client, I am using next-auth - The client is successfully calling Google and getting an access token from there.
On the client, the callback that runs after getting the access token from Google makes a call my Django API.
I have set up the backend with dj_rest_auth - My settings are almost identical to the ones described here.
Once the client callback runs and calls my Django API with the access token from Google, I successfully get on the client an access token and a refresh token.
If it is a new user loggin in the first time, a new user is created in Djangos DB
const response = await fetch(`${djangoAPIurl}/api/social/login/google/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
access_token: accessToken,
id_token: idToken
})
});
const data = await response.json();
const { access_token, refresh_token } = data;
Both access_token and refresh_token are defined and appear to be valid tokens.
So far, everything happens as expected. My issue appears after this point.
In my api, I have another view defined.
#api_view(['GET'])
#authentication_classes([SessionAuthentication, BasicAuthentication, TokenAuthentication])
#permission_classes([IsAuthenticated])
def test_view(request):
current_user = request.user
print('current_user.auth: ', current_user.is_authenticated)
response = JsonResponse({"received": True})
return response
From my client, I am attempting to call this view in the following way.
const response = await fetch(`${djangoAPIurl}/api/test/test_view/`, {
headers: new Headers({
Authorization: `Bearer ${session.accessToken}`
})
});
The header is constructed correctly, with session.accessToken being the value I got from the api/social/login/google/ call and the request is routed correctly, however, it fails with Forbidden 403 because the user is not authenticated. I have removed the authentication and permission decrators and the request ends up being processed by the view, and there, upon inspection of the user, it is an Anonymous user. I have also tried changing Bearer to Token, to no avail.
Do you have any advice what I might be doing wrong or missing? Have I completely missunderstood how to use the token I get back from api/social/login/google/? All advice is much appreicated!
I think this is because your secret for hashing JWTS on the client side and server side is not same. Next-Auth automatically creates a secret key for hashing jwt's and dj_rest_auth does the same, unless you explicitly tell them both to use the same secret for hashing jwts. I'm a bit late to answer this, but Hope this will help future people😁😁.
I am getting the following error
Whoa there!
The request token for this page is invalid. It may have already been used, or expired because it is too old. Please go back to the site or application that sent you here and try again; it was probably just a mistake
1) The following method in which we are calling the twitter credentials to your Api
2)The callback function is static
3) i am using Oauth 1 and using google cloud for hosting
4)I have already cleared the cache 2 times still no use
.def _twitter(self):
# Get the access token supplied
oauth_token = self.test_credentials.get('oauth_token')
oauth_token_secret = self.test_credentials.get('oauth_token_secret')
if not oauth_token or not oauth_token_secret:
raise AuthenticationException('Invalid request format.', 400)
auth = tweepy.OAuthHandler(current_app.config['TWITTER_CONSUMER_KEY'], current_app.config['TWITTER_CONSUMER_SECRET'])
auth.set_access_token(oauth_token, oauth_token_secret)
api = tweepy.API(auth)
user = api.verify_credentials()
if not user:
raise AuthenticationException('Unable to verify credentials with remote server.', 500)
# Save the user
auth_string = self._auth_string(unicode(user.id_str))
stored_user = User.query(User.auth_ids == auth_string).get()
if not stored_user:
return User(name=user.name)
if stored_user and not stored_user.name:
stored_user.name = user.name
stored_user.put()
return stored_user
I forgot to add my callback function in the twitter api callbacks (these resolved my error)
I getting back into Python and wanted to use the pyfoursquare package to access the Foursquare API. I'm trying to get information about venues using the venues method in the API class. I'm primarily trying to find out whether a venue page is verified with Foursquare or not. When I provide my client id, client secret, and venue id I keep getting back an error that states "Authentication required", which doesn't makes sense because I'm providing that information. Any help would be great. Thank you.
import pyfoursquare as foursquare
client_id = ""
client_secret = ""
callback = ""
auth = foursquare.OAuthHandler(client_id, client_secret, callback)
api = foursquare.API(auth)
result = api.venues("4e011a3e62843b639cfa9449")
print result[0].name
Let me know if you would like to see the error message. Thanks again.
I believe you are skipping the step of grabbing your OAuth2 access token, so you're not technically authenticated.
Have a look at the following instructions, under "How to Use It":
https://github.com/marcelcaraciolo/foursquare
The lines that might be useful to you are:
#First Redirect the user who wish to authenticate to.
#It will be create the authorization url for your app
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
#If the user accepts, it will be redirected back
#to your registered REDIRECT_URI.
#It will give you a code as
#https://YOUR_REGISTERED_REDIRECT_URI/?code=CODE
code = raw_input('The code: ').strip()
#Now your server will make a request for
#the access token. You can save this
#for future access for your app for this user
access_token = auth.get_access_token(code)
print 'Your access token is ' + access_token
I am creating web service using silex micro framework. This is first time i am using it and I dont have prior knowledge on symfony. I could be able to understand how silex works and how to write controller providers , service providers etc ..
I couldnt work out authentication for my webservice.
I want to use JWT authentication and I found this cnam/security-jwt-service-provider extending firebase/php-jwt.
I set it up right and I get this output when I access protected resource
{"message":"A Token was not found in the TokenStorage."}
which is correct.
Question: I want to post the username , password to application and get token back. ( username=admin , password=foo )
I am using postman chrome extension ( also used Advanced rest client ) to post values to url ( http://silex.dev/api/login)
Post data I am sending
Key=> username Value=> admin
Key=> password Value=> foo
I also tried
Key=> _username Value=> admin
Key=> _password Value=> foo
Aldo tried key vaule pairs in basic auth headers.
response I get id
{
"success": false,
"error": "Invalid credentials"
}
When I debug the Application I see no post data at all.
$vars = json_decode($request->getContent(), true);
I get null $var.
PS: I know I will get a valid token back if I get these values posted correctly because I edited values from empty to correct values in breakpoint.
Apparently I should send data in json format and should set content-type appication/json
eg:
{
"_username":"admin",
"_password":"foo"
}
and response will something be like
{
success: true
token: "eyJ0eXAiOisKV1diLCJfbGgiOhJIjzI1NiJ9.eyJuYW1lIjoiYWRtaW4iLCJleHAiOjE0Mzk5MDUxMjh9.DMdXAv2Ay16iI1UQbHZABLCU_gsD_j9-gEU2M2L2MFQ"
}
I'm trying to retrieve embedded tweets using statuses/oembed , the url sent to the api is https://api.twitter.com/1.1/statuses/oembed/507185938620219395.json
but i noticed in the documentation the sent url should be
https://api.twitter.com/1.1/statuses/oembed.json?id=507185938620219395
i'm already using search/tweets smoothly, the problem is only with oembed.
Below is a sample of what i'm doing
from twitter import *
class TwitterCrawler(object):
# Authenticate twitter API
# Access token, Access token secret, Consumer key, Consumer secret
def __init__(self):
self.t = Twitter(
auth=OAuth(self.accessToken,
self.accessTokenSecret,
self.consumerKey,
self.consumerSecret)
)
def getEmbeddedTweet(self):
result =self.t.statuses.oembed(id="507185938620219395")
return result
the error returned is:
TwitterHTTPError
Twitter sent status 404 for URL: 1.1/statuses/oembed/567386147631144960.json using parameters:...details: b'{"errors":[{"message":"Sorry, that page does not exist","code":34}]}'
The correct endpoint for this is publish.twitter.com/oembed