I am currently trying to configure a REST API I added using AWS Amplify. I have already configured user authentication in which users can sign-up and sign-in by following the steps outlined in the authentication docs. I then added a REST API using the api steps.
At the moment, I am just trying to retrieve a list of items from DynamoDB. The api is successful when I test it on the aws console, however, when I make the call from my android api, it returns the following error:
{"message":"Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=[a long string of characters]
I understand that amplify automatically sets the API to be restricted using AWS_IAM, which I think is why the above message is returned. I am trying to get it to authenticate using the user pools I setup before with the authentication steps. The code in my android that app that makes the call to the API is as follows:
RestOptions options = new RestOptions("/models");
Amplify.API.get("modelsapi", options, new ResultListener<RestResponse>() {
#Override
public void onResult(RestResponse restResponse) {
Log.i(TAG, restResponse.toString());
Log.i(TAG, restResponse.getData().asString());
}
#Override
public void onError(Throwable throwable) {
Log.e(TAG, throwable.toString());
}
});
Do I need to setup a Authorizer on AWS api console? And if so, How do I pass the authorization header with the user token. I have a seen a few responses from people using react native but not with android: AWS-amplify Including the cognito Authorization header in the request
The function which the Api invokes is as follows if needed:
app.get(path, function(req, res) {
let queryParams = {
TableName: tableName
}
dynamodb.scan(queryParams, (err, data) => {
if (err) {
res.statusCode = 500;
res.json({error: 'Could not load items: ' + err});
} else {
res.json(data.Items);
}
});
});
Any points/help would be greatly appreciated! Thanks!
Have figured it out. Even though Amplify is meant to take the credentials automatically when making an API call, it seemed to throw up the unauthorized error anyway. When I tested using the console it worked fine. I had to manually add the authorization header to the Rest options:
RestOptions options = RestOptions.builder()
.addPath("models")
.addHeader("Authorization", token.getTokenString())
.build();
Related
I've been going through the AWS Amplify docs and tutorials for how to use Amplify and Cognito identity pools together with UNauthenticated users. The example given by the Amplify docs is:
Amplify.Auth.fetchAuthSession(
result -> {
AWSCognitoAuthSession cognitoAuthSession = (AWSCognitoAuthSession) result;
switch(cognitoAuthSession.getIdentityId().getType()) {
case SUCCESS:
Log.i("AuthQuickStart", "IdentityId: " + cognitoAuthSession.getIdentityId().getValue());
break;
case FAILURE:
Log.i("AuthQuickStart", "IdentityId not present because: " + cognitoAuthSession.getIdentityId().getError().toString());
}
},
error -> Log.e("AuthQuickStart", error.toString())
);
But in practice when I use this code - I get an error printed out in LogCat:
AuthQuickStart: FAILURE IdentityId not present because: AmplifyException {message=You are currently signed out., cause=null, recoverySuggestion=Please sign in and reattempt the operation.}
Note: I did configure AWS Cognito to support Unauthenticaed users!
I've also looked everywhere for the Amplify Android API doc to see what other APIs are supported - couldn't find any Android API docs.
And looking into the AWS Amplify.Auth methods i could not find ANY function that deals with unauthenticated users
Question:
Any clue how can i use Amplify (Android) and have AWS credentials via AWS Cognito for unauthenticated users ???
This is David from the Amplify Android team. I was actually just looking into this the other day and currently there's a hack that's required to make unauth users work.
After setting up unauth/guest users through the CLI (as you mentioned you had) you have to call the getAWSCredentials method on the underlying escape hatch once for the app to get it to work.
Here's a code snippet I'd written that you can run after Amplify.configure (and again, this only needs to be run once per app install):
AWSMobileClient mobileClient = (AWSMobileClient) Amplify.Auth.getPlugin("awsCognitoAuthPlugin").getEscapeHatch();
mobileClient.getAWSCredentials(new Callback<AWSCredentials>() {
#Override
public void onResult(AWSCredentials result) {
// Now you'll see the Identity ID and AWSCredentials in the resulting auth session object.
Amplify.Auth.fetchAuthSession(
result2 -> Log.i(TAG, result2.toString()),
error -> Log.e(TAG, error.toString()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void onError(Exception e) {
// Handle the error however is best for your app
}
});
I'm working on a solution to avoid this hack right now and adding a documentation section on Unauth users to our site but in the meantime this should get it working for you.
Again note you only have to do this once and from then on out, it should just work when you call fetchAuthSession.
UPDATE: The non patched (official) version:
Amplify.Auth.fetchAuthSession(
result -> {
AWSCognitoAuthSession cognitoAuthSession = (AWSCognitoAuthSession) result;
switch (cognitoAuthSession.getIdentityId().getType()) {
case SUCCESS:
Log.i(TAG, "identity: " + cognitoAuthSession.getIdentityId().getValue());
Log.i(TAG, "credentials: " + cognitoAuthSession.getAWSCredentials().getValue(););
break;
case FAILURE:
Log.i(TAG, "FAILURE IdentityId not present because: " + cognitoAuthSession.getIdentityId().getError().toString());
}
},
error -> Log.e(TAG, "UNAUTH USERS ERR: " + error.toString()));
You wont be able to retrieve an authenticated session unless you have a logged in user.
If your Identity Pool (not User Pool) is configured for unauthenticated or guest users you can make a simple call to the GetId endpoint:
GetId
Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account.
This is a public API. You do not need any credentials to call this API.
Request Syntax
{
"AccountId": "string",
"IdentityPoolId": "string",
"Logins": {
"string" : "string"
}
}
https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html
You should then be able to use the ID to retrieve a token using:
GetOpenIdToken
Gets an OpenID token, using a known Cognito ID. This known Cognito ID is returned by GetId. You can optionally add additional logins for the identity. Supplying multiple logins creates an implicit link.
The OpenID token is valid for 10 minutes.
This is a public API. You do not need any credentials to call this API.
Request Syntax
{
"IdentityId": "string",
"Logins": {
"string" : "string"
}
}
https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html
I have an Android application in which I'm using Azure AD B2C to authenticate users. Users login and logout of the application as needed. I would like to give the user the option to delete their own account.
I understand that I need to use the Azure AD Graph API to delete the user. This is what I have so far:
According to this link, it looks like deleting a user from a personal account (which is what the B2C users are using) is not possible. Is that correct?
Here's my code snippet for the Graph API call. Feel free to ignore it if I'm off track and there is a better way to solve this.
I believe I need a separate access token than what my app currently has (as the graph API requires other API consent). So, I'm getting the access token as follows:
AcquireTokenParameters parameters = new AcquireTokenParameters.Builder()
.startAuthorizationFromActivity(getActivity())
.fromAuthority(B2CConfiguration.getAuthorityFromPolicyName(B2CConfiguration.Policies.get("SignUpSignIn")))
.withScopes(B2CConfiguration.getGraphAPIScopes())
.withPrompt(Prompt.CONSENT)
.withCallback(getGraphAPIAuthCallback())
.build();
taxApp.acquireToken(parameters);
In the getGraphAPIAuthCallback() method, I'm calling the Graph API using a separate thread (in the background):
boolean resp = new DeleteUser().execute(authenticationResult.getAccessToken()).get();
Finally, in my DeleterUser() AsyncTask, I'm doing the following:
#Override
protected Boolean doInBackground(String... aToken) {
final String asToken = aToken[0];
//this method will be running on background thread so don't update UI from here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
IAuthenticationProvider mAuthenticationProvider = new IAuthenticationProvider() {
#Override
public void authenticateRequest(final IHttpRequest request) {
request.addHeader("Authorization",
"Bearer " + asToken);
}
};
final IClientConfig mClientConfig = DefaultClientConfig
.createWithAuthenticationProvider(mAuthenticationProvider);
final IGraphServiceClient graphClient = new GraphServiceClient.Builder()
.fromConfig(mClientConfig)
.buildClient();
try {
graphClient.getMe().buildRequest().delete();
} catch (Exception e) {
Log.d(AccountSettingFragment.class.toString(), "Error deleting user. Error Details: " + e.getStackTrace());
}
return true;
}
Currently, my app fails when trying to get an access token with a null pointer exception:
com.microsoft.identity.client.exception.MsalClientException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
Any idea what I need to do to provide the user the option to users to delete their own account? Thank you!
Thanks for the help, #allen-wu. Due to his help, this azure feedback request and this azure doc, I was able to figure out how to get and delete users silently (without needing intervention).
As #allen-wu stated, you cannot have a user delete itself. So, I decided to have the mobile app call my server-side NodeJS API when the user clicks the 'Delete Account' button (as I do not want to store the client secret in the android app) and have the NodeJS API call the Azure AD endpoint to delete the user silently. The one caveat is that admin consent is needed the first time you try to auth. Also, I have only tested this for Graph API. I'm not a 100% sure if it works for other APIs as well.
Here are the steps:
Create your application in your AAD B2C tenant. Create a client secret and give it the following API permissions: Directory.ReadWrite.All ;
AuditLog.Read.All (I'm not a 100% sure if we need the AuditLog permission. I haven't tested without it yet).
In a browser, paste the following link:
GET https://login.microsoftonline.com/{tenant}/adminconsent?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
&redirect_uri=http://localhost/myapp/permissions
Login using an existing admin account and provide the consent to the app.
Once you've given admin consent, you do not have to repeat steps 1-3 again. Next, make the following call to get an access token:
POST https://login.microsoftonline.com/{B2c_tenant_name}.onmicrosoft.com/oauth2/v2.0/token
In the body, include your client_id, client_secret, grant_type (the value for which should be client_credentials) and scope (value should be 'https://graph.microsoft.com/.default')
Finally, you can call the Graph API to manage your users, including deleting them:
DELETE https://graph.microsoft.com/v1.0/users/{upn}
Don't forget to include the access token in the header. I noticed that in Postman, the graph api had a bug and returned an error if I include the word 'Bearer' at the start of the Authorization header. Try without it and it works. I haven't tried it in my NodeJS API yet, so, can't comment on it so far.
#allen-wu also suggested using the ROPC flow, which I have not tried yet, so, cannot compare the two approaches.
I hope this helps!
There is a line of code: graphClient.getUsers("").buildRequest().delete();
It seems that you didn't put the user object id in it.
However, we can ignore this problem because Microsoft Graph doesn't allow a user to delete itself.
Here is the error when I try to do it.
{
"error": {
"code": "Request_BadRequest",
"message": "The principal performing this request cannot delete itself.",
"innerError": {
"request-id": "8f44118f-0e49-431f-a0a0-80bdd954a7f0",
"date": "2020-06-04T06:41:14"
}
}
}
To begin with, I'm working on a Unity Game where I'm authenticating user when the game starts. My build environment is android. I'm using Firebase authentication for Google Play Games Services to authenticate user.
When the game starts in my android device or emulator, it is able to authenticate Play Games Services as well as able to connect with Firebase (I'm getting analytics data). However, when I pass the PlayGames AuthCode into Firebase.Auth Credentials, it stops executing the code (I've debug log for it). It does not throw any error in LogCat except
Firebase | server_auth_code
I tried searching web for different issues, but nothing. I checked my keys in player setting, firebase settings, OAuth 2.0 credentials on my Google API console and even check keys from my Google Play Console (which I'm not using at this stage). I have even checked my test users email addresses in Game Services and tried multiple google play games account. But issue still persist.
I'm using similar script in my other unity project where authentication works like a charm. I tried to use same script here and ended up with this issue: here. However, I solved it by removing all the packages and re-importing them into unity and changed my call functions in the script. Now, I'm stuck at this issue.
Here is cs file:
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System.Threading.Tasks;
public class SetFirebase : MonoBehaviour
{
string authCode;
void Start()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().
RequestServerAuthCode(false /* Don't force refresh */).Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
Social.localUser.Authenticate((bool success) =>
{
if (success)
{
authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
Debug.Log("PlayGames successfully authenticated!");
Debug.Log("AuthCode: " + authCode);
}
else
{
Debug.Log("PlayGames SignIn Failed");
}
});
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
Debug.Log("Firebase Ready!!!");
RunFirebase();
}
else
{
Debug.LogError(System.String.Format("Could not resolve all Firebase dependencies: {0}", dependencyStatus));
}
});
}
private void RunFirebase(){
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Debug.Log("init firebase auth ");
Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode);
Debug.Log(" passed auth code ");
auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("SignInOnClick was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
return;
}
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
});
}
}
My LogCat executes everything till "init firebase auth" but does not execute "passed auth code" so I know there is some issue in passing the credentials. It also does not run anything inside auth.SignInWithCredentialAsync(credential).
Any help or suggestion would be highly appreciated. Thank you.
There are two things I may suggest:
1) Replace ContinueWith with ContinueWithOnMainThread. This is a Firebase Extension that will guarantee that your logic runs on the main Unity thread (which tends to resolve many Unity specific issues). I go into more detail about that here.
2) Your logic may have a race condition between the Authenticate callback and the CheckAndFixDependenciesAsync continuation. These will not necessarily run in the order that you see them in your logic.
If I were building this system, I might prefer using Coroutines and a custom yield instruction:
class Authenticate : CustomYieldInstruction
{
private bool _keepWaiting = true;
public override bool keepWaiting => _keepWaiting;
public Authenticate(Social.ILocalUser user) {
user.Authenticate((bool success)=>{
/* old authentication code here */
_keepWaiting = false;
});
}
}
Then in a coroutine have something like:
private IEnumerator InitializeCoroutine() {
/* old authentication code */
// I'm ignoring error checking for now, but it shouldn't be hard to figure in.
// I'm mostly going from memory now anyway
// start both authentication processes in parallel
var authenticate = new Authenticate(Social.localUser);
var firebaseDependenciesTask = FirebaseApp.CheckAndFixDependenciesAsync();
// wait on social
yield return authenticate;
// wait on Firebase. If it finished in the meantime this should just fall through
yield return new WaitUntil(()=>firebaseDependenciesTask.IsComplete);
RunFirebase();
}
This way my logic looks roughly synchronous whilst still maintaining the asynchronosity (spell check claims that I made up that word) of the systems you're depending on and you avoid threading related issues that arise when using ContinueWith.
Let me know if that helps!
--Patrick
I want to verify the reCAPTCHA of my Android user. So I'm reading this documentation: https://developers.google.com/recaptcha/docs/verify:
For Android library users, you can call the SafetyNetApi.RecaptchaTokenResult.getTokenResult() method to get response token if the status returns successful.
In the manual of this function, the following description is written about getTokenResult (https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetApi.RecaptchaTokenResult.html#getTokenResult()):
Gets the reCAPTCHA user response token, which must be validated by calling the siteverify method described in Verify the user's response.
The manual of the siteverify function describes the following (https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetClient.html#verifyWithRecaptcha(java.lang.String)):
Provides user attestation with reCAPTCHA.
If reCAPTCHA is confident that this is a real user on a real device it will return a token with no challenge. Otherwise it will provide a visual/audio challenge to attest the humanness of the user before returning a token.
My question
I want to use my backend server (Cloud Functions) to verify the reCAPTCHA. However, according to the Android documentation, all the above functions seem to be put client-side. Indeed, siteverify should be called with the token got with getTokenResult, and both seem to be part of the Android SecureNET ReCAPTCHA Android API...
However, I think that using Cloud Functions would be more secure! Can I use my backend however?
Edit: back-end call to siteverify in Cloud Functions
exports.verifyRecaptcha = functions.https.onRequest((request, response) => {
const user_response_token = request.query.user_response_token;
if(user_response_token == '') {
throw new functions.https.HttpsError('invalid-argument', 'The function must be called with an adequat user response token.');
}
const remote_url = 'https://www.google.com/recaptcha/api/siteverify';
const secret = null;
request.post({url: remote_url, form:{secret: secret, response: user_response_token}}, function(error, response, body) {
if(error) {
throw new functions.https.HttpsError('unknown', error);
}
if(!response.statusCode != 200) {
throw new functions.https.HttpsError('unknown', 'Something went wrong. Status code: ' + response.statusCode + '.');
}
if(!body.success) {
throw new functions.https.HttpsError('unknown', 'Unable to verify this captcha.');
}
return response;
});
});
You can take the token returned from getTokenResult(), send it to your backend, and have your backend call the web API version of siteverify:
https://www.google.com/recaptcha/api/siteverify
I have an ASP.NET WebApi 2.1 application with OAuth2 configured. I have and Android client where I can do authentication by using the following methods:
WebView approach (Web Api External Providers): redirect to https://www.facebook.com/dialog/oauth..., user do login there, FB asks for permissions, redirects to my url, catch it, access token got, done.
Facebook SDK approach: under the hood it does: redirect to https://graph.facebook.com/oauth..., user do login there, FB asks for permissions, redirects to my url, catch it, access token got, done.
The problem is, if I go with the WebView version, the token is good for authorizing user in my Web Api application, but I cannot call Graph API by using it, I receive OAuthException 190 (no subcode).
But if I do the SDK authorization, Graph API is accessible (through the Android Facebook SDK), but using the token I've got from it, Web Api authorization is not working, I get 401 by calling Authorization/UserInfo.
So my question are the above token types interchangeable somehow?
Any help would be greatly appreciated.
Sorry if that was not clear, I'm using Web Api w/ ASP.NET Identity 2.0 template, so OAuth plumbing code is already present there.
I was able to find an answer to my own question, let me share it with you.
So the problem is that the token I've got from the Facebook's OAuth dialog after the redirect is not the same token that my application can use to call Facebook Graph APIs in the name of the actual user. That Graph API token is reachable at the following point:
Assume you are using the mentioned template above, you can find App_Data/Startup.Auth.cs class with definition of a FacebookAuthenticationOptions instance. There you can catch the API token and can persist that into the database. For example:
var fbopts = new FacebookAuthenticationOptions
{
AppId = Global.Config.ExternalServices.FacebookAppID,
AppSecret = Global.Config.ExternalServices.FacebookAppSecret,
Scope = { "email", "user_friends", "publish_actions" },
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = async context =>
{
// This token will be OK for calling Graph API
string accessToken = context.AccessToken;
using (var tracer = Global.Tracer.CreateBuilder())
{
try
{
tracer.InformationLine("Storing Facebook OAuth token: " + accessToken);
string fbUserID = context.Identity.GetUserId();
string fbUserName = context.Identity.Name;
tracer.InformationLine("Facebook User ID: " + fbUserID);
tracer.InformationLine("Facebook User Name: " + fbUserName);
// Store it into the db
// assume Task StoreOAuthToken(string providerName, string providerKey, string accessToken) is defined
await StoreOAuthToken("Facebook", fbUserID, accessToken);
}
catch (Exception ex)
{
tracer.ErrorLine("Failed.", ex);
}
}
}
}
};
app.UseFacebookAuthentication(fbopts);
At this point you're gonna have a row in a table that consists of the following columns:
OAuthAccessToken.ProviderName
OAuthAccessToken.ProviderKey
OAuthAccessToken.AccessToken
Now you can provide an API to your consumers to have that API token for calling Graph API, like:
[Route("AccessTokens")]
[Authorize]
public async Task<List<OAuthAccessToken>> GetAccessTokens(string providerName = null)
{
var userID = User.Identity.GetUserId();
var q = from l in this.Context.AspNetUserLogins // Managed by ASP.NET Identity 2.0
from t in this.Context.OAuthAccessTokens // Stored by you with above code
where l.UserId == userID && t.ProviderName == l.LoginProvider && t.ProviderKey == l.ProviderKey
select t;
if (!string.IsNullOrEmpty(providerName)) q = q.Where(t => t.ProviderName == providerName);
return await q.ToListAsync();
}
So on Android after doing a Facebook login I have the Bearer token for my application's Web Api calls, and I can get my token for accessing Graph API by calling the action above.
Maybe there are easier methods for achieving the above. Please let me know if you find any.