Я реализую аутентификацию Google в своем приложении веб-форм ASP.NET с помощью OWIN. Однако после входа в систему Google я не могу получить объект loginInfo в методе ExternalLoginCallback. LoginInfo всегда имеет значение null, что не позволяет мне получить доступ к информации пользователя.
Реализация кода:
Метод настройки
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/login.aspx"),
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
var googleAuthOptions = new GoogleOAuth2AuthenticationOptions
{
ClientId = "ClientId", // Replace with your actual ClientId
ClientSecret = "ClientSecret", // Replace with your actual ClientSecret
CallbackPath = new PathString("/signin-google"),
Provider = new GoogleOAuth2AuthenticationProvider
{
OnAuthenticated = context =>
{
var emailClaim = context.Identity.FindFirst(ClaimTypes.Email);
if (emailClaim != null)
{
context.Identity.AddClaim(new System.Security.Claims.Claim("Email", emailClaim.Value));
}
return Task.FromResult(0);
}
}
};
googleAuthOptions.Scope.Add("email");
googleAuthOptions.Scope.Add("profile");
googleAuthOptions.Scope.Add("openid");
app.UseGoogleAuthentication(googleAuthOptions);
}
ExternalLogin Method
public void ExternalLogin(object sender, EventArgs e)
{
var properties = new AuthenticationProperties { RedirectUri = "/login.aspx/ExternalLoginCallback" };
HttpContext.Current.GetOwinContext().Authentication.Challenge(properties, "Google");
HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true;
}
ExternalLoginCallback Method
public async Task ExternalLoginCallback()
{
try
{
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var loginInfo = await authenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
lbl_warning.Text = "User not found.";
lbl_warning.Visible = true; // Ensure the warning label is visible
return;
}
var emailClaim = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
// Additional logic to handle the user's email claim can be added here
}
catch (Exception ex)
{
lbl_warning.Text = "An error occurred: " + ex.Message;
lbl_warning.Visible = true; // Show the error message
}
}
Redirect URI
The redirect URI I am using in the Google API Console is:
http://localhost:50180/signin-google
Подробнее здесь: https://stackoverflow.com/questions/790 ... -web-forms
Невозможно получить информацию для входа в систему после аутентификации Google в веб-формах ASP.NET ⇐ C#
Место общения программистов C#
1727158407
Anonymous
Я реализую аутентификацию Google в своем приложении веб-форм ASP.NET с помощью OWIN. Однако после входа в систему Google я не могу получить объект loginInfo в методе ExternalLoginCallback. LoginInfo всегда имеет значение null, что не позволяет мне получить доступ к информации пользователя.
Реализация кода:
[b]Метод настройки[/b]
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/login.aspx"),
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
var googleAuthOptions = new GoogleOAuth2AuthenticationOptions
{
ClientId = "ClientId", // Replace with your actual ClientId
ClientSecret = "ClientSecret", // Replace with your actual ClientSecret
CallbackPath = new PathString("/signin-google"),
Provider = new GoogleOAuth2AuthenticationProvider
{
OnAuthenticated = context =>
{
var emailClaim = context.Identity.FindFirst(ClaimTypes.Email);
if (emailClaim != null)
{
context.Identity.AddClaim(new System.Security.Claims.Claim("Email", emailClaim.Value));
}
return Task.FromResult(0);
}
}
};
googleAuthOptions.Scope.Add("email");
googleAuthOptions.Scope.Add("profile");
googleAuthOptions.Scope.Add("openid");
app.UseGoogleAuthentication(googleAuthOptions);
}
ExternalLogin Method
public void ExternalLogin(object sender, EventArgs e)
{
var properties = new AuthenticationProperties { RedirectUri = "/login.aspx/ExternalLoginCallback" };
HttpContext.Current.GetOwinContext().Authentication.Challenge(properties, "Google");
HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true;
}
ExternalLoginCallback Method
public async Task ExternalLoginCallback()
{
try
{
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var loginInfo = await authenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
lbl_warning.Text = "User not found.";
lbl_warning.Visible = true; // Ensure the warning label is visible
return;
}
var emailClaim = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
// Additional logic to handle the user's email claim can be added here
}
catch (Exception ex)
{
lbl_warning.Text = "An error occurred: " + ex.Message;
lbl_warning.Visible = true; // Show the error message
}
}
Redirect URI
The redirect URI I am using in the Google API Console is:
http://localhost:50180/signin-google
Подробнее здесь: [url]https://stackoverflow.com/questions/79017194/unable-to-retrieve-logininfo-after-google-authentication-in-asp-net-web-forms[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия