提供雲端上的資料儲存是Windows Azure Mobile Services主要的服務之一,一旦牽扯到資料的維護,那麼使用者驗證機制就是必要的工作,Windows Azure Mobile Services
目前在這部分提供了4種認證方式,分別是Microsoft Account(Windows Live)、Google、Facebook及Twitter
文/黃忠成
About Authentication
提供雲端上的資料儲存是Windows Azure Mobile Services主要的服務之一,一旦牽扯到資料的維護,那麼使用者驗證機制就是必要的工作,Windows Azure Mobile Services
目前在這部分提供了4種認證方式,分別是Microsoft Account(Windows Live)、Google、Facebook及Twitter,會使用這些非自訂的認證使用者方式原因很簡單,現今的使用者驗證已經由
多帳號走向單一帳號整合,以前我們在購物或是瀏覽一些會員制的網站時,總是得申請加入會員,然後填寫一些資料,麻煩就不用提了,帳號越來越多也引發了管理上的問題。
由於Facebook、Google等網路服務的用戶越來越多,大多數的電腦用戶都擁有這4種服務其中之一的帳號,如果可以能與這些服務整合,那麼開發者就可以省下自行開發使用者認證及
儲存使用者帳密的工作,在某一程度上這也降低了網站洩漏個人資料的風險(舉個例來說,Facebook在使用者帳密驗證的安全性上有一定水準,至少他們對被攻擊的經驗值比我們高 XD)。
Windows Azure Mobile Services所提供的驗證服務主要是過濾使用其服務,例如資料存取、API呼叫的使用權,以資料存取來說,每個資料表都有相關的權限設定(CRUD)。
圖1
	
舉例來說,假設我們在這裡把READ PERMISSION設定為”Only Authenticated Users”,那麼原本的Windows Phone範例就會出現以下的錯誤。
圖2
	
Using Authentication in Windows Phone
本文使用Google Login來展示Authentication在Azure Mobile Services的應用,請先至https://code.google.com/apis/console/網站來取得一個ClientID及SECURITY KEY,這兩個資訊待會要填入Azure Mobile Services服務中才能連結兩端。
圖3
	
圖4
	
這裡先輸入Mobile Services的URL,然後點選more options。
圖5
	
你必須修改Authorized Redirect URLs為<your mobile servcie site>/login/google。
完成後會得到以下的畫面。
圖6
	
接著回到Azure Mobile Service的管理介面,切到IDENTITY頁面,輸入剛剛在Google API Console得到的資訊。
圖7
	
接著修改原來的Windows Phone程式(上篇文章中的例子)。
MainPage.xaml.cs
private IMobileServiceTable _customersTable =   App.MobileService.GetTable();
        private MobileServiceUser user;
        private async System.Threading.Tasks.Task Authenticate()
        {
            while (user == null)
            {
                string message;
                try
                {
                    user = await App.MobileService
                        .LoginAsync(MobileServiceAuthenticationProvider.Google);
                    message =
                        string.Format("You are now logged in - {0}", user.UserId);
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }
                MessageBox.Show(message);
            }
        }
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }
        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            await Authenticate();
            InitData();
        }
.................
  
一切無誤的話程式應該會導引驗證並成功取得資料。
圖8
	
圖9
	
Using Authentication in Android
在Android中使用也很簡單,我們修改上篇文章的例子。
MainActivity.java
import com.microsoft.windowsazure.mobileservices.MobileServiceUser;
import com.microsoft.windowsazure.mobileservices.MobileServiceAuthenticationProvider;
import com.microsoft.windowsazure.mobileservices.UserAuthenticationCallback;
public class MainActivity extends Activity {
    private MobileServiceClient _client;
    private MobileServiceTable _table;
    private CustomersAdapter _adapter;
    public List _list = new ArrayList();
   
    private void authenticate() {
        // Login using the Google provider.
        _client.login(MobileServiceAuthenticationProvider.Google,
                new UserAuthenticationCallback() {
                    @Override
                    public void onCompleted(MobileServiceUser user,
                            Exception exception, ServiceFilterResponse response) {
                        if (exception == null) {
                            createAndShowDialog(String.format(
                                            "You are now logged in - %1$2s",
                                            user.getUserId()), "Success");
                            refreshItemsFromTable();
                        } else {
                            createAndShowDialog("You must log in. Login Required", "Error");
                        }
                    }
                });
        }
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            // Create the Mobile Service Client instance, using the provided
            // Mobile Service URL and key
            _client = new MobileServiceClient(
                    "", "",
                    this);
            // Get the Mobile Service Table instance to use
            _table = _client.getTable(Customers.class);
        } catch (MalformedURLException e) {
            createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
        }
       
        _adapter = new CustomersAdapter(this,  android.R.layout.simple_list_item_1);
        ListView listViewToDo = (ListView) findViewById(R.id.listView1);
        listViewToDo.setAdapter(_adapter);
authenticate();
    }
……………………
     
圖10
	
Using Authentication in iOS
在iOS中使用也很簡單,修改上篇文章中的程式。
ViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.client = [MSClient clientWithApplicationURLString:@"https://myrest.azure-mobile.net/" applicationKey:@"appkey"];
    self.table = [self.client tableWithName:@"Customers"];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidAppear:(BOOL)animated
{
    if (self.client.currentUser != nil) {
        return;
    }
    [self.client loginWithProvider:@"google" controller:self animated:YES completion:^(MSUser *user, NSError *error) {
        NSPredicate * predicate = [NSPredicate predicateWithFormat:@"Name=='code6421'"];
        [self.table  readWithPredicate:predicate completion:^(NSArray *results, NSInteger totalCount, NSError *error)
         {
             self.items = [results mutableCopy];
             [self.tableView reloadData];
         }];
    }];    
}
圖11
	