Is it possible change username in Amazon Cognito with iOS SDK? - ios

as written in the title is it possible change username of a Amazon Cognito user? I can't find anything in documentation

It is possible to update the preferred_username of a Cognito User using the iOS SDK, using the updateAttributes API call. However, kindly note that you would not be able to modify the username of a user. Quoting the official AWS documentation,
The username value is a separate attribute and not the same as the
name attribute. A username is always required to register a user, and
it cannot be changed after a user is created.
But, the preferred_username value can indeed be changed, and a sample code to change the preferred username using the iOS SDK, as per the official documentation is stated as follows:
AWSCognitoIdentityUserAttributeType * attribute = [AWSCognitoIdentityUserAttributeType new];
attribute.name = #"preferred_username";
attribute.value = #"John User";
[[user updateAttributes:#[attribute]] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserUpdateAttributesResponse *> * _Nonnull task) {
//success
return nil;
}];
I would also like to state that the AWS API documentations for the iOS SDK are rather minimal, and I would recommend developers to go through the SDK source code whenever in doubt.

Related

Cannot set PubNub auth key Swift iOS

I have a webapp and the iOS app built in Swift. The thing is I don't know Swift and I'm trying to modify the iOS app in order to add the authorization key to the PubNub client before subscribing/publishing to channels.
Link to PubNub docs
PRE:
Access Manager is enabled
my_auth_key is hardcoded and already enabled form the server for the corresponding channel I want to subscribe.
Here is the code
What's the correct way to set the auth key?
Thanks in advance
Polak, mentioned docs code snippet refer to previously created instance to get it's pre-configured PNConfiguration instance and change required field. This practice can be used in case if you need change something at run-time.
If you have data for authKey at the moment of client initialization, you can set it:
var pubnubClient: PubNub = {
let configuration = PNConfiguration(publishKey: UCConstants.PubNub.publishKey, subscribeKey: UCConstants.PubNub.subscribeKey)
configuration.authKey = "my_auth_key"
return PubNub.clientWithConfiguration(configuration)
}()
Also, I've tried exact your code and don't have any issues with setting of authKey, because I can see it with subscribe request.
If you still will have troubles with PAM and auth key usage, please contact us on support#pubnub.com
Looks like you can:
let configuration = PNConfiguration(
authKey: "super_secret",
publishKey: UCConstants.PubNub.publishKey,
subscribeKey: UCConstants.PubNub.subscribeKey
)
Based on the Obj-C code: https://github.com/pubnub/objective-c/blob/8c1f0876b5b34176f33681d22844e8d763019635/PubNub/Data/PNConfiguration.m#L174-L181

OVER_QUERY_LIMIT in simple SPGooglePlacesAutocompleteQuery request

I'm trying to create simple autocomplete UI widget:
self.autocompleteQuery = [[SPGooglePlacesAutocompleteQuery alloc] initWithApiKey:[GlobalConfig sharedInstance].kGoogleBrowserKey];
self.autocompleteQuery.language = kFFAutocompleteQueryLanguage;
self.autocompleteQuery.types = SPPlaceTypeAddress;
self.autocompleteQuery.location = [FFAppDataHelper coordinatesForMoscow];
self.autocompleteQuery.radius = [GlobalConfig sharedInstance].kMoscowRadius;
self.autocompleteQuery.countryCode = #"RU";
Then I want to get all values for input string from UITextField on 'valueChanged' event:
self.autocompleteQuery.input = [streetName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
[self.autocompleteQuery fetchPlaces:^(NSArray *places, NSError *error) {
[self loaderStopAnimating];
if (places) {
//do some stuff
} else {
FFError *detectedError = [FFError errorWithNSError:error];
[self showErrorMessage:[detectedError errorMessage]];
}
}];
So when I type 'k' I get response with streets and if I add next char to my text field I receive OVER_QUERY_LIMIT every time. I've tried it on simulator and devices with the same result. And it starts working again after 10-20 sec. I don't use loops or smth similar, I just want to get suggestions for input string in real time, but I can't get it because of error. What should I do to avoid it?
For the web service request, use a key.
Follow this :https://developers.google.com/maps/documentation/geocoding/start#api_key
Doc says:
Note: Maps for Work users must include client and signature parameters with their requests instead of a key.
All Geocoding API applications should use an API key. Including a key in your request:
Allows you to monitor your application's API usage in the Google Developers Console. Enables per-key instead of per-IP-address quota limits. Ensures that Google can contact you about your application if necessary. The Geocoding API uses an API key to identify your application. API keys are managed through the Google APIs console. To create your key:
Visit the APIs console at Google Developers Console and log in with your Google Account. Click the Services link from the left-hand menu in the APIs Console, then activate the Geocoding API service. Once the service has been activated, your API key is available from the API > Access page, in the Simple API Access section. Geocoding API applications use the Key for server apps. To specify a key in your request, include it as the value of a key parameter.
Note: By default, a key can be used from any server. We strongly recommend that you restrict the use of your key by IP address to servers that you administer. You can specify which IP addresses are allowed to use your API key by clicking the Edit allowed referers... link in the API console.
Note: HTTPS is enforced for requests that include an API key.

How to force Google OAuth popup in Firebase when user already authenticated previously?

Whenever a user has previously authenticated with Google, it automatically defaults to logging them in with THAT account on subsequent attempts. I want to eliminate this and force the popup/redirect so that a user with multiple google accounts can choose which one to use. How?
Background:
The automatic logging in feature is proving problematic for me as I have a whitelisted set of e-mails for users allowed to use my app. If a Google user chooses the wrong account when first logging in, they can't go back and choose the one associated to their whitelisted e-mail.
Just as #nvnagr said, you can do this with the following code:
var provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({
'prompt': 'select_account'
});
But I think you need to update the firebase version to 3.6.0 something.
Google supports a parameter in authentication url to deal with this issue.
If you add prompt=select_account in your request to Google authentication, it'll force the user to do an account selection. See the details and other values of prompt.
https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters
I'm not sure if there is an easy way to add this parameter through firebase api.
When you're calling the oAuth function, you can pass a third options parameter to make the authentication last for the session only. This should solve your problem. Docs
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.authWithOAuthPopup("google", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
}, {
remember: 'sessionOnly'
});

