All Downloads are FREE. Search and download functionalities are using the official Maven repository.

csharp.auth.OAuthAuthenticator.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
{{>partial_header}}

using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;

namespace {{packageName}}.Client.Auth
{
    /// 
    /// An authenticator for OAuth2 authentication flows
    /// 
    public class OAuthAuthenticator : AuthenticatorBase
    {
        readonly string _tokenUrl;
        readonly string _clientId;
        readonly string _clientSecret;
        readonly string{{nrt?}} _scope;
        readonly string _grantType;
        readonly JsonSerializerSettings _serializerSettings;
        readonly IReadableConfiguration _configuration;

        /// 
        /// Initialize the OAuth2 Authenticator
        /// 
        public OAuthAuthenticator(
            string tokenUrl,
            string clientId,
            string clientSecret,
            string{{nrt?}} scope,
            OAuthFlow? flow,
            JsonSerializerSettings serializerSettings,
            IReadableConfiguration configuration) : base("")
        {
            _tokenUrl = tokenUrl;
            _clientId = clientId;
            _clientSecret = clientSecret;
            _scope = scope;
            _serializerSettings = serializerSettings;
            _configuration = configuration;

            switch (flow)
            {
                /*case OAuthFlow.ACCESS_CODE:
                    _grantType = "authorization_code";
                    break;
                case OAuthFlow.IMPLICIT:
                    _grantType = "implicit";
                    break;
                case OAuthFlow.PASSWORD:
                    _grantType = "password";
                    break;*/
                case OAuthFlow.APPLICATION:
                    _grantType = "client_credentials";
                    break;
                default:
                    break;
            }
        }

        /// 
        /// Creates an authentication parameter from an access token.
        /// 
        /// Access token to create a parameter from.
        /// An authentication parameter.
        protected override async ValueTask GetAuthenticationParameter(string accessToken)
        {
            var token = string.IsNullOrEmpty(Token) ? await GetToken().ConfigureAwait(false) : Token;
            return new HeaderParameter(KnownHeaders.Authorization, token);
        }

        /// 
        /// Gets the token from the OAuth2 server.
        /// 
        /// An authentication token.
        async Task GetToken()
        {
            var client = new RestClient(_tokenUrl,
                configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration)));

            var request = new RestRequest()
                .AddParameter("grant_type", _grantType)
                .AddParameter("client_id", _clientId)
                .AddParameter("client_secret", _clientSecret);

            if (!string.IsNullOrEmpty(_scope))
            {
                request.AddParameter("scope", _scope);
            }

            var response = await client.PostAsync(request).ConfigureAwait(false);
            
            // RFC6749 - token_type is case insensitive.
            // RFC6750 - In Authorization header Bearer should be capitalized.
            // Fix the capitalization irrespective of token_type casing.
            switch (response.TokenType?.ToLower())
            {
                case "bearer":
                    return $"Bearer {response.AccessToken}";
                default:
                    return $"{response.TokenType} {response.AccessToken}";
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy