WebApi ASP.NET身份Facebook登录
|
在用于asp.net身份的facebook身份验证流程中,facebook oath对话框将一个代码而不是访问令牌附加到redirect_url,以便服务器可以通过http:// localhost:49164 / signin-facebook交换此代码作为访问令牌。 code = …& state = …. 我的问题是,我的客户是一个移动应用程序使用的facebook sdk,直接给我一个访问令牌。 Facebook说使用sdk总是给你一个访问令牌,所以我可以直接给web API访问令牌。我明白这不是很安全,但它是可能的? 解决方法我不知道你是否终于找到了解决方案,但我想做一些很相似的事情,我仍然把拼图的部分放在一起。我试图张贴这作为一个评论,而不是一个答案,因为我不提供一个真正的解决方案,但它太长。 显然,所有WebAPI Owin OAuth选项都是基于浏览器的,也就是说他们需要大量的浏览器重定向请求,不适合本地移动应用程序(我的情况)。 通过使用图形调用返回的信息,您可以检查用户是否已经注册。 编辑: 更新: public partial class Startup
{
/// <summary>
/// This part has been added to have an API endpoint to authenticate users that accept a Facebook access token
/// </summary>
static Startup()
{
PublicClientId = "self";
//UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
UserManagerFactory = () =>
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
userManager.UserValidator = new UserValidator<ApplicationUser>(userManager) { AllowOnlyAlphanumericUserNames = false };
return userManager;
};
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),Provider = new ApplicationOAuthProvider(PublicClientId,UserManagerFactory),AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),AllowInsecureHttp = true
};
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
OAuthBearerOptions.AccessTokenFormat = OAuthOptions.AccessTokenFormat;
OAuthBearerOptions.AccessTokenProvider = OAuthOptions.AccessTokenProvider;
OAuthBearerOptions.AuthenticationMode = OAuthOptions.AuthenticationMode;
OAuthBearerOptions.AuthenticationType = OAuthOptions.AuthenticationType;
OAuthBearerOptions.Description = OAuthOptions.Description;
OAuthBearerOptions.Provider = new CustomBearerAuthenticationProvider();
OAuthBearerOptions.SystemClock = OAuthOptions.SystemClock;
}
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static Func<UserManager<ApplicationUser>> UserManagerFactory { get; set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication,please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
[Initial boilerplate code]
OAuthBearerAuthenticationExtensions.USEOAuthBearerAuthentication(app,OAuthBearerOptions);
[More boilerplate code]
}
}
public class CustomBearerAuthenticationProvider : OAuthBearerAuthenticationProvider
{
public override Task ValidateIdentity(OAuthValidateIdentityContext context)
{
var claims = context.Ticket.Identity.Claims;
if (claims.Count() == 0 || claims.Any(claim => claim.Issuer != "Facebook" && claim.Issuer != "LOCAL_AUTHORITY" ))
context.Rejected();
return Task.FromResult<object>(null);
}
}
进入AccountController,我添加了以下操作 [HttpPost]
[AllowAnonymous]
[Route("FacebookLogin")]
public async Task<IHttpActionResult> FacebookLogin(string token)
{
[Code to validate input...]
var tokenExpirationTimeSpan = TimeSpan.FromDays(14);
ApplicationUser user = null;
// Get the fb access token and make a graph call to the /me endpoint
// Check if the user is already registered
// If yes retrieve the user
// If not,register it
// Finally sign-in the user: this is the key part of the code that creates the bearer token and authenticate the user
var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name,user.Id,null,"Facebook"));
// This claim is used to correctly populate user id
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier,"LOCAL_AUTHORITY"));
AuthenticationTicket ticket = new AuthenticationTicket(identity,new AuthenticationProperties());
var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
var accesstoken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
Authentication.SignIn(identity);
// Create the response
JObject blob = new JObject(
new JProperty("userName",user.UserName),new JProperty("access_token",accesstoken),new JProperty("token_type","bearer"),new JProperty("expires_in",tokenExpirationTimeSpan.TotalSeconds.ToString()),new JProperty(".issued",ticket.Properties.IssuedUtc.ToString()),new JProperty(".expires",ticket.Properties.ExpiresUtc.ToString())
);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(blob);
// Return OK
return Ok(blob);
}
而已。我发现与经典/令牌端点响应的唯一的区别是承载令牌稍短,过期和发布日期在UTC,而不是在GMT(至少在我的机器上)。 我希望这有帮助! (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc – ASP.NET MVC如何知道方法是一种动作方法?
- 解决asp.net Sharepoint无法连接发布自定义字符串处理程序,
- asp.net – 如何强制实体框架插入标识列?
- ASP.NET MVC 2加载部分视图使用jQuery – 没有客户端验证
- 如何在ASP.NET Core 2.0中设置多个身份验证方案?
- 如何基于.NET Core创建ASP.NET项目,而不是基于完整的框架?
- asp.net-mvc – 用于字符串的ASP.NET MVC显示模板用于整数
- asp.net-mvc – Asp.Net MVC Ajax.BeginForm没有通过Ajax提
- asp.net – RadGrid在Visual Studio 2013中打开应用程序时,
- asp.net – 如何在Azure网站上设置machineKey
- ASP.Net便携式服务器
- 实体框架 – 实体框架验证混淆 – 最大字符串长度
- asp.net-mvc – Dotnetopenauth使用自定义身份提
- asp.net-membership – 将ASP.NET成员资格提供程
- asp.net-mvc – 如何判断MVC AsyncController线程
- ASP.NET MVC 2.0 – RenderPartial和RenderActio
- .NET Framework 3.5中有哪些有用的新ASP.NET功能
- asp.net – MVC-Mini-Profiler – Web窗体 – 找
- asp.net – 确定所需服务器数量的最佳方法
- asp.net-mvc – 用于字符串的ASP.NET MVC显示模板
