【问题标题】:Authenticate android app to call web api service验证 android 应用程序以调用 web api 服务
【发布时间】:2014-11-27 14:56:46
【问题描述】:
我有一个 android 应用程序,它有一个学生登录表单,我想根据 sql server 中存储的数据在 web api 上检查学生凭证
我在网上搜索并观看了很多视频,这些视频谈论了很多场景,但对我没有任何帮助。
我想要的只是对我的休息服务进行自定义验证(所以我应该为每个请求发送凭据)
- asp.net web api服务应该怎么做
- 如何在 android 应用程序中实现它
【问题讨论】:
标签:
android
asp.net
authentication
asp.net-web-api
http-authentication
【解决方案1】:
似乎您没有搜索“基于 Web API 令牌的身份验证”;)无论如何,您需要实现的内容非常简单。
您需要使用 OAuth 2.0 Resource Owner Credentials Flow,这意味着您只想为特定端点提供一次用户名/密码,即(/token),然后如果用户名/密码有效,您将获得称为 Bearer Access Token 的东西。
此令牌在指定期限内有效,您可以在 Web API 中进行配置。
获得访问令牌后,您需要将其安全地存储在您的 android 应用程序中,然后使用 Authorization 标头(Bearer scheme(.
我写了非常详细的帖子,100% 涵盖了你的场景。请查看Token Based Authentication 的帖子,如果您需要进一步的帮助,请告诉我。
【解决方案2】:
我已经使用基本身份验证来保证安全,所以我应该提供
的base64编码
username:password
在每个请求的标头中如下
授权:基本'编码用户名:密码
httpGet.setHeader("Authorization", "Basic "+encodeUsernameAndPassword());
在服务器端我已经实现了消息处理程序
public class BasicAuthenticationHandler : DelegatingHandler
{
public readonly IAuthenticationService authService;
public BasicAuthenticationHandler(IAuthenticationService service)
{
this.authService = service;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
AuthenticationHeaderValue authHeader = request.Headers.Authorization;
if (authHeader == null || authHeader.Scheme != "Basic")
{
return Unauthorized(request);
}
string encodedCredentials = authHeader.Parameter;
var credentialsBytes = Convert.FromBase64String(encodedCredentials);
var credentials = Encoding.ASCII.GetString(credentialsBytes).Split(':');
if (!authService.Authenticate(credentials[0], credentials[1]))
{
return Unauthorized(request);
}
string[] roles = null;//todo
IIdentity identity = new GenericIdentity(credentials[0], "Basic");
IPrincipal user = new GenericPrincipal(identity, roles);
HttpContext.Current.User = user;
return base.SendAsync(request, cancellationToken);
}