2023-02-15 271
我在我们现有的ASP.NET MVC网站项目中获取社交登录时遇到问题.正常客户(我们的自定义DB)登录工作正常.出于某种原因,iAuthenticationManager上的挑战方法不会重定向到ExternalLoginCallback操作,以便正确的社交登录提供商可以提示登录.现在,挑战方法是重定向到accountController登录操作和登录页面加载后的URL,如下所示:
http://localhost/Account/Login?ReturnUrl=%2fAccount%2fExternalLogin
我已经在有关.我经历了本教程首页在代码,设置和创建概念证明中获取理解.然后我与本教程将新标识API融入我们现有的网站并替换我们的旧系统.web.security.membershipprovider 实施.以下是代码的一些快照.
startup.auth.cs
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
//app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator
.OnValidateIdentity<ApplicationUserManager, IdentityUser, int>(validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (id) => (Int32.Parse(id.GetUserId())))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
FacebookAuthenticationOptions fbAuthenticationOptions = new FacebookAuthenticationOptions();
fbAuthenticationOptions.Scope.Add("email");
fbAuthenticationOptions.AppId = "XXXXXX";
fbAuthenticationOptions.AppSecret = "YYYYYYY";
fbAuthenticationOptions.Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
foreach (var claim in context.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
string claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
};
fbAuthenticationOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
app.UseFacebookAuthentication(fbAuthenticationOptions);
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
challengeresult类accountcontroller.cs中
private class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
IOwinContext owinContext = context.HttpContext.GetOwinContext();
IAuthenticationManager authenticationManager = owinContext.Authentication;
try
{
authenticationManager.Challenge(properties, LoginProvider);
}
catch (Exception ex)
{
throw;
}
}
}
accountController.cs中的ExternalLogin
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
accountallogincallback在accountcontroller.cs
中
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var user = await UserManager.FindAsync(loginInfo.Login);
if (user != null)
{
await SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
else
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
string email = info.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:email").Value;
string firstName = info.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:first_name").Value;
string lastName = info.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:last_name").Value;
// If the user does not have an account, then prompt the user to create an account
RegisterDisplay registerDisplay = new RegisterDisplay
{
Email = email,
Agree = true,
UserName = loginInfo.DefaultUserName,
MailingAddress = new MailingAddress() { FirstName = firstName, LastName = lastName }
};
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
TempData["RegisterDisplay"] = registerDisplay;
return View("Register", returnUrl);
}
}
这个让我难以置灭了,因为我没有看到调试器中抛出任何错误.如果需要显示任何其他代码,请告诉我.任何帮助将不胜感激.谢谢.
确定a co-worker 我认为解决了挑战方法跳过的问题ExternalLoginCallback.这是一个web.config问题,我忘了用原来的问题发布.我们需要修改身份验证模式为无.它用来形成,这导致网站劫持挑战电话.
原始系统.Web.config中的Web部分
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
</system.web>
修复系统.Web.config中的Web部分
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>
我们也必须将删除子组添加到system.webserver模块部分
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthenticationModule" />
</modules>
</system.webServer>
现在一切都是重定向的.
在我的情况下,挑战简而言之只是rovindunt 401 (Unauthorized):
HttpContext.GetOwinContext().Authentication.Challenge("Application")
要完成它,我必须将其更改为:
HttpContext.GetOwinContext().Authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie)
因为这是我如何在Startup上配置我的cookie身份验证:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, // <---- I have to pass the same value as `AuthenticationType` to the `Challenge` method
AuthenticationMode = AuthenticationMode.Passive,
LoginPath = new PathString("/Account/Login"),
Provider = cookieAuthenticationProvider
});
Challenge方法仅使用注册的身份验证方法工作,并且它通过配置的AuthenticationType属性来重新调整它们.
不确定您的代码均恰好是错误的,而是检查用以下代码下面的代码替换代码.几个月前我有同样的问题,原因在添加Facebook应用程序凭据之前添加了电子邮件范围.
var facebookOptions = new FacebookAuthenticationOptions()
{
AppId = "FacebookAppId",
AppSecret = "FacebookAppSecret"
};
facebookOptions.Scope.Add("email");
// Add your claims, provider details here.
app.UseFacebookAuthentication(facebookOptions);
以上所述是小编给大家介绍的IAuthenticationManager.Challenge没有调用ExternalLoginCallback,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!
原文链接:https://77isp.com/post/33801.html
=========================================
https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态