You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms应用Auth0自定义数据库:注册存储用户地理位置需求

解决Xamarin.Forms对接Auth0自定义数据库注册时保存地理位置等信息的方案

Hey there! Let's break down how to get your Xamarin.Forms app saving location data alongside other user details (like name, stage name, address) to your Auth0 custom database during registration. I'll cover both the Auth0 script adjustments and the Xamarin.Forms implementation steps.

1. 调整Auth0自定义数据库的Create User脚本

First, head over to your Auth0 dashboard, navigate to Authentication > Databases, select your custom database, and go to the Custom Database tab. Find the Create script—this is where you'll modify the logic to accept and store your extra user fields, including location coordinates.

Here's a modified example script (adjust it to match your actual database setup, e.g., MongoDB, PostgreSQL):

function create(user, callback) {
  // 引入数据库连接(以MongoDB为例)
  const MongoClient = require('mongodb').MongoClient;
  const bcrypt = require('bcrypt'); // 一定要用bcrypt加密密码!

  MongoClient.connect('YOUR_DATABASE_CONNECTION_STRING', (err, db) => {
    if (err) return callback(err);

    // 提取所有需要存储的字段,注意和前端传入的字段名保持一致
    const hashedPassword = bcrypt.hashSync(user.password, 10); // 加密密码
    const userRecord = {
      email: user.email,
      password: hashedPassword,
      name: user.name,
      stageName: user.stageName,
      address: user.address,
      location: {
        latitude: user.latitude,
        longitude: user.longitude
      }
    };

    // 插入用户记录到数据库
    db.collection('users').insertOne(userRecord, (insertErr, result) => {
      db.close();
      if (insertErr) return callback(insertErr);
      // 返回用户ID和邮箱给Auth0
      callback(null, {
        _id: result.insertedId.toString(),
        email: user.email
      });
    });
  });
}

关键提醒: Never store plain-text passwords—always use a library like bcrypt to hash them before saving to your database.

2. Xamarin.Forms端实现:收集数据并调用Auth0注册API

Next, let's build the registration flow in your Xamarin.Forms app to collect user input and get their current location.

2.1 获取用户地理位置

Use Xamarin.Essentials to access the device's location services. First, add the NuGet package Xamarin.Essentials to your project.

Then, create a method to fetch the current location:

using Xamarin.Essentials;
using System.Threading.Tasks;

private async Task<Location> GetUserCurrentLocation()
{
    try
    {
        // 请求中等精度的位置,超时10秒
        var locationRequest = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
        var currentLocation = await Geolocation.GetLocationAsync(locationRequest);

        if (currentLocation != null)
            return currentLocation;
    }
    catch (FeatureNotSupportedException)
    {
        await DisplayAlert("Oops", "Location services aren't supported on this device.", "OK");
    }
    catch (PermissionException)
    {
        await DisplayAlert("Permission Needed", "We need location access to save your current location.", "OK");
        // 请求定位权限
        await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
    }
    catch (Exception ex)
    {
        await DisplayAlert("Error", $"Failed to get location: {ex.Message}", "OK");
    }
    return null;
}

Don't forget to add the required permissions:

  • Android: Add these lines to AndroidManifest.xml:
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
  • iOS: Add these entries to Info.plist:
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>We need your location to save your registration details.</string>
    

2.2 收集用户输入并提交注册请求

Create a registration page with entry fields for name, stage name, address, email, password. Then, on the "Register" button click, collect all data and send it to Auth0's signup endpoint.

Here's a sample click handler (using Newtonsoft.Json for serialization):

using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

private async void RegisterBtn_Clicked(object sender, EventArgs e)
{
    // 先获取地理位置
    var userLocation = await GetUserCurrentLocation();
    if (userLocation == null)
        return;

    // 收集用户输入的信息
    var registrationData = new
    {
        email = EmailEntry.Text.Trim(),
        password = PasswordEntry.Text,
        name = FullNameEntry.Text.Trim(),
        stageName = StageNameEntry.Text.Trim(),
        address = AddressEntry.Text.Trim(),
        latitude = userLocation.Latitude,
        longitude = userLocation.Longitude
    };

    // 调用Auth0的注册端点
    using var httpClient = new HttpClient();
    var jsonContent = new StringContent(
        JsonConvert.SerializeObject(registrationData),
        Encoding.UTF8,
        "application/json"
    );

    var auth0Domain = "YOUR_AUTH0_DOMAIN"; // 比如your-domain.auth0.com
    var response = await httpClient.PostAsync($"https://{auth0Domain}/auth/signup", jsonContent);

    if (response.IsSuccessStatusCode)
    {
        await DisplayAlert("Success!", "Your account has been created.", "OK");
        // 导航到登录页面
        await Navigation.PushAsync(new LoginPage());
    }
    else
    {
        var errorMessage = await response.Content.ReadAsStringAsync();
        await DisplayAlert("Registration Failed", $"Error: {errorMessage}", "OK");
    }
}

3. 验证与测试

After setting up both sides:

  • Test the registration flow in your app: fill in all fields, ensure location is fetched successfully, and submit.
  • Check your custom database (e.g., MongoDB Atlas, PostgreSQL) to confirm that all fields—including latitude, longitude, stageName, etc.—are stored correctly.
  • Verify that passwords are hashed (not plain text) in your database.

额外注意事项

  • Field Name Consistency: Make sure the field names in your Xamarin.Forms code match exactly what you're using in the Auth0 Create script (e.g., stageName vs stage_name).
  • Privacy Compliance: Clearly inform users why you're collecting their location, and ensure you're following regulations like GDPR or CCPA.
  • Error Handling: Add more robust error handling for cases like empty fields, invalid email formats, or network failures.

内容的提问来源于stack exchange,提问作者Phoneswapshop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:05:13