private async Task <HttpResponseMessage> SendAuthenticatedRequest(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            await EnsureValidAccessTokenAsync(cancellationToken);

            request.Headers.Authorization = new AuthenticationHeaderValue(AccessTokenTypeParser.ToString(_accessToken.Type), _accessToken.Value);
            return(await base.SendAsync(request, cancellationToken));
        }
Example #2
0
        private async Task WriteAccessTokenAsync(IOwinResponse response, string accessToken, AccessTokenType accessTokenType, TimeSpan expiresIn)
        {
            response.ContentType = "application/json; charset=UTF-8";

            var tokenObj = new JObject(
                new JProperty("access_token", accessToken),
                new JProperty("token_type", AccessTokenTypeParser.ToString(accessTokenType)),
                new JProperty("expires_in", (int)expiresIn.TotalSeconds));

            await response.WriteAsync(tokenObj.ToString());
        }
Example #3
0
        public static void SetAuthenticationFailed(
            this IOwinResponse response,
            AccessTokenType type,
            string error,
            string errorDescription = null,
            string requiredScope    = null)
        {
            if (error == null)
            {
                throw new ArgumentNullException(nameof(error));
            }

            if (error == AuthenticationErrorCodes.InvalidRequest)
            {
                response.StatusCode = 400;
            }

            if (error == AuthenticationErrorCodes.InvalidToken)
            {
                response.StatusCode = 401;
            }

            if (error == AuthenticationErrorCodes.InsufficentScope)
            {
                response.StatusCode = 403;
            }

            response.OnSendingHeaders(rsp =>
            {
                var sb = new StringBuilder($@"{AccessTokenTypeParser.ToString(type)} error=""{error}""");

                if (!string.IsNullOrEmpty(errorDescription))
                {
                    sb.Append($@",error_description=""{errorDescription}""");
                }

                if (!string.IsNullOrEmpty(requiredScope))
                {
                    sb.Append($@",scope=""{requiredScope}""");
                }

                ((IOwinResponse)rsp).Headers.Set(
                    "WWW-Authenticate",
                    sb.ToString()
                    );
            }, response);
        }