Error on refreshing auth token in Firebase iOS - ios

I'm trying to refresh my auth token in Firebase using swift as follows
let currentUser = Auth.auth().currentUser
currentUser?.getIDTokenForcingRefresh(true) { idToken, error in
if error != nil {
return;
}
self.userDataManager.fetchUser()
}
It's hitting the error return statement with,
message = "Requests to this API securetoken.googleapis.com method google.identity.securetoken.v1.SecureToken.GrantToken are blocked.";
status = "PERMISSION_DENIED";
I search around the docs, But couldn't find a proper solution for this. Please help with this.

I had the same error but with the Web APIs. Solved it by
Going to https://console.developers.google.com/apis/credentials,
Clicking on the API key
Enabling the "Token Service API", along with "Identity Toolkit API"

Related

AWS Amplify iOS SDK : FederatedSignIn Failed to retrieve authorization token on Amplify.API.post

I've been working with the Amplify SDK to get federatedSignIn working with my iOS app with "Sign in with Apple" and Cognito to eventually make calls to API Gateway / Lambda functions.
TL;DR : My access token does not appear to be "automatically included in outbound requests" to my API as per the last paragraph of this section of the docs : Cognito User pool authorization
I have successfully authenticated using the tutorial found here Authentication Getting Started and other various Youtube videos on the Amazon Web Services channel.
Upon successful sign in through Apple I'm given an ASAuthorizationAppleIDCredential object. This contains the user field (token) which I pass to the Amplify.Auth class using the following Swift code :
func signIn (with userId: String)
{
guard
let plugin = try? Amplify.Auth.getPlugin(for: AWSCognitoAuthPlugin().key),
let authPlugin = plugin as? AWSCognitoAuthPlugin,
case .awsMobileClient (let client) = authPlugin.getEscapeHatch()
else
{
return
}
client.federatedSignIn(providerName: AuthProvider.signInWithApple.rawValue, token: userId) { (state, error) in
if let unwrappedError = error
{
print (unwrappedError)
}
else if let unwrappedState = state
{
print ("Successful federated sign in:", unwrappedState)
}
}
}
All appears to be successful and to double check I use the following bit of code to ensure I'm authorized :
func getCredentialsState (for userId:String)
{
let provider = ASAuthorizationAppleIDProvider()
provider.getCredentialState(forUserID: userId) { (credentialsState, error) in
if let unwrappedError = error
{
print (unwrappedError)
}
switch credentialsState
{
case .authorized:
print ("User Authorized")
case .notFound, .revoked:
print ("User Unauthenticated")
case .transferred:
print ("User Needs Transfer")
#unknown default:
print ("User Handle new use cases")
}
}
}
In the console I see "User Authorized" so everything appears to be working well.
However when I then go to make a call to Amplify.API.post I get the following error:
[Amplify] AWSMobileClient Event listener - signedOutFederatedTokensInvalid
Failed APIError: Failed to retrieve authorization token.
Caused by:
AuthError: Session expired could not fetch cognito tokens
Recovery suggestion: Invoke Auth.signIn to re-authenticate the user
My function for doing the POST is as follows :
func postTest ()
{
let message = #"{'message": "my Test"}"#
let request = RESTRequest (path: "/test", body: message.data(using: .utf8))
Amplify.API.post (request:request)
{
result in switch result
{
case .success(let data):
let str = String (decoding: data, as: UTF8.self)
print ("Success \(str)")
case .failure(let apiError):
print ("Failed", apiError)
}
}
}`
I then went into the API Gateway UI and changed the generated Method Request on my resource from AWS IAM to my Cognito User Pool Authorizer thinking this was the issue. I also changed the awsAPIPlugin authorizationType to "AMAZON_COGNITO_USER_POOLS" in my amplifyconfiguration.json file. This unfortunately did not have any affect.
I've seen posts such as this issue User is not created in Cognito User pool for users logging in with Google federated login #1937 where people discuss the problem of having to to use a web ui to bring up the social sign in. I understand that Apple will reject your app sometimes for this. Therefore this is not a solution.
I then found this post which seems to resolve the issue however this appears to use the old version of the SDK? Get JWT Token using federatedSignIn #1276
I'm not great with Swift (I'm still an Objective C expert, but am slowly learning Swift) so I'm uncertain which path to go here and whether this is actually a solution? It does seem to be quite more complicated than the function I have that does my POST? The RESTRequest does seem to be a simple and easy solution but I'm uncertain how to pass it the Authorization token (or even how to get the token if it is needed here).
However, everything I've read about the SDK is that the authorization should be handled automatically in the background according the docs in my first link above. Specifically pointed out, again, here : Cognito User pool authorization. The last paragraph here states 👍
With this configuration, your access token will automatically be included in outbound requests to your API, as an Authorization header.
Therefore, what am I missing here as this does not appear to automatically include my access token to my outbound requests to my API?

How to send Dialogflow an access token from Swift using ApiAi Pod

While following this tutorial: https://medium.com/#pallavtrivedi03/integrating-dialogflow-as-a-chat-bot-in-an-ios-app-e66a4c7f2723
I was unable to find out how to interact with dialogflow intents that require authentication via the swift app. Once the dialogflow path reaches a point where it needs authentication, the request is not met with a response.
I have successfully sent requests and received responses from dialogflow using the following:
func performQuery(senderId:String,name:String,text:String)
{
let request = ApiAI.shared().textRequest()
if text != "" {
request?.query = text
} else {
return
}
//print("request: ")
request?.setMappedCompletionBlockSuccess({ (request, response) in
let response = response as! AIResponse
print(response.result.parameters)
//print(response.result.action)
I am not an experienced swift user so it could be that I am missing something simple, however, I am unable to find any documentation on the topic.
Any information on ways to interact with dialogflow using oauth2 would be greatly appreciated.

Insufficient authentication scopes error for Google Sheet API for iOS

I'm trying to fetch a Google Sheet with the Google Sheets API for iOS. I've successfully added the user authentication since it's no longer asking for an API key, but I'm now getting a 403 error for:
Request had insufficient authentication scopes*.
I've added the following scopes in the Google Developers Console.
/auth/drive
/auth/spreadsheets
And here's the code I'm using to make and execute the query.
let potentialShowSheetID = "1n4wvD2vSSiAnG_pnD9rWR6dNCSnZz0pAGAiSYRaJCKs"
let service = GTLRSheetsService()
private let scopes = [kGTLRAuthScopeSheetsSpreadsheets] // This was specified in
// another Stack Overflow question, but I'm not sure how it would be used
// and it doesn't seem to help.
override func viewDidLoad() {
super.viewDidLoad()
service.authorizer = GIDSignIn.sharedInstance().currentUser.authentication.fetcherAuthorizer()
let query = GTLRSheetsQuery_SpreadsheetsGet.query(withSpreadsheetId: potentialShowSheetID)
service.executeQuery(query) { (ticket, data, error) in
print("GTLRService ticket: \(ticket)")
if error != nil {
print("GTLRService potential show query error: \(error!)")
}
else {
print("data: \(data ?? "unknown data")")
}
}
}
Is there a way to specify the scope in the query with the Google Sheets API for iOS? I looked through the framework pretty well and it doesn't ever seem to take that as a parameter. Maybe I'm missing something else.
UPDATE: I checked the granted scopes for the user and it doesn't include the Drive or Sheets API.
print("Scopes:", GIDSignIn.sharedInstance()?.currentUser.grantedScopes ?? "unknown scopes")
// Prints -> Scopes: [https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/userinfo.email]
How can I specify the scopes to grant access to during authentication?
After some digging around the Google Sign In API headers, I found I just had to specify the scopes with this:
GIDSignIn.sharedInstance()?.scopes = [kGTLRAuthScopeSheetsSpreadsheets, kGTLRAuthScopeCalendar]
...before signing in with GIDSignInButton.

AWS SDK swift com.amazonaws.AWSSNSErrorDomain Code=0 "(null)"

I'm trying to use the AWS SDK to create an endpoint on an application so that I can send push notifications. The push notifications go through when I manually enter the details on the AWS console but I'm trying to register the device from inside the app so that new users can be signed up.
Following the steps on http://docs.aws.amazon.com/mobile/sdkforios/developerguide/setup.html I have created the credentials for the app in the AppDelegate and use these credentials in another class.
The code I'm using to try and access the AWS SNS is :
func subscribeEndpoint(json: JSON)
{
let sns = AWSSNS.defaultSNS()
let request = AWSSNSCreatePlatformEndpointInput()
let user_id = json["id"].string!
request.token = "XXXXX"
request.customUserData = user_id
print("token : \(token) user : \(user_id)")
request.platformApplicationArn = "XXXX"
sns.createPlatformEndpoint(request).continueWithBlock({ (task: AWSTask!) -> AnyObject! in
if task.error != nil {
print("Error dis: \(task.error!)")
} else {
let createEndpointResponse = task.result as! AWSSNSCreateEndpointResponse
print("endpointArn: \(createEndpointResponse.endpointArn)")
}
return nil
})
}
I have tested using the device token generated by the device when registering for notifications (this value works when inputting on the AWS SNS console). The user_id has also been tested and isn't null.
The error I keep getting is
Error dis: Error Domain=com.amazonaws.AWSSNSErrorDomain Code=0 "(null)"
Not really sure what the cause of the problem is but if anyone could help me it would be greatly appreciated. Thanks
This is most likely an authorization error. Are you setting the default service configuration correctly?
When you use AWSSNS.defaultSNS() it loads the configuration from the default configuration object. The credential provider used for the default configuration should assume a role which has permissions to call createPlatformEndpoint from the client.
You can verify it from the IAM console if the role that is assumed has enough permissions.
Thanks,
Rohan

Trying Login with Plaid APi

When i Login with plaid Api in live credential, it shows this type of error.
{
code = 1106;
message = "bad public_token";
resolve = "This public_token is corrupt or does not exist in our database. See https://plaid.com/docs/link for docs.";
}
so Any idea about that? Help me.

Resources