手动生成IdentityServer4参考令牌并保存到PersistedGrants表

时间:2019-04-02 03:17:09

标签: c# asp.net-identity identityserver4 asp.net-core-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

谢谢

1 个答案:

答案 0 :(得分:0)

  • 在IdentityServer中,令牌的种类(引用的jwt)为 可配置的for each client(应用程序),请求令牌。
  • AccessTokenType.ReferenceTokenTypes.AccessToken有效,不适用于 TokenTypes.IdentityToken,如您的代码段所示。

通常,遵循original quickstart然后扩展the generic code以满足您的需求会更简单。我现在在上面的代码段中看到的只是您的特定内容,而不是默认部分,它们负责创建IdSrv会话并将其重定向回客户端。

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

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

tokenHandlePersistedGrantStore

中的键