cloudBackend.setCredential not setting createdBy/updatedBy/owner properties of CloudEntity - android

I am using mobile backend starter and I am trying to update an entity when using the secured by id setting. I keep getting the error
com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
"code": 401,
"errors": [
{
"domain": "global",
"location": "Authorization",
"locationType": "header",
"message": "Insuffient permission for updating a CloudEntity: CE:123456 by: USER:123456",
"reason": "required"
}
],
"message": "Insuffient permission for updating a CloudEntity: CE: 123456 by: USER:123456"
}
The documentation (https://cloud.google.com/developers/articles/mobile-backend-starter-api-reference/#ciagaa) states
In the code below, the backend allows the call in “Secured by Client
ID” mode. It also sets createdBy/updatedBy/owner properties of
CloudEntity automatically
GoogleAccountCredential credential =
GoogleAccountCredential.usingAudience(this, "<Web Client ID>");
credential.setSelectedAccountName("<Google Account Name>");
cloudBackend.setCredential(credential);
So I wrote the following code
mCloudBackend = new CloudBackendMessaging(this);
GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(this, Consts.AUTH_AUDIENCE);
mCloudBackend.setCredential(credential);
String accountName =
mCloudBackend.getSharedPreferences().getString(
Consts.PREF_KEY_ACCOUNT_NAME, null);
credential.setSelectedAccountName(accountName);
mCloudBackend.setCredential(credential);
newPost.setId(updateRide);
mCloudBackend.update(newPost, handler);
Unfortunately this is giving the error above. However, the update is going through as I can see changes in entity when I query the datastore. The problem seems to come from the fact that the createdBy/updatedBy/owner properties are set to null and so are not being set automatically.
I have seen other questions where the answer has been to query the entity prior to the update, use this to set the aforementioned properties and then perform the update. I would rather avoid this as it seems like an unnecessary call to the datastore. So my question is how to I get the GoogleAccount createdBy updatedBy and owner properties?

I faced similar problem while playing with the mobile backend starter source.And even though I followed the answers provided in this link,I wasn't able to resolve the issue.However,what I did was to grab the mobile backend source code and make some modifications.Grab the code and in the CrudOperations.java file,you will see this method
private Map<String, Entity> findAndUpdateExistingEntities(EntityListDto cdl, User user)
throws UnauthorizedException{
// create a list of CEs with existing Id
EntityListDto entitiesWithIds = new EntityListDto();
Map<String, EntityDto> entitiesWithIdMap = new HashMap<String, EntityDto>();
for (EntityDto cd : cdl.getEntries()) {
if (cd.getId() != null) {
entitiesWithIds.add(cd);
entitiesWithIdMap.put(cd.getId(), cd);
}
}
// try to get existing CEs
Map<String, Entity> existingEntities = getAllEntitiesByKeyList(entitiesWithIds
.readKeyList(user));
// update existing entities
for (String id : existingEntities.keySet()) {
// check ACL
Entity e = existingEntities.get(id);
SecurityChecker.getInstance().checkAclForWrite(e, user);
// update metadata
EntityDto cd1 = entitiesWithIdMap.get(id);
cd1.setUpdatedAt(new Date());
if (user != null) {
cd1.setUpdatedBy(user.getEmail());
}
// update the entity
cd1.copyPropValuesToEntity(e);
}
return existingEntities;
}
From the above code,comment out SecurityChecker.getInstance().checkAclForWrite(e, user);
and the throws UnAuthorizedException lines and redeploy your backend.Doing so will make all users of your app able to make updates to the concerned entity.This could be risky if you are strictly concerned about ownership.So,consider your security concerns before taking this approach.Haven done that,you can now freely update the concerned cloud entity.Remember to make as default your newly deployed backend on the server side.

Related

Firebase Auth Custom claims not propagating to client

I have a user with UID 1 where the custom claims are set as,
frompos=true
I am setting new custom claims to this user from the ADMIN SDK for java the following way:
Map<String,Object> claims = new HashMap<>();
claims.put("frompos",false);
FirebaseAuth.getInstance().setCustomUserClaimsAsync("1", claims).get(10000,
TimeUnit.MILLISECONDS);
I print the claims on the server side to check if the claims are set:
UserRecord user = FirebaseAuth.getInstance().getUserAsync("1").get(10000,
TimeUnit.MILLISECONDS);
LOG.debug("user new claims " + user.getCustomClaims());
The result as expected is that the claims get set:
user new claims {frompos=false}
Now on the android sdk side, I have the user already logged in so I am refreshing the ID token manually to propagate the claims as the docs say
(https://firebase.google.com/docs/auth/admin/custom-claims)
FirebaseAuth.getInstance().getCurrentUser().getIdToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
#Override
public void onComplete(#NonNull Task<GetTokenResult> task) {
if(task.isSuccessful()){
Log.d("FragmentCreate","Success refreshing token "+(FirebaseAuth.getInstance().getCurrentUser()==null));
Log.d("FragmentCreate","New token "+task.getResult().getToken());
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("FragmentCreate","Failure refreshing token "+(FirebaseAuth.getInstance().getCurrentUser()==null)+" "+e.toString());
}
});
Now I use the printed Id Token printed here and verify it on server side and print the claims from it
FirebaseToken tokenTest = FirebaseAuth.getInstance(ahmedabadRepoApp).verifyIdTokenAsync(token).get(10000,TimeUnit.MILLISECONDS);
LOG.debug("Token claims are "+tokenTest.getClaims());
But the claims printed here are:
{"aud":"ahmedabadrepo","auth_time":1514724115,"email_verified":false,"exp":1514730425,"iat":1514726825,"iss":"https://securetoken.google.com/ahmedabadrepo","sub":"1","frompos":true,"user_id":"1","firebase":{"identities":{},"sign_in_provider":"custom"}}
Thus the frompos value did not propagate to the client sdk even though I did refresh the Id token manually.
I was having the same issue in angular - I set the claim using the Admin SDK on the server, but then they would not be in the user on the client.
Using the following I can see the claims in the payload:
this.firebaseAuth.auth.currentUser.getIdToken().then(idToken => {
const payload = JSON.parse(this.b64DecodeUnicode(idToken.split('.')[1]))
console.log(payload);
}
)
b64DecodeUnicode(str) {
return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) {
var code = p.charCodeAt(0).toString(16).toUpperCase();
if (code.length < 2) {
code = '0' + code;
}
return '%' + code;
}));
}
Here is a good write up of this where I copied the above:
At the moment the client-side code must parse and decode the user’s ID
token to extract the claims embedded within. In the future, the
Firebase client SDKs are likely to provide a simpler API for this use
case.
Relevant info from Firebase Docs:
Custom claims can only be retrieved through the user's ID token.
Access to these claims may be necessary to modify the client UI based
on the user's role or access level. However, backend access should
always be enforced through the ID token after validating it and
parsing its claims. Custom claims should not be sent directly to the
backend, as they can't be trusted outside of the token.
Once the latest claims have propagated to a user's ID token, you can
get these claims by retrieving the ID token first and then parsing its
payload (base64 decoded):
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
firebase.auth().currentUser.getIdToken()
.then((idToken) => {
// Parse the ID token.
const payload = JSON.parse(b64DecodeUnicode(idToken.split('.')[1]));
// Confirm the user is an Admin.
if (!!payload['admin']) {
showAdminUI();
}
})
.catch((error) => {
console.log(error);
This might help: https://stackoverflow.com/a/38284384/9797228
firebase.auth().currentUser.getIdToken(true)
The client sdk is caching the old token (old claims).
You should add a mechanism to refresh it after changing the claims (eg. push notification) or just wait for the old token to expires or user to lougout and login again.
It's explained here https://youtu.be/3hj_r_N0qMs?t=719
Edit
You can force the sdk to refresh the token using firebase.auth().currentUser.getIdToken(true)

Endpoints generated client library

My problem is that I migrated to Endpoints v2, and at some point down the line my GCM registration code stopped working.
Stopped working? More specifically, the generated client library is attempting to send a POST request in the form provided in the top line of this image:
The second line is what happens when I send the request myself manually with Postman (changing it so that it sends the data in the URL fragment instead of in the query string). This works, and is added to my database.
The registration is sent using the standard API builder:
Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://"+Constants.PROJECT_ID+".appspot.com/_ah/api/");
regService = builder.build();
regService.registerDevice(gcmRegistrationId).execute();
The endpoint itself looks like this:
#ApiMethod(name = "registerDevice", httpMethod = "post")
public void registerDevice(#Named("regId") String regId) {
if(findRecord(regId) != null) {
log.info("Device " + regId + " already registered, skipping register");
return;
}
RegistrationRecord record = new RegistrationRecord();
record.setRegId(regId);
ofy().save().entity(record).now();
}
How can this be resolved?
My code is being deployed and generated with the following commands:
gradlew endpointsOpenApiDocs
gcloud endpoints services deploy backend\build\endpointsOpenApiDocs\openapi.json
gradlew appengineDeploy
gradlew endpointsClientLibs
If you want the parameter to be a query string, it should be marked #Nullable as well. This will tell take the parameter out of the path. Looks like there is some mismatch between the configuration in the old and new frameworks, but it is more correct to use #Nullable for query parameters and omit it for path parameters.

Servicestack hosting on subdomain and authenticating from main domain

I am creating one web app in asp.net MVC with identity (OWIN)
framework. Now it will be hosted in one domain lets say domain.com
Now i want to host servicestack on sub domain lets say
service.domain.com
Now any user who login in domain.com with username and password and if
it success then i want to authenticate servicestack too so that all
services with [Authenticate] attribute will work.
The primary objective of hosting servicestack on subdomain is to make
code independent for database side.
And i can easily call this REST api in my future Android and iOS app.
Is it something wrong i am doing?
I have tried with code provided by mythz but now i get this error
AuthKey required to use: HS256
My MVC code is (running on: localhost:51055)
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
{
var jwtProvider = new JwtAuthProvider();
var header = JwtAuthProvider.CreateJwtHeader(jwtProvider.HashAlgorithm);
var body = JwtAuthProvider.CreateJwtPayload(new AuthUserSession
{
UserAuthId = user.Id,
DisplayName = user.NameSurname,
Email = user.Email,
IsAuthenticated = true,
},
issuer: jwtProvider.Issuer,
expireIn: jwtProvider.ExpireTokensIn,
audience: jwtProvider.Audience,
roles: new[] { "TheRole" },
permissions: new[] { "ThePermission" });
var jwtToken = JwtAuthProvider.CreateJwt(header, body, jwtProvider.GetHashAlgorithm());
var client = new JsonServiceClient("http://localhost:52893/");
client.SetTokenCookie(jwtToken);
}
}
error occured on this statement jwtProvider.GetHashAlgorithm()
Any my servicestack code is (running on: localhost:52893)
public class AppHost : AppHostBase
{
public AppHost() : base("MVC 4", typeof(HelloService).Assembly) { }
public override void Configure(Funq.Container container)
{
SetConfig(new HostConfig
{
RestrictAllCookiesToDomain = "localhost",
HandlerFactoryPath = "api",
DebugMode = true
});
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[] {
new JwtAuthProviderReader(AppSettings) {
AuthKey = AesUtils.CreateKey(),
HashAlgorithm = "RS256"
},
}));
Plugins.Add(new CorsFeature(
allowOriginWhitelist: new[] {
"http://localhost",
"http://localhost:51055"
},
allowCredentials: true,
allowedMethods: "GET, POST, PUT, DELETE, OPTIONS",
allowedHeaders: "Content-Type, Allow, Authorization, Wait, Accept, X-Requested-With, Put-Default-Position, Put-Before, If-Match, If-None-Match, Content-Range",
exposeHeaders: "Content-Range"
));
}
}
Is something wrong i am doing?
You're looking to integrate 2 different frameworks together by using Authentication from MVC (OWIN) with ServiceStack - an isolated framework that doesn't have any coupling or knowledge of OWIN or MVC's Authentication. This is further conflated by trying to transfer Authentication from one domain into a different framework on a different sub domain. Usually trying to try integrate Authentication between completely different frameworks is a difficult endeavor and requiring it to work across sub-domains adds even more complexity.
Storing an Authenticate User Session
With that said the 2 easiest solutions that can work is to store an authenticated UserSession in ServiceStack by serializing an AuthUserSession into the location which ServiceStack expects by using the same distributed Caching Provider configured on both MVC and ServiceStack Apps.
So you can configure ServiceStack to use a Redis CacheClient you can create and store a UserSession in MVC:
var session = new AuthUserSession {
UserAuthId = userId,
DisplayName = userName,
Email = userEmail,
IsAuthenticated = true,
};
Then save it using the configured Redis Manager in MVC:
var sessionId = SessionExtensions.CreateRandomSessionId();
using (var redis = redisManager.GetClient())
{
redis.Set($"urn:iauthsession:{sessionId}", session);
}
To get ServiceStack to use this Authenticated UserSession you need to configure the ss-id Session Cookie Id with sessionId and since you want the client to send the same Cookie to sub-domain you need to configure the Cookie to use a wildcard domain.
Using JWT
The alternative (and my preferred solution) that doesn't require sharing any infrastructure dependencies is to use a stateless JWT Token which encapsulates the Users Session in a JWT Token. To do this in MVC you would create a JWT Token from an Authenticated User Session which you can send to a ServiceStack AppHost configured with the same JwtAuthProvider.
Clients can then make Authenticated Requests by sending JWT Tokens in the JWT Cookie, i.e. sending the JWT Token in the ss-tok cookie which to work across sub-domains needs to be configured to use the same wildcard domain as above.