Evernote iOS SDK - How do I authenticate with a token?

I am using Evernote SDK for iOS and I am saving the authentication token when the user has authorized access.
Once the user installs my application on a different device, I want to use that token to reauthenticate automatically, but it looks like SDK doesn't support that. Is there a way to do that?
I had the same issue last week, and their SDK indeed doesn't support it out-of-the-box, but after some research I found a solution that works perfectly. This solution mimics a valid authentication flow.
A little background:
When the ENSession class initializes, it retrieves the credentials that are saved on the keychain (unless [[ENSession sharedSession] unauthenticate] was called earlier). The problem is that the keychain is empty when using a different device, so our goal is to add a valid ENCredentials instance to the ENCredentialStore.
Solution:
Add the following imports to your code: ENCredentials.h and ENCredentialStore.h. We will need them later.
Initialize the ENSession like you already do, using setSharedSessionConsumerKey:(NSString *)key consumerSecret:(NSString *)secret optionalHost:(NSString *)host.
In order to create a valid ENCredentials object, we need to provide the following objects:
NSString * host
NSString * edamUserId
NSString * noteStoreUrl
NSString * webApiUrlPrefix
NSString * authenticationToken
NSDate * expirationDate
The host is always www.evernote.com (as defined in ENSession under ENSessionBootstrapServerBaseURLStringUS).
edamUserId is the user id you received when you got the original token. Same for the expirationDate. If you are not sure how to get them then you should use [[ENSession sharedSession].userStore getUserWithSuccess:^(EDAMUser *user) once authenticated.
So the only objects that are actually missing are noteStoreUrl and webApiUrlPrefix. Their format is always:
noteStoreUrl: https://www.evernote.com/shard/edam_shard/notestore
webApiUrlPrefix: https://www.evernote.com/shard/edam_shard/
Luckily, your token already contains edam_shared (value of S=, see this):
#"S=s161:U=5ce3f20:E=1561182201b:C=24eb9d000f8:P=285:A=app:V=2:H=e8ebf56eac26aaacdef2f3caed0bc309"
If you extract s161 and put it in the URLs above it will work (I am sure you know how to extract that, but let me know if you're having problems).
Now we are ready to authenticate using the token. First, expose the necessary functions from ENSession using a category:
#interface ENSession(Authentication)
- (void)startup;
- (void)addCredentials:(ENCredentials *)credentials;
#end
And authenticate using the token:
ENCredentials *credentials = [[ENCredentials alloc] initWithHost:ENSessionBootstrapServerBaseURLStringUS edamUserId:userId noteStoreUrl:noteStoreUrl webApiUrlPrefix:webApiUrlPrefix authenticationToken:token expirationDate:expirationDate];
[[ENSession sharedSession] addCredentials:credentials];
[[ENSession sharedSession] startup];
The last line is important in order to refresh the ENSession and retrieve the new stored credentials.
Now you are authenticated and ready to query the SDK. Good luck.

How do I use an iOS app's bundle identifier to 'authorize' upload to Google Cloud Storage?

Our service is using Google App Engine as our backend, and we're now implementing an upload-function for images etc.
Using the answers from several different questions here on stack, I have made it working, but not completely as I want. We are not using the built-in OAuth etc, and for now we want the storage to be public, but not entirely public. We would like to limit it to users of our own app (I.E no authentication). In the Cloud-console we can create an API-key for iOS. When doing this, we copy the API-key to the app, and pass it along with every upload-request. This is currently working, when the bucket-permission is set to allUsers - WRITE
However, inside the API-key, we can supply our app's own Bundle Identifier, so that, supposedly, only requests from our app is allowed. (App Store ID/URL is also permitted, apparently).
Adding this bundle-id does nothing as long as the bucket has the permission allUsers - WRITE. If I change the bundle-id to not match the actual bundle-id, it still works. So which permission should it use for the bucket to make the bundle-id in the API-key apply? And what should be sent along in the upload-code on iOS (acl?)?.
If I remove the allUsers-permission, and use something else, I get this error when trying to upload:
{message:"There is a per-IP or per-Referer restriction configured
on your API key and the request does not match these
restrictions. Please use the Google Developers Console
to update your API key configuration if request from this
IP or referer should be allowed." data:[1] code:403}}
This is how I'm using it right now (though I have tried several different things, all picked up from different questions/answers):
GTLServiceStorage *serv = [[GTLServiceStorage alloc] init];
serv.additionalHTTPHeaders = [NSDictionary dictionaryWithObjectsAndKeys:
#"[my project id]", #"x-goog-project-id",
#"application/json-rpc", #"Content-Type",
#"application/json-rpc", #"Accept", nil];
serv.APIKey = #"[my iOS API key, gotten from console, (linked to bundle-id?)]";
serv.retryEnabled = YES;
GTLStorageBucket *bucket = [[GTLStorageBucket alloc] init];
bucket.name = #"[my bucket]";
GTLUploadParameters *params = [GTLUploadParameters uploadParametersWithFileHandle:fileHandle MIMEType:#"image/jpeg"];
GTLStorageObject *storageObject = [[GTLStorageObject alloc] init];
storageObject.name = #"testFile.jpg";
//I have no idea what I'm doing with the following stuff, but I've tried several things:
GTLStorageObjectAccessControl *objAccessControl
= [GTLStorageObjectAccessControl new];
//This is working
objAccessControl.entity = #"allUsers";
objAccessControl.email = #"[my app-id]#project.gserviceaccount.com";
objAccessControl.role = #"OWNER";
//If I try this instead, it is not working.
//objAccessControl.domain = #"[my app-id].apps.googleusercontent.com";
//objAccessControl.role = #"WRITER";
//Probably because it's bullshit, I have no idea what I'm doing.
storageObject.acl = #[objAccessControl];
[...] //Bucket and upload and stuff. It seems like it's the ACL-thing above that's not working..
It seems like I have to connect the permissions on the bucket to the iOS API Key somehow, but I don't know if it's even possible.
What I want: All users to be able to use the cloud, given that they are requesting it from my iOS app.
As this question never got an answer I'll add one here, based on the information currently in the post.
The reason you got the error 'There is a per-IP or per-Referer restriction..' when calling the GCS API with the iOS API Key is simply because the GCS API doesn't work with API Keys for private data, only Bearer Tokens (ie. using OAuth). There isn't anything you could have done to make the API Key work with the GCS API directly with private data. The reason it worked when you had 'allUsers - WRITE' set as the ACL is simply because that ACL allows public access.
To access the private data without user intervention requires a Service Account, however the Google APIs Objective-C Client only supports OAuth2 Client IDs. The rationale being that Service Accounts are intended for server-side authentication only. Using a Service Account in a client would involve distributing the private key along with the app, which could easily be compromised. For reference, here's a sample of how you might authorize the GCS service using OAuth:
NSString *keychainItemName = #"My App";
NSString *clientID = <your-client-id>;
NSString *clientSecret = <your-client-secret>;
// How to check for existing credentials in the keychain
GTMOAuth2Authentication *auth;
auth = [GTMOAuth2WindowController authForGoogleFromKeychainForName:kKeychainItemName
clientID:clientID
clientSecret:clientSecret];
...
// How to set up a window controller for sign-in
NSBundle *frameworkBundle = [NSBundle bundleForClass:[GTMOAuth2WindowController class]];
GTMOAuth2WindowController *windowController;
windowController = [GTMOAuth2WindowController controllerWithScope:kGTLAuthScopeStorageDevstorageFullControl
clientID:clientID
clientSecret:clientSecret
keychainItemName:kKeychainItemName
resourceBundle:frameworkBundle];
[windowController signInSheetModalForWindow:[self window]
completionHandler:^(GTMOAuth2Authentication *auth,
NSError *error) {
if (error == nil) {
self.storageService.authorizer = auth;
}
}];
...
// Initialize service with auth
GTLServiceStorage *serv = [[GTLServiceStorage alloc] init];
serv.authorizer = auth;
All of this was taken from the storage sample on the google-api-objectivec-client GitHub page, so you can refer to it for a complete example with context.
This still leaves the question of how to implement access to GCS from iOS without user authorization. The short answer to this is that the iOS Key can be used to restrict access to your own backend API hosted on Google Cloud Endpoints, and that backend application can authorize against GCS using a Service Account (usually the Application Default Service Account). The Cloud Storage Client Library Examples page has samples using the default credentials for different languages.
Further details on how to implement an Endpoints API for this purpose are probably getting outside of the scope of this question, but this should serve as a good starting point.

Resources