使用 Xamarin.Auth 进行 OAuth2 身份验证 - 用户名和密码

本文关键字:用户 密码 身份验证 Xamarin Auth 进行 OAuth2 使用 | 更新日期: 2023-09-27 17:56:03

我在使用 Xamarin.Auth 进行 OAuth2 身份验证时遇到了一些问题。

从邮递员,我正在通过GET方法向我的后端URL发送令牌请求:http://example.com/backend/oauth/token通过添加到标头:

授权, 基本 xxx

并在 URL 中使用以下参数:

client_id=后端客户端

范围=读取

grant_type=密码

用户名=管理员

密码=管理员

所以它是这样的:http://example.com/backend/oauth/token?client_id=backendClient&scope=read&grant_type=password&username=admin&password=admin

它给了我 JSON,看起来像:

{
"access_token": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"token_type": "bearer",
"refresh_token": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"expires_in": 9999,
"scope": "read"
}

我想从移动应用程序(使用 Xamarin.Forms 应用)向后端服务进行身份验证,并且我尝试使用 Xamarin.Auth 对后端进行身份验证 - https://developer.xamarin.com/guides/xamarin-forms/web-services/authentication/oauth/

事实上,使用 OAuth2Authenticator,它至少能够"ping"我的后端(通过放置 URL、clientIde 等),因为它返回:

<UnauthorizedException>
    <error>unauthorized</error>
    <error_description>Full authentication is required to access this resource</error_description>
</UnauthorizedException>

但是消息它以错误的方式发送 - 至少我是这么认为的,因为标头中没有授权 + 我没有看到任何将用户名和密码传递到 OAuth2Authenticator 的可能性。

有没有人知道,我怎么能做到这一点?或者我应该使用其他东西 - 而不是Xamarin.Auth?

谢谢。

使用 Xamarin.Auth 进行 OAuth2 身份验证 - 用户名和密码

以下是我的做法(不使用 Xamarin.Auth):

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenGoesHere);

然后,您可以添加您喜欢的任何内容和Get/Post/PutAsync,无论您需要什么。