How can I set Firebase Database Security Rules for Android App

I'm making android app which will collect useful info from user. Here is the code
Firebase postRef = mRef.child("marks");
Map<String, String> marks = new HashMap<String, String>();
marks.put("Name", fname);
marks.put("Phone", fphone);
marks.put("Year", fyear);
marks.put("Email", femail);
String uid=postRef.getKey();
Toast.makeText(im.this,"Thanks!",Toast.LENGTH_LONG).show();
This will result in getting the data from every user of my Android App. How should I set specific rules by which only authenticated users can get access of their information. Not other users info.
I tried this in Firebase Rules:
{
"rules":{
"$uid":{
".read":"auth.uid==$uid",
".write":"auth.uid==$uid",
".validate":"newData.hasChildren(['uid','Email','Name'])"
}
}
}
But its not working. Kindly tell me specific solution.
If I read your question and comment correctly you are putting your data under the "marks" node. That means you also have to include that in your security rules like this:
{
"rules":{
"marks":{
"$uid":{
".read":"auth.uid==$uid",
".write":"auth.uid==$uid",
".validate":"newData.hasChildren(['uid','Email','Name'])"
}
}
}
}

Google Plus Single Sign On Server Flow - Google_AuthException Error fetching OAuth2 access token, message: 'invalid_grant'

