.net-core - 是否有可能仅使用用户对象返回 access_token?

标签 .net-core identityserver4

我正在实现一项功能,其中 access_token 将通过电子邮件发送,在这种情况下,我需要生成此 token ,并在访问通过电子邮件传递的链接时对用户进行身份验证。

public async Task<IActionResult> GetLink () 
{
    var user = await userManager.FindByEmailAsync("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660302130714020926120315124805090b480414" rel="noreferrer noopener nofollow">[email protected]</a>"); // is active user created
    if (user != null)
    {
        var ident = await userManager.GetAuthenticationTokenAsync(user, "Test", "access_token");
        return Ok(ident);
    }
    return NoContent();
}

根据预期的研究会是这样的,但这不是用持久化数据完成的,而且我的模型不允许这样做,有人知道如何持久化吗?或者甚至只是返回 token ?

我认为这是一种不好的行为,不是 Not Acceptable ,但是,在这种情况下,我的用户没有访问密码,也许有必要使用 token 或其他模式登录。 这是一个非常简单的流程,该链接将是一个授予操作的链接(基本上只有读取权限),并且该链接将仅通过电子邮件发送给用户。

最佳答案

上述问题可以通过如下方式解决:

[HttpGet("get_token")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetUserToken([FromServices] ITokenService TS, [FromServices] IUserClaimsPrincipalFactory<EkyteUser> principalFactory,
[FromServices] IdentityServerOptions options)
{           
    var Request = new TokenCreationRequest();                        
    var user = await userManager.FindByIdAsync(User.GetSubjectId());
    var IdentityPricipal = await principalFactory.CreateAsync(user);
    var IdServerPrincipal = IdentityServerPrincipal.Create(user.Id.ToString(), user.UserName);

    Request.Subject = IdServerPrincipal;
    Request.IncludeAllIdentityClaims = true;
    Request.ValidatedRequest = new ValidatedRequest();
    Request.ValidatedRequest.Subject = Request.Subject;
    Request.ValidatedRequest.SetClient(Config.GetClient());
    Request.Resources = new Resources(Config.GetResources(), Config.GetApiResources());
    Request.ValidatedRequest.Options = options;            
    var Token = await TS.CreateAccessTokenAsync(Request);
    Token.Issuer = "http://" + HttpContext.Request.Host.Value;

    var TokenValue = await TS.CreateSecurityTokenAsync(Token);
    return Ok(TokenValue);
}

有必要识别用户、设置必要的资源以及正在访问的客户端。之后,只需包含访问主机即可生成 token 。

关于.net-core - 是否有可能仅使用用户对象返回 access_token?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45803128/

相关文章:

mongodb - 使用 DotNet Core 的 MongoDB 驱动程序时出现异常

.net - .NET 与 .NET Core 2 的不同 P/Invoke 入口点

azure - NLog with Application Insights - 将异常记录为异常而不是跟踪

identityserver4 - IdentityServer4 的用户注册过程

c# - IdentityServer4 AddSigningCredentials 与证书

c# - ASP.NET 核心 WebSocket

c# - 如何从 ASP.NET Core 3.1 中的 appsettings.json 读取整个部分?

c# - Identity Server 4 v3.1.2 UserInteraction LoginUrl 不起作用

authentication - 我们可以在 Identity Server 4 中设置静态颁发者吗?

asp.net - PostLogoutRedirectUri 在带有 SPA 的身份服务器 4 中始终为空(Angular 7 OIDC 客户端)