Example #1
0
        public AuthParams
        (
            OAuthGrantType grantType,
            ICollection <Scope> scopes,
            string clientId,
            string clientSecret   = "",
            ITokenStorage storage = null,
            string username       = "",
            string password       = ""
        )
        {
            if ((!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password)) && storage == null)
            {
                throw new Exception("You must implemet storage for refresh token");
            }

            if ((!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password)) && grantType != OAuthGrantType.Password)
            {
                throw new Exception("You are using wrong grant type, use password");
            }

            GrantType    = grantType;
            Scopes       = scopes;
            ClientId     = clientId;
            ClientSecret = clientSecret;
            Username     = username;
            Password     = password;
            Storage      = storage;
        }
        /// <summary>
        /// This method deserialises the response from an access token request and returns
        /// an <see cref="Credentials"/>object which can be persisted to credential storage
        /// </summary>
        /// <param name="restResponse">The Rest Response containing the access tokens</param>
        /// <param name="grantType">The OAuth grant type used to get specific tokens</param>
        /// <remarks>The response object is a JSON blob similar to
        /// {
        ///     "access_token":"VygNPcxVEG3...PSX",
        ///     "refresh_token":"NzE...nwud",
        ///     "id_token": "eyJ0...wAcQ",
        ///     "expires_in":"3600",
        ///     "token_type": "Bearer"
        /// }
        /// </remarks>
        private Credentials ExtractTokensFromResponse(IRestResponse restResponse, OAuthGrantType grantType)
        {
            Credentials credentials  = null;
            string      responseData = restResponse.Content;

            if (!String.IsNullOrWhiteSpace(responseData))
            {
                ExchangeAuthorizationCodeResponse response = JsonConvert.DeserializeObject <ExchangeAuthorizationCodeResponse>(responseData);

                string userEmail    = null;
                string userNickName = null;
                if (!string.IsNullOrEmpty(response.Id_Token))
                {
                    JwtSecurityToken token = new JwtSecurityToken(response.Id_Token);

                    Claim nickname = token.Claims.FirstOrDefault(x => x.Type.Equals("nickname", StringComparison.InvariantCultureIgnoreCase));
                    Claim name     = token.Claims.FirstOrDefault(x => x.Type.Equals("name", StringComparison.InvariantCultureIgnoreCase));

                    if (nickname != null)
                    {
                        userNickName = nickname.Value;
                    }

                    if (name != null)
                    {
                        userEmail = name.Value;
                    }
                }

                credentials = new Credentials
                {
                    AccessToken  = response.Access_Token,
                    UserNickName = userNickName,
                    UserEmail    = userEmail
                };

                switch (grantType)
                {
                case OAuthGrantType.AuthorizationCode:
                    credentials.RefreshToken = response.Refresh_Token;
                    break;

                // If grant type is refresh_token, persist the current refresh_token (until it's revoked)
                case OAuthGrantType.RefreshToken:
                    credentials.RefreshToken = myCredentials.RefreshToken;
                    break;
                }
            }

            return(credentials);
        }
Example #3
0
 /// <summary>
 /// Creates a new <see cref="TokenContext"/>.
 /// </summary>
 /// <param name="httpContext">The current <see cref="HttpContext"/>.</param>
 /// <param name="clientId">The client identifier of the application.</param>
 /// <param name="redirectUri">The redirect uri of the application.</param>
 /// <param name="clientSecret">Client sesret of the application.</param>
 /// <param name="authorizationCodeOrRefreshToken">Authorization code or refresh token provided by client application.</param>
 /// <param name="grantType">The OAuth grant type.</param>
 public TokenContext(HttpContext httpContext, string clientId, Uri redirectUri, string clientSecret, OAuthTicket authorizationCodeOrRefreshToken, OAuthGrantType grantType) : base(httpContext)
 {
     ClientId     = Guard.ArgumentNotNullOrWhiteSpace(clientId, nameof(clientId));
     RedirectUri  = Guard.ArgumentNotNull(redirectUri, nameof(redirectUri));
     ClientSecret = Guard.ArgumentNotNullOrWhiteSpace(clientSecret, nameof(clientSecret));
     GrantType    = grantType;
     if (grantType == OAuthGrantType.AuthorizationCode)
     {
         AuthorizationCode = Guard.ArgumentNotNull(authorizationCodeOrRefreshToken, nameof(authorizationCodeOrRefreshToken));
     }
     else
     {
         RefreshToken = Guard.ArgumentNotNull(authorizationCodeOrRefreshToken, nameof(authorizationCodeOrRefreshToken));
     }
 }
        public virtual async Task <TClient> RegisterClientAsync(string ownerUserName, string name, OAuthGrantType grantType)
        {
            Contract.Requires(!string.IsNullOrEmpty(name));

            TClient client = new TClient();

            client.GrantType = grantType;

            using (RijndaelManaged cryptoManager = new RijndaelManaged())
            {
                cryptoManager.GenerateKey();
                client.Id = BitConverter.ToString(cryptoManager.Key).Replace("-", string.Empty).ToLowerInvariant();

                cryptoManager.GenerateKey();
                client.Secret = BitConverter.ToString(cryptoManager.Key).Replace("-", string.Empty).ToLowerInvariant();
            }

            client.OwnerUserName = ownerUserName;
            client.Name          = name;
            client.SecretHash    = new PasswordHasher().HashPassword(client.Secret);
            client.DateAdded     = DateTimeOffset.Now;

            await ClientCollection.InsertOneAsync(client);

            return(client);
        }