UPDATE 27th January 2013
I have now resolved this, Please check the accepted answer.
I am having trouble to get my refresh token and my access token when using the server side flow between my Android Application and my PHP server.
So I have managed to get my One Time Code by using the below:
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
Bundle appActivities = new Bundle();
appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
"http://schemas.google.com/AddActivity");
String scopes = "oauth2:server:client_id:" + SERVER_CLIENT_ID +
":api_scope:" + SCOPE_STRING;
try {
code = GoogleAuthUtil.getToken(
OneTimeCodeActivity.this, // Context context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
System.out.println(transientEx.printStactTrace());
return "Error";
} catch (UserRecoverableAuthException e) {
// Recover
code = null;
System.out.println(e.printStackTrace());
OneTimeCodeActivity.this.startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
System.out.println(authEx.printStackTrace());
return "Error";
} catch (Exception e) {
System.out.println(authEx.printStackTrace());
}
}
Which will then store the token in the variable "code" and I call up the async task as
task.execute();
The code above will always bring up a popup message and throw UserRecoverableAuthException Need Permission that requires the user to grant offline access, which means the above will need to be called twice to retrieve the code and store it in "code"
I am now trying to send this across to my server which is implemented in PHP.
I have used the quick start https://developers.google.com/+/quickstart/php and managed to get that working.
In here, there is a sample signin.php
In here and according to the documentation this already implements a One Time Authorisation Server Side Flow.
So now my problem is sending this One Time Code to the server.
I used the photohunt Android Auth example for this located here.
https://github.com/googleplus/gplus-photohunt-client-android/blob/master/src/com/google/plus/samples/photohunt/auth/AuthUtil.java
I used the "authorization" method of the code and called up signin.php/connect through a post method shown below
$app->post('/connect', function (Request $request) use ($app, $client) {
$token = $app['session']->get('token');
if (empty($token)) {
// Ensure that this is no request forgery going on, and that the user
// sending us this connect request is the user that was supposed to.
if ($request->get('state') != ($app['session']->get('state'))) {
return new Response('Invalid state parameter', 401);
}
// Normally the state would be a one-time use token, however in our
// simple case, we want a user to be able to connect and disconnect
// without reloading the page. Thus, for demonstration, we don't
// implement this best practice.
//$app['session']->set('state', '');
$code = $request->getContent();
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// You can read the Google user ID in the ID token.
// "sub" represents the ID token subscriber which in our case
// is the user ID. This sample does not use the user ID.
$attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)
->getAttributes();
$gplus_id = $attributes["payload"]["sub"];
// Store the token in the session for later use.
$app['session']->set('token', json_encode($token));
$response = 'Successfully connected with token: ' . print_r($token, true);
}
return new Response($response, 200);
});
Now when I send the code using the above implementation, I get an 500 messages that says the below
Google_AuthException Error fetching OAuth2 access token, message: 'invalid_grant'
in ../vendor/google/google-api-php-client/src/auth/Google_OAuth2.php line 115
at Google_OAuth2->authenticate(array('scope' => 'https://www.googleapis.com/auth/plus.login'), '{ "token":"xxxxxxxx"}') in ../vendor/google/google-api-php-client/src/Google_Client.php line 131
at Google_Client->authenticate('{ "token":"xxxxxxx"}') in ../signin.php line 99
at {closure}(object(Request))
at call_user_func_array(object(Closure), array(object(Request))) in ../vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php line 117
at HttpKernel->handleRaw(object(Request), '1') in ../vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php line 61
at HttpKernel->handle(object(Request), '1', true) in ../vendor/silex/silex/src/Silex/Application.php line 504
at Application->handle(object(Request)) in ../vendor/silex/silex/src/Silex/Application.php line 481
at Application->run() in ../signin.php line 139
Funny enough I have had to worked once where I did receive a 200, but I cannot recreate it.
So I know I have definitely got the implementation wrong, but I have no clue on how to send it and get my refresh token. I can't find anywhere on the web that explains this. Is someone able to help me please.
UPDATE 16 Jan 2014
Using https://www.googleapis.com/oauth2/v1/tokeninfo?access_token= I can see that the token being produced from getToken is valid and is indeed valid for 1 hour.
I can confirm the json formation is correct by changing the way I am inputting into the Post request and if I don't do it properly I get a total failure.
Now I am going deeper into the php and look at this section Google_OAuth2.php line 115 where it is breaking it is throwing a Google_AuthException. The code is below and this is provided in the quick starter pack
/**
* #param $service
* #param string|null $code
* #throws Google_AuthException
* #return string
*/
public function authenticate($service, $code = null) {
if (!$code && isset($_GET['code'])) {
$code = $_GET['code'];
}
if ($code) {
// We got here from the redirect from a successful authorization grant, fetch the access token
$request = Google_Client::$io->makeRequest(new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUri,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
)));
if ($request->getResponseHttpCode() == 200) {
$this->setAccessToken($request->getResponseBody());
$this->token['created'] = time();
return $this->getAccessToken();
} else {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
if ($decodedResponse != null && $decodedResponse['error']) {
$response = $decodedResponse['error'];
}
throw new Google_AuthException("Error fetching OAuth2 access token, message: '$response'", $request->getResponseHttpCode());
}
}
$authUrl = $this->createAuthUrl($service['scope']);
header('Location: ' . $authUrl);
return true;
}
I edit the code above to make sure the code, the client id and secret were correct and they were. So that is where I am now, I don't think it is scope issues as well as I hard coded it in the client setup and still does not work. Not too sure.
UPDATE 23rd January
OK, I think it is a time issue. I used https://developers.google.com/+/photohunt/android and base my design on the BaseActivity in the Photohunt using the AuthUtil, and I get invalid grant on my server. How do I move the time back on my server in code. I read somewhere I can do time() - 10 somewhere but not sure where...
It sounds like you may be sending the same authorization code multiple times. On Android GoogleAuthUtil.getToken() caches any tokens that it retrieves including authorization codes.
If you ask for a second code without invalidating the previous code, GoogleAuthUtil will return the same code. When you try to exchange a code on your server which has already been exchanged you get the invalid_grant error. My advice would be to invalidate the token immediately after you retrieve it (even if you fail to exchange the code, you are better off getting a new one than retrying with the old one).
code = GoogleAuthUtil.getToken(
OneTimeCodeActivity.this, // Context context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
GoogleAuthUtil.invalidateToken(
OneTimeCodeActivity.this,
code
);
invalid_grant can be returned for other reasons, but my guess is that caching is causing your problem since you said it worked the first time.
This issue is now resolved. This was due to the implementation on the One Time Code exchange with the server
As specified in the my issue above, I used the photohunt example to do the exchange with my server. The Android code can be found on the below link
https://github.com/googleplus/gplus-photohunt-client-android/blob/master/src/com/google/plus/samples/photohunt/auth/AuthUtil.java
One line 44 it reads this
byte[] postBody = String.format(ACCESS_TOKEN_JSON, sAccessToken).getBytes();
This will only work if on the server side you handle the JSON. I did not.
When calling up $client->authenticate($code); in php, $code had a JSON string and therefore when calling https://accounts.google.com/o/oauth2/token the authorization code was wrong.
So it was easy as I was not sending the code in the right format.
I found this out when digging and testing https://accounts.google.com/o/oauth2/token and created a manual cURL to test the token.
As provided in the Google+ API it was stated that all examples included a One Time Code exchange, but I think the code across all platform are not consistent and one has to double check themselve to make sure everything flows correctly, which was my mistake.

Categories

Resources