Android应用如何通过WebApi调用ABP Module Zero的AccountController实现登录认证
Hey there! Let's walk through how to implement user login and authentication using the pre-built AccountController from ABP Module Zero in your Android app that talks to an ASP.NET MVC 5 Web API. ABP uses token-based authentication (usually JWT) for mobile clients, which is perfect for your use case — here's a step-by-step breakdown:
AccountController The default AccountController exposes a POST endpoint at /api/Account/Login that accepts a LoginInput model. The key fields you need to send are:
userNameOrEmailAddress: The user's username or registered emailpassword: The user's plain-text password (always use HTTPS to keep this secure!)rememberMe: A boolean (true/false) if you want the token to persist longertenancyName: Optional, only required if your app uses multi-tenancy (leave empty for single-tenant setups)
Let's use Retrofit (a popular Android HTTP client) as an example — here's how to set this up:
First, define a data class to match the backend's LoginInput model:
data class LoginInput( val userNameOrEmailAddress: String, val password: String, val rememberMe: Boolean, val tenancyName: String? = null // Optional for single-tenant apps )
Next, create a Retrofit interface for the auth API:
interface AuthApi { @POST("api/Account/Login") suspend fun login(@Body loginInput: LoginInput): Response<LoginResponse> }
And another data class to parse the successful login response (matches ABP's AuthenticateResultModel):
data class LoginResponse( val accessToken: String, val expireInSeconds: Int, val refreshToken: String, val userId: Long )
In your Android login screen's ViewModel or Activity, call the login method, and save the token to SharedPreferences if successful (so you can reuse it for future requests):
// Example using viewModelScope for coroutines viewModelScope.launch { val loginInput = LoginInput( userNameOrEmailAddress = "user@example.com", password = "yourSecurePassword", rememberMe = true ) val response = authApi.login(loginInput) if (response.isSuccessful) { response.body()?.let { loginResult -> // Save token to SharedPreferences val sharedPref = requireContext().getSharedPreferences("AppAuthPrefs", Context.MODE_PRIVATE) with(sharedPref.edit()) { putString("access_token", loginResult.accessToken) apply() } // Navigate to your app's main screen } } else { // Handle login failure (e.g., wrong password, user not found) val errorMsg = response.errorBody()?.string() ?: "Login failed. Please check your credentials." // Show error to the user (e.g., toast or snackbar) } }
For every future request that requires authentication, add the Bearer token to the request headers. With Retrofit, you can create an interceptor to automatically handle this:
class AuthInterceptor(private val sharedPref: SharedPreferences) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val token = sharedPref.getString("access_token", null) val authenticatedRequest = chain.request().newBuilder() .apply { token?.let { addHeader("Authorization", "Bearer $it") } } .build() return chain.proceed(authenticatedRequest) } }
Add this interceptor to your Retrofit client to apply it to all requests:
val okHttpClient = OkHttpClient.Builder() .addInterceptor(AuthInterceptor(sharedPref)) .build() val retrofit = Retrofit.Builder() .baseUrl("https://your-api-base-url.com/") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build()
- Always Use HTTPS: Never send passwords over unencrypted HTTP — this is non-negotiable for security.
- Handle Token Expiry: The
expireInSecondsfield tells you how long the access token is valid. Use therefreshTokento get a new access token without re-authenticating the user (check theAccountController'sRefreshTokenendpoint for this). - Multi-Tenant Checks: If your app uses multi-tenancy, make sure to pass the correct
tenancyNamein theLoginInput— otherwise, login will fail. - Verify Backend Config: Ensure your ABP backend has token-based authentication enabled. Module Zero includes this by default, but double-check your
Startup.csto confirm JWT auth is configured.
内容的提问来源于stack exchange,提问作者Joshua Kisanga

