Reputation: 6893
I am doing authentication using azure mobile apps in my xamarin forms app and once I retrieve unique User Authentication Id, I am storing this with bunch of other user information into a sync table called Users as shown below.
So basically I am also using Azure Mobile Sync in my app. Id column below is predefined Azure Mobile Id. Everything works fine as long as I have same user with Id stored in Local sync db.
Once, if I lose this local Db information (It can be caused by reinstalling app or deleting app data). User will prompt to re-login and although I get the same Azure Authentication Id, snyc will cause a new insert into Azure Users table. Because it doesnt know that it is an existing row. Possible Solutions is to make userAuthId as PK (eventually it is unique). But if I do that I will lose azure mobile sync feature, wont I? Can somebody shade me lights how to make Custom Id column for azure mobile sync? or instead of auto generate, i can pass the value from client.
Upvotes: 0
Views: 267
Reputation: 6893
I found a solution myself following suggestion from Bruce Chen. Basically just remove the Default Value or Binding as shown in the image and on your backend Api change the Post function as below and also your controller should retrieve UserId from the authentication by calling ClaimsPrincipal as below. Using this method, you get the authenticated UserId within your Api. You can see the full implementation on this github link. So you can pass this as Id of the table. I also added extra check before I insert that if Id is already exist or not since I am not auto generating the Id.
I hope this helps to anybody else having same problem.
public string UserId => ((ClaimsPrincipal)User).FindFirst(ClaimTypes.NameIdentifier).Value;
public async Task<IHttpActionResult> PostUser(User item)
{
try
{
User current;
item.Id = UserId;
myAppsAPIContext db = new myAppsAPIContext();
User User = db.Users.Where(u => u.Id == UserId).SingleOrDefault();
if (User == null)
{
current = await InsertAsync(item);
}
else
current = User;
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
catch (Exception ex)
{
TelemetryClient.TrackException(ex);
return null;
}
}
Upvotes: 0
Reputation: 18465
I encountered the similar issue before, I just set the value of Id
column in my users table to UserAuthId
. For adding the additional UserAuthId
and use it as the foreign key in other tables, I assumed that after user logged, you need to check the online Users
table and try to retrieve the existing user record based on the current UserAuthId
, then you could insert/update your local data store or directly update your online Users
table. Moreover, I would recommend you follow adrian hall's book here about developing Azure Mobile Apps with Xamarin.
Upvotes: 1