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

时间:2016-07-07 13:57:51

标签: c# xamarin oauth-2.0 xamarin.forms xamarin.auth

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

从POSTMAN我通过GET方法向我的后端URL发送令牌请求: http://example.com/backend/oauth/token 通过添加到标题:

  

授权,基本xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

以及URL中的以下参数:

  

的client_id = backendClient

     

范围=读

     

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?

感谢。

1 个答案:

答案 0 :(得分:1)

这是我如何做到的(不使用Xamarin.Auth):

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

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