Example #5
0
        public virtual async Task <TClient> RegisterClientAsync(string ownerUserName, string name, OAuthGrantType grantType, ITransaction currentTransaction = null)
        {
            Contract.Requires(!string.IsNullOrEmpty(name));

            TClient client = new TClient();

            client.GrantType = grantType;

            using (RijndaelManaged cryptoManager = new RijndaelManaged())
            {
                cryptoManager.GenerateKey();
                client.Id = BitConverter.ToString(cryptoManager.Key).Replace("-", string.Empty).ToLowerInvariant();

                cryptoManager.GenerateKey();
                client.Secret = BitConverter.ToString(cryptoManager.Key).Replace("-", string.Empty).ToLowerInvariant();
            }

            client.Name       = name;
            client.SecretHash = new PasswordHasher().HashPassword(client.Secret);
            client.DateAdded  = DateTimeOffset.Now;

            ITransaction transaction = currentTransaction ?? Database.CreateTransaction();

            transaction.HashSetAsync(ClientHashKey, new[] { new HashEntry(client.Id, JsonConvert.SerializeObject(client)) });
            transaction.SetAddAsync(string.Format(ClientsByUserSetKey, ownerUserName), client.Id);

            if (currentTransaction == null)
            {
                await transaction.ExecuteAsync();
            }

            return(client);
        }
        /// <summary>
        /// Create token endpoint specific request context.
        /// </summary>
        /// <param name="httpContext">The current HTTP request specific <see cref="HttpContext"/>.</param>
        /// <returns>The task to create the token endpoint specific request context.</returns>
        /// <exception cref="ArgumentNullException">Specified <paramref name="httpContext"/> is null.</exception>
        public Task <TokenContext> CreateTokenGrantContextAsync(HttpContext httpContext)
        {
            Guard.ArgumentNotNull(httpContext, nameof(httpContext));

            //Must be POST request.
            if (!string.Equals(httpContext.Request.Method, "POST"))
            {
                return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidRequest.UnsupportedHttpMethod.Format())));
            }

            //Conent-Type = application/x-www-form-urlencoded.
            if (!httpContext.Request.HasFormContentType)
            {
                return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidRequest.UnsupportedContentType.Format())));
            }

            var form = httpContext.Request.Form;

            //Extract client_id.
            var clientId = form.GetValue(OAuthDefaults.ParameterNames.ClientId);

            if (string.IsNullOrWhiteSpace(clientId))
            {
                return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidRequest.MissingClientId.Format())));
            }

            //Extract redirect_uri
            var redirectUriString = form.GetValue(OAuthDefaults.ParameterNames.RedirectUri);

            if (string.IsNullOrWhiteSpace(redirectUriString))
            {
                return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidRequest.MissingRedirectUri.Format())));
            }
            Uri redirectUri;

            try
            {
                redirectUri = new Uri(redirectUriString);
            }
            catch
            {
                return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidRequest.InvalidRedirectUri.Format())));
            }

            //Extract client_secret
            var clientSecret = form.GetValue(OAuthDefaults.ParameterNames.ClientSecret);

            if (string.IsNullOrWhiteSpace(clientSecret))
            {
                return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidRequest.MissingClientSecret.Format())));
            }

            //Extract grant_type
            var grantTypeString = form.GetValue(OAuthDefaults.ParameterNames.GarntType);

            if (string.IsNullOrWhiteSpace(grantTypeString))
            {
                return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidRequest.MissingGrantType.Format())));
            }
            if (!_valideGrantTypes.Contains(grantTypeString))
            {
                return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.UnsupportedGrantType.UnsupportedGrantType.Format(grantTypeString))));
            }

            OAuthGrantType grantType = grantTypeString == "authorization_code"
               ? OAuthGrantType.AuthorizationCode
               : OAuthGrantType.RefreshToken;

            if (grantType == OAuthGrantType.AuthorizationCode)
            {
                var code = form.GetValue(OAuthDefaults.ParameterNames.Code);
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidRequest.MissingAuthorizationCode.Format())));
                }

                try
                {
                    OAuthTicket authorizationCode = _ticketFormat.Unprotect(code);
                    return(Task.FromResult(new TokenContext(httpContext, clientId, redirectUri, clientSecret, authorizationCode, grantType)));
                }
                catch
                {
                    return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidGrant.InvalidAuthorizationCode.Format())));
                }
            }
            else
            {
                var token = form.GetValue(OAuthDefaults.ParameterNames.RefreshToken);
                if (string.IsNullOrWhiteSpace(token))
                {
                    return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidRequest.MissingRefreshToken.Format())));
                }
                try
                {
                    OAuthTicket refreshToken = _ticketFormat.Unprotect(token);
                    return(Task.FromResult(new TokenContext(httpContext, clientId, redirectUri, clientSecret, refreshToken, grantType)));
                }
                catch
                {
                    return(Task.FromResult(new TokenContext(httpContext, OAuthErrors.InvalidGrant.InvalidRefreshToken.Format())));
                }
            }
        }