You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.4 KiB
62 lines
2.4 KiB
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using OpenIddict.Abstractions;
|
|
using OpenIddict.Server.AspNetCore;
|
|
using static OpenIddict.Abstractions.OpenIddictConstants;
|
|
|
|
namespace Company.Server.Controllers;
|
|
|
|
public class UserinfoController(UserManager<IdentityUser> userManager) : Controller
|
|
{
|
|
[Authorize(AuthenticationSchemes = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)]
|
|
[HttpGet("~/connect/userinfo"), HttpPost("~/connect/userinfo")]
|
|
[IgnoreAntiforgeryToken, Produces("application/json")]
|
|
public async Task<IActionResult> Userinfo()
|
|
{
|
|
var user = await userManager.FindByIdAsync(User.GetClaim(Claims.Subject)!);
|
|
if (user is null)
|
|
{
|
|
return Challenge(
|
|
authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
|
|
properties: new AuthenticationProperties(new Dictionary<string, string?>
|
|
{
|
|
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidToken,
|
|
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
|
|
"The specified access token is bound to an account that no longer exists."
|
|
}));
|
|
}
|
|
|
|
var claims = new Dictionary<string, object?>(StringComparer.Ordinal)
|
|
{
|
|
// Note: the "sub" claim is a mandatory claim and must be included in the JSON response.
|
|
[Claims.Subject] = await userManager.GetUserIdAsync(user)
|
|
};
|
|
|
|
if (User.HasScope(Scopes.Profile))
|
|
{
|
|
claims[Claims.Name] = await userManager.GetUserNameAsync(user);
|
|
claims[Claims.PreferredUsername] = await userManager.GetUserNameAsync(user);
|
|
}
|
|
|
|
if (User.HasScope(Scopes.Email))
|
|
{
|
|
claims[Claims.Email] = await userManager.GetEmailAsync(user);
|
|
claims[Claims.EmailVerified] = await userManager.IsEmailConfirmedAsync(user);
|
|
}
|
|
|
|
if (User.HasScope(Scopes.Phone))
|
|
{
|
|
claims[Claims.PhoneNumber] = await userManager.GetPhoneNumberAsync(user);
|
|
claims[Claims.PhoneNumberVerified] = await userManager.IsPhoneNumberConfirmedAsync(user);
|
|
}
|
|
|
|
if (User.HasScope(Scopes.Roles))
|
|
{
|
|
claims[Claims.Role] = await userManager.GetRolesAsync(user);
|
|
}
|
|
|
|
return Ok(claims);
|
|
}
|
|
}
|
|
|