Created
March 21, 2024 06:03
-
-
Save altbodhi/9d8703c608a4fba1236ca74eeb5d4386 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// controller | |
[HttpGet("tgCheckWebAppAuth")] | |
public async Task<IActionResult> CheckWebAppAuth([FromQuery] Dictionary<string, string> userData) | |
{ | |
var user = telegramLoginUrl.CheckWebAppTelegramAuthorization(userData); | |
if (await Invalid(user)) return Unauthorized(); | |
await SignIn(user, [new Claim("Source", "TelegramWebApp")]); | |
return Ok(user); | |
} | |
/// Test.razor (route baseURI to /CoolApp) | |
async Task Login() | |
{ | |
var auth_state = await authStateProv.GetAuthenticationStateAsync(); | |
if ((auth_state.User.Identity != null && auth_state.User.Identity.IsAuthenticated)) | |
return; | |
var str = await JS.InvokeAsync<string>("eval", "window.Telegram.WebApp.initData"); | |
var user = await http_client.GetFromJsonAsync<TgUser>($"{nm.BaseUri}api/TgLoginUrl/tgCheckWebAppAuth?{str}"); | |
nm.NavigateTo(nm.BaseUri, true); | |
} | |
/// server class PersistingRevalidatingAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider | |
private async Task OnPersistingAsync() | |
{ | |
logger.LogWarning("OnPersistingAsync"); | |
if (authenticationStateTask is null) | |
{ | |
throw new UnreachableException($"Authentication state not set in {nameof(OnPersistingAsync)}()."); | |
} | |
var authenticationState = await authenticationStateTask; | |
var principal = authenticationState.User; | |
var id = principal.Identities.FirstOrDefault(x => x.IsAuthenticated); | |
if (id == null) | |
{ | |
logger.LogWarning("OnPersistingAsync principal.Identities.Count() = {x}", principal.Identities.Count()); | |
/// !!!! <= always here finish | |
return; | |
} | |
var userId = id.FindFirst(options.ClaimsIdentity.UserIdClaimType)?.Value; | |
var email = id.FindFirst(options.ClaimsIdentity.EmailClaimType)?.Value; | |
var name = id.FindFirst(options.ClaimsIdentity.UserNameClaimType)?.Value; | |
logger.LogWarning("OnPersistingAsync principal {principal} IsAuthenticated={IsAuthenticated}, {name}, {userId}, {email}", id, id.IsAuthenticated, name, userId, email); | |
if (principal.Identity?.IsAuthenticated == true) | |
{ | |
if (userId != null && email != null && name != null) | |
{ | |
state.PersistAsJson(nameof(UserInfo), new UserInfo | |
{ | |
UserId = userId, | |
Email = email, | |
Name = name | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment