コード例 #1
0
        public async Task <IActionResult> Post([FromBody] RegistryCredentials credentials)
        {
            // must specify a registry
            if (string.IsNullOrEmpty(credentials.Registry))
            {
                return(Unauthorized());
            }

            // deny requests for foreign instances, if configured
            if (!string.IsNullOrEmpty(Config.Registry) && credentials.Registry.ToLowerInvariant() != Config.Registry.ToLowerInvariant())
            {
                return(Unauthorized());
            }
            try
            {
                credentials.Registry = RegistryCredentials.DeAliasDockerHub(credentials.Registry);
                var handler = new AuthHandler(cache, Config, loggerFactory.CreateLogger <AuthHandler>());
                await handler.LoginAsync(credentials.Registry, credentials.Username, credentials.Password);

                var json = JsonConvert.SerializeObject(credentials);

                // publicly visible parameters for session validation
                var headers = new Dictionary <string, object>
                {
                    { "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
                    { "exp", DateTimeOffset.UtcNow.ToUnixTimeSeconds() + Config.AuthTokenLifetime },
                    { "reg", credentials.Registry }
                };

                var token = new Token
                {
                    Usr = credentials.Username,
                    Pwd = credentials.Password,
                    Reg = credentials.Registry,
                    Iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                    Exp = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + Config.AuthTokenLifetime
                };

                var jwe = Jose.JWT.Encode(token, crypto, JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM, extraHeaders: headers);

                return(Ok(new
                {
                    token = jwe
                }));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error authenticating token request.");
                return(Unauthorized());
            }
        }