手动生成IdentityServer4引用令牌并保存到PersistedGrants表

问题描述 投票:2回答:1

我已经学习了IdentityServer4一周,并成功实现了一个简单的ResourceOwnedPassword流认证流程。

现在,我正在通过跟随this tutorial在IdentityServer4上实施Google身份验证

这就是我在做的事情:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    //...

    const string connectionString = @"Data Source=.\SQLEXPRESS;database=IdentityServer4.Quickstart.EntityFramework-2.0.0;trusted_connection=yes;";
    var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

    services.AddIdentityServer()
        .AddDeveloperSigningCredential()
        .AddProfileService<IdentityServerProfileService>()
        .AddResourceOwnerValidator<IdentityResourceOwnerPasswordValidator>()
        // this adds the config data from DB (clients, resources)
        .AddConfigurationStore(options =>
        {
            options.ConfigureDbContext = builder =>
            {
                builder.UseSqlServer(connectionString,
                    sql => sql.MigrationsAssembly(migrationsAssembly));
            };

        })
        // this adds the operational data from DB (codes, tokens, consents)
        .AddOperationalStore(options =>
        {
            options.ConfigureDbContext = builder =>
                builder.UseSqlServer(connectionString,
                    sql => sql.MigrationsAssembly(migrationsAssembly));
            // this enables automatic token cleanup. this is optional.
            options.EnableTokenCleanup = true;
            options.TokenCleanupInterval = 30;
        });

    // Add jwt validation.
    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddIdentityServerAuthentication(options =>
        {
            // base-address of your identityserver
            options.Authority = "https://localhost:44386";

            options.ClaimsIssuer = "https://localhost:44386";

            // name of the API resource
            options.ApiName = "api1";
            options.ApiSecret = "secret";

            options.RequireHttpsMetadata = false;

            options.SupportedTokens = SupportedTokens.Reference;

        });

    //...
}

** Google控制器(用于处理来自Google的退回令牌**

public class GLoginController : Controller
    {
        #region Properties

        private readonly IPersistedGrantStore _persistedGrantStore;

        private readonly IUserFactory _userFactory;

        private readonly IBaseTimeService _baseTimeService;

        private readonly ITokenCreationService _tokenCreationService;

        private readonly IReferenceTokenStore _referenceTokenStore;

        private readonly IBaseEncryptionService _baseEncryptionService;

        #endregion

        #region Constructor

        public GLoginController(IPersistedGrantStore persistedGrantStore,
            IBaseTimeService basetimeService,
            ITokenCreationService tokenCreationService,
            IReferenceTokenStore referenceTokenStore,
            IBaseEncryptionService baseEncryptionService,
            IUserFactory userFactory)
        {
            _persistedGrantStore = persistedGrantStore;
            _baseTimeService = basetimeService;
            _userFactory = userFactory;
            _tokenCreationService = tokenCreationService;
            _referenceTokenStore = referenceTokenStore;
            _baseEncryptionService = baseEncryptionService;
        }

        #endregion

        #region Methods

        [HttpGet("login")]
        [AllowAnonymous]
        public IActionResult Login()
        {
            var authenticationProperties = new AuthenticationProperties
            {
                RedirectUri = "/api/google/handle-external-login"
            };

            return Challenge(authenticationProperties, "Google");
        }

        [HttpGet("handle-external-login")]
        //[Authorize("ExternalCookie")]
        [AllowAnonymous]
        public async Task<IActionResult> HandleExternalLogin()
        {
            //Here we can retrieve the claims
            var authenticationResult = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
            var principal = authenticationResult.Principal;

            var emailAddress = principal.FindFirst(ClaimTypes.Email)?.Value;
            if (string.IsNullOrEmpty(emailAddress))
                return NotFound(new ApiMessageViewModel("Email is not found"));

            // Find user by using username.
            var loadUserConditions = new LoadUserModel();
            loadUserConditions.Usernames = new HashSet<string> { emailAddress };
            loadUserConditions.Pagination = new PaginationValueObject(1, 1);

            // Find users asynchronously.
            var loadUsersResult = await _userFactory.FindUsersAsync(loadUserConditions);
            var user = loadUsersResult.FirstOrDefault();

            // User is not defined.
            if (user == null)
            {
                user = new User(Guid.NewGuid(), emailAddress);
                user.Email = emailAddress;
                user.HashedPassword = _baseEncryptionService.Md5Hash("abcde12345-");
                user.JoinedTime = _baseTimeService.DateTimeUtcToUnix(DateTime.UtcNow);
                user.Kind = UserKinds.Google;
                user.Status = UserStatuses.Active;

                //await _userFactory.AddUserAsync(user);
            }
            else
            {
                // User is not google account.
                if (user.Kind != UserKinds.Google)
                    return Forbid("User is not allowed to access system.");
            }

            var token = new Token(IdentityServerConstants.TokenTypes.IdentityToken);
            var userCredential = new UserCredential(user);

            token.Claims = userCredential.GetClaims();
            token.AccessTokenType = AccessTokenType.Reference;
            token.ClientId = "ro.client";
            token.CreationTime = DateTime.UtcNow;
            token.Audiences = new[] {"api1"};
            token.Lifetime = 3600;


            return Ok();
        }

        #endregion
    }

一切都很好,我可以从Google OAuth2返回索赔,使用Google电子邮件地址在数据库中查找用户,如果他们没有任何帐户,请注册。

我的问题是:如何使用我在HandleExternalLogin方法中收到的Google OAuth2声明来生成参考令牌,将其保存到PersistedGrants表并返回到客户端。

这意味着当用户访问https://localhost:44386/api/google/login后,在重定向到Google同意屏幕后,他们可以接收由access_token生成的refresh_tokenIdentityServer4

谢谢,

c# asp.net-identity identityserver4 asp.net-core-2.1
1个回答
0
投票
  • 在IdentityServer中,令牌的种类(引用的jwt)是可配置的for each client(应用程序),请求令牌。
  • AccessTokenType.Reference适用于TokenTypes.AccessToken而不是TokenTypes.IdentityToken,就像你的片段一样。

一般来说,遵循original quickstart更简单,然后根据您的需要扩展the generic code。我现在在上面的代码片段中看到的只是您的特定内容,而不是默认部分,负责创建IdSrv会话并重定向回客户端。

如果您仍想手动创建令牌:

  • ITokenService注入您的控制器。
  • 修复我上面提到的错误:TokenTypes.AccessToken而不是 TokenTypes.IdentityToken
  • 打电话给var tokenHandle = await TokenService.CreateAccessTokenAsync(token);

tokenHandlePersistedGrantStore的关键

© www.soinside.com 2019 - 2024. All rights reserved.