public HttpWebResponse GetResponse(OAuthContext context, TokenBase accessToken)
        {
            SignContext(context, accessToken);

            Uri uri = context.GenerateUri();

            Console.WriteLine("Uri: {0}", uri);

            var request = (HttpWebRequest) WebRequest.Create(uri);
            request.Method = context.RequestMethod;

            if ((context.FormEncodedParameters != null) && (context.FormEncodedParameters.Count > 0))
            {
                request.ContentType = "application/x-www-form-urlencoded";
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(UriUtility.FormatQueryString(context.FormEncodedParameters));
                }
            }

            if (UseHeaderForOAuthParameters)
            {
                request.Headers[Parameters.OAuth_Authorization_Header] = context.GenerateOAuthParametersForHeader();
            }

            return (HttpWebResponse) request.GetResponse();
        }
        private IContextSignatureImplementation FindImplementationForAuthContext(OAuthContext authContext)
        {
            IContextSignatureImplementation impl =
                _implementations.FirstOrDefault(i => i.MethodName == authContext.SignatureMethod);

            if (impl != null) return impl;

            throw Error.UnknownSignatureMethod(authContext.SignatureMethod);
        }
Esempio n. 3
0
 public TokenEndPoint(
     OAuthContext context,
     AuthorizationCodeStorage authCodeStorage,
     RefreshTokenStorage refreshTokenStorage)
 {
     _context = context;
     _authorizationCodestorage = authCodeStorage;
     _refreshTokenStorage = refreshTokenStorage;
 }
        /*[Test]
        public void Go()
        {
            var factory = new OAuthContextFactory();
            var context = factory.FromUri("GET", new Uri("http://localhost.:888/api/contacts/list.rails"));
            
            OAuthConsumer consumer = new OAuthConsumer("http://localhost/rt", "http://localhost/at");
            consumer.SignatureMethod = SignatureMethod.RsaSha1;
            consumer.ConsumerKey = "key";
            consumer.ConsumerSecret = "secret";
            consumer.Key = TestCertificates.OAuthTestCertificate().PrivateKey;
            consumer.SignContext(context, new TokenBase { ConsumerKey="key", Token = "accesskey", TokenSecret = "accesssecret" });
            
            OAuthContext context2 = factory.FromUri("GET", context.GenerateUri());

            Assert.AreEqual(context.Signature, context2.Signature);

            OAuthProvider provider = new OAuthProvider();
            provider.TestAlgorithm = TestCertificates.OAuthTestCertificate().PublicKey.Key;
            var outcome = provider.VerifyProtectedResourceRequest(context2);

            Assert.IsTrue(outcome.Granted, outcome.AdditionalInfo);            
        }*/

        public void Test()
        {
            string signature = "RJfuUrAU7qFkBfk9nR02qw9YsdlJzaT2tYINzZ8b+H5dQLfcZqUjmgEjOvfqBo6HcDg3tFKcZgxsUF+zw5Tv4KWTuhPaAl7SFOmpvVzAA5Pn0pKSkivEl6oAvKQW7JP00/KQoR9gD7HrspFvzYsoqv3DlfGgLF7VYx62JzUPYr4=";

            OAuthContext context = new OAuthContext() { RequestMethod = "GET",  RawUri = new Uri("http://localhost/service") };

            context.Signature = signature;

            Console.WriteLine(context.GenerateUri().ToString());
        }
        public bool ValidateSignature(OAuthContext authContext, SigningContext signingContext)
        {
            if (signingContext.Algorithm == null) throw Error.AlgorithmPropertyNotSetOnSigningContext();

            SHA1CryptoServiceProvider sha1 = GenerateHash(signingContext);

            var deformatter = new RSAPKCS1SignatureDeformatter(signingContext.Algorithm);
            deformatter.SetHashAlgorithm("MD5");

            byte[] signature = Convert.FromBase64String(authContext.Signature);

            return deformatter.VerifySignature(sha1, signature);
        }
        private string GenerateSignature(OAuthContext authContext, SigningContext signingContext)
        {
            if (signingContext.Algorithm == null) throw Error.AlgorithmPropertyNotSetOnSigningContext();

            SHA1CryptoServiceProvider sha1 = GenerateHash(signingContext);

            var formatter = new RSAPKCS1SignatureFormatter(signingContext.Algorithm);
            formatter.SetHashAlgorithm("MD5");

            byte[] signature = formatter.CreateSignature(sha1);

            return Convert.ToBase64String(signature);
        }
Esempio n. 7
0
        public static async Task<TokenEndPoint> GetTokenEndProint
        (
            IOwinContext owinContext,
            OAuthOptions options,
            AuthorizationCodeStorage storage,
            RefreshTokenStorage refreshTokenStorage
        )
        {
            var request = new TokenRequest(owinContext);
            await request.LoadAsync();

            var context = new OAuthContext(options, request, owinContext);

            return new TokenEndPoint(context, storage, refreshTokenStorage);
        }
        public TokenBase GrantRequestToken(OAuthContext context)
        {
            SigningContext signingContext = CreateSignatureContextForAuthContext(context);

            if (!_signer.ValidateSignature(context, signingContext))
            {
                throw Error.FailedToValidateSignature();
            }

            return new TokenBase
                       {
                           ConsumerKey = context.ConsumerKey,
                           Token = "requestkey",
                           TokenSecret = "requestsecret"
                       };
        }
        private string GenerateSignature(OAuthContext authContext, SigningContext signingContext)
        {
            string consumerSecret = (signingContext.ConsumerSecret != null)
                                        ? UriUtility.UrlEncode(signingContext.ConsumerSecret)
                                        : "";
            string tokenSecret = (authContext.TokenSecret != null)
                                     ? UriUtility.UrlEncode(authContext.TokenSecret)
                                     : null;
            string hashSource = string.Format("{0}&{1}", consumerSecret, tokenSecret);

            var hashAlgorithm = new HMACSHA1();

            hashAlgorithm.Key = Encoding.ASCII.GetBytes(hashSource);

            return ComputeHash(hashAlgorithm, signingContext.SignatureBase);
        }
        public void BeginAuthentication()
        {
            var oContext = new OAuthContext
            {
                ConsumerKey = Credentials.Facebook.ConsumerKey,
                ConsumerSecret = Credentials.Facebook.ConsumerSecret,                                   
                VerifierUrl = Credentials.Facebook.VerifierUrl,
                RequestAccessTokenUrl = Credentials.Facebook.RequestAccessTokenUrl,
                RequestProfileUrl = Credentials.Facebook.RequestProfileUrl,
                Scope = Credentials.Facebook.Scope,
                OAuthVersion = OAuthVersion.V2,
                SocialSiteName = "Facebook"
            };

            //In version 2.0 no need to get request token
            oContext.ObtainVerifier();
        }
        public void BeginAuthentication()
        {
            var oContext = new OAuthContext
            {
                ConsumerKey = Credentials.Google.ConsumerKey,
                ConsumerSecret = Credentials.Google.ConsumerSecret,
                RequestTokenUrl = Credentials.Google.RequestTokenUrl,
                VerifierUrl = Credentials.Google.VerifierUrl,
                RequestAccessTokenUrl = Credentials.Google.RequestAccessTokenUrl,
                RequestProfileUrl = Credentials.Google.RequestProfileUrl,
                Realm = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.DnsSafeHost + HttpContext.Current.Request.ApplicationPath,
                OAuthVersion = OAuthVersion.V1,
                SocialSiteName = "Google"
            };

            oContext.GetRequestToken();
            oContext.ObtainVerifier();
        }
        public TokenBase ExchangeRequestTokenForAccessToken(OAuthContext context)
        {
            SigningContext signingContext = CreateSignatureContextForAuthContext(context);

            if (!_signer.ValidateSignature(context, signingContext))
            {
                throw Error.FailedToValidateSignature();
            }

            if (context.Token != "requestkey")
            {
                throw Error.InvalidRequestToken(context.Token);
            }

            if (context.ConsumerKey != "key")
            {
                throw Error.InvalidConsumerKey(context.ConsumerKey);
            }

            return new TokenBase {ConsumerKey = context.ConsumerKey, Token = "accesskey", TokenSecret = "accesssecret"};
        }
        public AccessOutcome VerifyProtectedResourceRequest(OAuthContext context)
        {
            var outcome = new AccessOutcome {Context = context};
            
            SigningContext signingContext = null;
            
            try
            {
                signingContext = CreateSignatureContextForAuthContext(context);
            }
            catch (Exception ex)
            {
                outcome.AdditionalInfo = "Failed to parse request for context info";
                return outcome;
            }

            if (!_signer.ValidateSignature(context, signingContext))
            {
                outcome.AdditionalInfo = "Failed to validate signature";
                return outcome;
            }

            if (context.Token != "accesskey")
            {
                outcome.AdditionalInfo = "Invalid access token";
                return outcome;
            }

            if (context.ConsumerKey != "key")
            {
                outcome.AdditionalInfo = "Invalid consumer key";
                return outcome;
            }

            outcome.Granted = true;
            outcome.AccessToken = new TokenBase {ConsumerKey = "key", TokenSecret = "accesssecret", Token = "accesskey"};

            return outcome;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                OContext = OAuthContext.Current;

                if(!IsPostBack)
                {
                    //End authentication and register tokens.
                    OContext.EndAuthenticationAndRegisterTokens();

                    txtTokenKey.Text = OContext.Token;
                    txtTokenSecret.Text = OContext.TokenSecret;
                    txtVerifier.Text = OContext.Verifier;
                }
            }
            catch (OAuthException ex)
            {
                Response.Write("<p>OAuth Exception occurred.</p>");
                Response.Write("<p>" + ex.InnerException.Message + "</p>");
                Response.Write("<p>" + ex.InnerException.StackTrace + "</p>");
            }
        }
Esempio n. 15
0
        public static async Task<Flow> Get
        (
            IOwinContext owinContext,
            OAuthOptions options,
            AuthorizationCodeStorage authCodeStorage,
            RefreshTokenStorage refreshTokenStorage
        )
        {
            var request = new AuthenticationRequest(owinContext);
            await request.LoadAsync();

            var context = new OAuthContext(options, request, owinContext);

            switch (context.AuthenticationRequest.response_type?.Trim())
            {
                case "code": return new AuthorizationCodeFlow(context, authCodeStorage);
                case "id_token": return new ImplicitFlow(context);
                case "id_token token": return new ImplicitFlow(context);
                case "code id_token": return new HybridFlow(context);
                case "code token": return new HybridFlow(context);
                case "code id_token token": return new HybridFlow(context);
                default: return null;
            }
        }
 public void SignContext(OAuthContext authContext, SigningContext signingContext)
 {
     authContext.Signature = GenerateSignature(authContext, signingContext);
 }
        protected void gOAuthClientEdit_SaveClick(object sender, EventArgs e)
        {
            divErrors.Visible = false;
            if (String.IsNullOrEmpty(tbClientName.Text))
            {
                divErrors.InnerText = "A valid Client Name must be provided.";
                divErrors.Visible   = true;
                return;
            }
            if (tbApiKey.Text.AsGuidOrNull() == null)
            {
                divErrors.InnerText = "A valid GUID must be provided for the API Key.";
                divErrors.Visible   = true;
                return;
            }
            if (tbApiSecret.Text.AsGuidOrNull() == null)
            {
                divErrors.InnerText = "A valid GUID must be provided for the API Secret.";
                divErrors.Visible   = true;
                return;
            }
            if (string.IsNullOrEmpty(tbCallbackUrl.Text))
            {
                divErrors.InnerText = "A valid Callback URL must be provided.";
                divErrors.Visible   = true;
                return;
            }
            ClientScopeService clientScopeService = new ClientScopeService(OAuthContext);
            ClientService      clientService      = new ClientService(OAuthContext);
            Client             client             = null;

            if (hfClientId.Value.AsIntegerOrNull().HasValue)
            {
                client = clientService.Get(hfClientId.Value.AsInteger());
            }
            else
            {
                client = new Client();
                clientService.Add(client);
            }

            client.ClientName  = tbClientName.Text;
            client.ApiKey      = tbApiKey.Text.AsGuid();
            client.ApiSecret   = tbApiSecret.Text.AsGuid();
            client.CallbackUrl = tbCallbackUrl.Text;
            client.Active      = cbActive.Checked;

            foreach (System.Web.UI.WebControls.ListItem item in cblClientScopes.Items)
            {
                int         scopeId     = item.Value.AsInteger();
                ClientScope clientScope = clientScopeService.Queryable().Where(cs => cs.ClientId == client.Id && cs.ScopeId == scopeId).FirstOrDefault();
                if (clientScope != null)
                {
                    clientScope.Active = item.Selected;
                }
                else if (item.Selected)
                {
                    clientScope          = new ClientScope();
                    clientScope.ClientId = client.Id;
                    clientScope.ScopeId  = item.Value.AsInteger();
                    clientScope.Active   = item.Selected;
                    clientScopeService.Add(clientScope);
                }
            }
            OAuthContext.SaveChanges();
            OAuthContext = new OAuthContext();
            gOAuthClients_Bind(sender, e);
            gOAuthClientEdit.Hide();
        }
Esempio n. 18
0
 private string GenerateSignature(OAuthContext authContext, SigningContext signingContext)
 {
     return(UriUtility.UrlEncode(string.Format("{0}&{1}", signingContext.ConsumerSecret, authContext.TokenSecret)));
 }
Esempio n. 19
0
 public CustomersController(OAuthContext context)
 {
     _context = context;
 }
Esempio n. 20
0
 public OAuthService(OAuthContext oAuthContext)
 {
     this.oAuthContext = oAuthContext;
 }
Esempio n. 21
0
 public HybridFlow(OAuthContext context)
     : base(context)
 {
 }
        public HttpResponseMessage CreateAccount(Account account)
        {
            OAuthContext  oAuthContext  = new OAuthContext();
            ClientService clientService = new ClientService(oAuthContext);
            var           clientId      = HttpContext.Current.User.Identity.Name;
            Client        oAuthClient   = clientService.GetByApiKey(clientId.AsGuid());

            if (oAuthClient.Active)
            {
                var              rockContext      = new Rock.Data.RockContext();
                PersonService    personService    = new PersonService(rockContext);
                UserLoginService userLoginService = new UserLoginService(rockContext);

                // Validate the Model
                if (!string.IsNullOrEmpty(account.Username))
                {
                    // Make sure the username is unique
                    UserLogin user = userLoginService.GetByUserName(account.Username);
                    if (user != null)
                    {
                        ModelState.AddModelError("Account.Username", "Username already exists");
                    }

                    // Make sure the password is valid
                    if (!UserLoginService.IsPasswordValid(account.Password))
                    {
                        ModelState.AddModelError("Account.Password", UserLoginService.FriendlyPasswordRules());
                    }

                    // Make sure this person meets the minimum age requirement
                    var birthday = account.Birthdate ?? Rock.RockDateTime.Today;
                    if (RockDateTime.Today.AddYears(MINIMUM_AGE * -1) < birthday)
                    {
                        ModelState.AddModelError("Account.Birthdate", string.Format("We are sorry, you must be at least {0} years old to create an account.", MINIMUM_AGE));
                    }
                }
                if (!ModelState.IsValid)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                // Try to match the person
                var matchPerson = personService.GetByMatch(account.FirstName, account.LastName, account.Birthdate, account.EmailAddress, account.MobileNumber, null, null);

                bool   confirmed = false;
                Person person    = new Person();
                if (matchPerson != null && matchPerson.Count() == 1)
                {
                    var mobilePhone = matchPerson.First().PhoneNumbers.Where(pn => pn.NumberTypeValueId == DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id).FirstOrDefault();
                    // The emails MUST match for security
                    if (matchPerson.First().Email == account.EmailAddress && (mobilePhone == null || mobilePhone.Number.Right(10) == account.MobileNumber.Right(10)))
                    {
                        person = matchPerson.First();

                        // If they don't have a current mobile phone, go ahead and set it
                        if (mobilePhone == null)
                        {
                            string cleanNumber = PhoneNumber.CleanNumber(account.MobileNumber);
                            var    phoneNumber = new PhoneNumber {
                                NumberTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id
                            };
                            person.PhoneNumbers.Add(phoneNumber);
                            phoneNumber.CountryCode        = cleanNumber.Length > 10 ? cleanNumber.Left(10 - cleanNumber.Length) : PhoneNumber.DefaultCountryCode();
                            phoneNumber.Number             = cleanNumber.Right(10);
                            phoneNumber.IsMessagingEnabled = true;
                        }

                        // Make sure the gender matches
                        person.Gender = account.Gender;

                        confirmed = true;
                    }
                }

                // If we don't have a match, create a new web prospect
                if (!confirmed)
                {
                    DefinedValueCache dvcConnectionStatus = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_WEB_PROSPECT.AsGuid());
                    DefinedValueCache dvcRecordStatus     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid());

                    person.FirstName         = account.FirstName;
                    person.LastName          = account.LastName;
                    person.NickName          = account.NickName;
                    person.Email             = account.EmailAddress;
                    person.IsEmailActive     = true;
                    person.EmailPreference   = EmailPreference.EmailAllowed;
                    person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    if (dvcConnectionStatus != null)
                    {
                        person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                    }

                    if (dvcRecordStatus != null)
                    {
                        person.RecordStatusValueId = dvcRecordStatus.Id;
                    }

                    person.Gender = account.Gender;

                    var birthday = account.Birthdate;
                    if (birthday.HasValue)
                    {
                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay   = birthday.Value.Day;
                        if (birthday.Value.Year != DateTime.MinValue.Year)
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(account.MobileNumber))
                    {
                        string cleanNumber = PhoneNumber.CleanNumber(account.MobileNumber);
                        var    phoneNumber = new PhoneNumber {
                            NumberTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id
                        };
                        person.PhoneNumbers.Add(phoneNumber);
                        phoneNumber.CountryCode        = cleanNumber.Length > 10 ? cleanNumber.Left(10 - cleanNumber.Length) : PhoneNumber.DefaultCountryCode();
                        phoneNumber.Number             = cleanNumber.Right(10);
                        phoneNumber.IsMessagingEnabled = true;
                    }

                    PersonService.SaveNewPerson(person, rockContext);
                }
                UserLogin userLogin = null;

                if (!string.IsNullOrWhiteSpace(account.Username) && UserLoginService.IsPasswordValid(account.Password))
                {
                    // Create the user login (only require confirmation if we didn't match the person)
                    userLogin = UserLoginService.Create(
                        rockContext,
                        person,
                        AuthenticationServiceType.Internal,
                        EntityTypeCache.Get(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id,
                        account.Username,
                        account.Password,
                        confirmed);
                }
                else if (!string.IsNullOrWhiteSpace(account.EmailAddress) && !confirmed)
                {
                    userLogin = userLoginService.Queryable()
                                .Where(u => u.UserName == ("SMS_" + person.Id.ToString()))
                                .FirstOrDefault();

                    // Create an unconfirmed SMS user login if does not exist
                    if (userLogin == null)
                    {
                        var entityTypeId = EntityTypeCache.Get("Rock.Security.ExternalAuthentication.SMSAuthentication").Id;

                        userLogin = new UserLogin()
                        {
                            UserName     = "******" + person.Id.ToString(),
                            EntityTypeId = entityTypeId,
                            IsConfirmed  = false,
                            PersonId     = person.Id
                        };
                        userLoginService.Add(userLogin);
                    }
                }
                // Send an email to confirm the account.
                if (userLogin != null && userLogin.IsConfirmed != true)
                {
                    // For mobile we will make a custom/short confirmation code
                    var mobileConfirmationCode = new BigInteger(MD5.Create().ComputeHash(userLogin.Guid.ToByteArray())).ToString().Right(6);
                    var mergeFields            = Rock.Lava.LavaHelper.GetCommonMergeFields(null, person);
                    mergeFields.Add("MobileConfirmationCode", mobileConfirmationCode);
                    mergeFields.Add("ConfirmAccountUrl", GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash() + "ConfirmAccount");
                    mergeFields.Add("Person", userLogin.Person);
                    mergeFields.Add("User", userLogin);

                    var recipients = new List <RockEmailMessageRecipient>();
                    recipients.Add(new RockEmailMessageRecipient(userLogin.Person, mergeFields));

                    var message = new RockEmailMessage(Rock.SystemGuid.SystemCommunication.SECURITY_CONFIRM_ACCOUNT.AsGuid());
                    message.SetRecipients(recipients);
                    message.AppRoot = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                    message.CreateCommunicationRecord = false;
                    message.Send();
                }

                rockContext.SaveChanges();

                return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, new StandardResponse()
                {
                    Message = string.Format("Account has been created.{0}", confirmed ? "" : " An email has been sent to confirm the email address."),
                    Result = StandardResponse.ResultCode.Success
                }
                                                                ));
            }

            return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden));
        }
        private string CreateAuthorizationHeaderInternal(HttpMethod httpMethod, string url, Dictionary <string, string> parameters,
                                                         string body)
        {
            Encoding enc = Encoding.UTF8;

            NameValueCollection authorizationHeaderParameters = new NameValueCollection();

            authorizationHeaderParameters.Add(Parameters.OAuth_Timestamp, DateTime.Now.Epoch().ToString());
            authorizationHeaderParameters.Add(Parameters.OAuth_Version, "1.0");
            authorizationHeaderParameters.Add(Parameters.OAuth_Consumer_Key, _consumerKey);
            authorizationHeaderParameters.Add(Parameters.OAuth_Signature_Method, SignatureMethod.RsaSha1);
            authorizationHeaderParameters.Add(Parameters.Realm, Realm);

            var oauthContext = new OAuthContext
            {
                AuthorizationHeaderParameters = authorizationHeaderParameters,
                RawUri        = new Uri(url),
                RequestMethod = httpMethod.Method
            };

            authorizationHeaderParameters.Add(Parameters.OAuth_Nonce, new GuidNonceGenerator().GenerateNonce(oauthContext));

            if (parameters != null && parameters.ContainsKey("CallbackUrl"))
            {
                authorizationHeaderParameters.Add(Parameters.OAuth_Callback, parameters["CallbackUrl"]);
            }
            if (parameters != null && parameters.ContainsKey("Oauth_Verifier"))
            {
                authorizationHeaderParameters.Add(Parameters.OAuth_Verifier, parameters["Oauth_Verifier"]);
            }
            if (parameters != null && parameters.ContainsKey("Token"))
            {
                authorizationHeaderParameters.Add(Parameters.OAuth_Token, parameters["Token"]);
            }

            if (body != null)
            {
                var rawContent = enc.GetBytes(body);
                oauthContext.Realm      = null;
                oauthContext.RawContent = rawContent;
                authorizationHeaderParameters.Add(Parameters.OAuth_Body_Hash, oauthContext.GenerateBodyHash());
            }

            oauthContext.AuthorizationHeaderParameters = authorizationHeaderParameters;

            var privateKey = GetCertificate(_certThumbprint).PrivateKey;
            // Set the signature base string so that it's viewable by the
            // caller upon the return of the response.
            var signatureBaseString = oauthContext.GenerateSignatureBase();
            var signer = new RsaSha1SignatureImplementation();

            signer.SignContext(oauthContext,
                               new SigningContext {
                Algorithm = privateKey, SignatureBase = signatureBaseString
            });

            authorizationHeaderParameters.Add(Parameters.OAuth_Signature, oauthContext.Signature);
            oauthContext.AuthorizationHeaderParameters = authorizationHeaderParameters;

            var authHeader = oauthContext.GenerateOAuthParametersForHeader();

            return(authHeader);
        }
Esempio n. 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientService"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 public ClientService(OAuthContext context) : base(context)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthorizationService"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 public AuthorizationService(OAuthContext context) : base(context)
 {
 }
Esempio n. 26
0
 public Flow(OAuthContext context)
 {
     Context = context;
 }
Esempio n. 27
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var    authentication = HttpContext.Current.GetOwinContext().Authentication;
            var    ticket         = authentication.AuthenticateAsync("OAuth").Result;
            var    identity       = ticket != null ? ticket.Identity : null;
            string userName       = null;

            string[] authorizedScopes = null;
            var      scopes           = (Request.QueryString.Get("scope") ?? "").Split(' ');
            bool     scopesApproved   = false;

            if (identity == null)
            {
                authentication.Challenge("OAuth");
                Response.Redirect(OAuthSettings["OAuthLoginPath"] + "?ReturnUrl=" + Server.UrlEncode(Request.RawUrl), true);
            }
            else if (CurrentUser == null)
            {
                // Kill the OAuth session
                authentication.SignOut("OAuth");
                authentication.Challenge("OAuth");
                Response.Redirect(OAuthSettings["OAuthLoginPath"] + "?ReturnUrl=" + Server.UrlEncode(Request.RawUrl), true);
            }
            else
            {
                OAuthContext  context       = new OAuthContext();
                ClientService clientService = new ClientService(context);
                Client        OAuthClient   = clientService.GetByApiKey(PageParameter("client_id").AsGuid());
                if (OAuthClient != null)
                {
                    ClientScopeService clientScopeService = new ClientScopeService(context);

                    userName = identity.Name;
                    AuthorizationService authorizationService = new AuthorizationService(context);

                    authorizedScopes = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLogin.UserName == identity.Name && a.Active == true).Select(a => a.Scope.Identifier).ToArray <string>();
                    if (!clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Any() ||
                        (authorizedScopes != null && scopes.Where(s => !authorizedScopes.Select(a => a.ToLower()).Contains(s.ToLower())).Count() == 0))
                    {
                        scopesApproved = true;
                    }

                    if (scopesApproved)
                    {
                        identity = new ClaimsIdentity(identity.Claims, "Bearer", identity.NameClaimType, identity.RoleClaimType);

                        //only allow claims that have been requested and the client has been authorized for
                        foreach (var scope in scopes.Where(s => clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope.Identifier.ToLower()).Contains(s.ToLower())))
                        {
                            identity.AddClaim(new Claim("urn:oauth:scope", scope));
                        }
                        authentication.SignIn(identity);
                    }
                    else
                    {
                        rptScopes.DataSource = clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(s => s.Scope).ToList();
                        rptScopes.DataBind();
                    }

                    lClientName.Text     = OAuthClient.ClientName;
                    lClientName2.Text    = OAuthClient.ClientName;
                    lUsername.Text       = CurrentUser.Person.FullName + " (" + userName + ")";
                    hlLogout.NavigateUrl = Request.RawUrl + "&OAuthLogout=true";
                }
                else
                {
                    throw new Exception("Invalid Client ID for OAuth authentication.");
                }
            }
        }
 public abstract Task<bool> GrantResourceOwnerCredentials(OAuthContext context);
Esempio n. 29
0
 public OAuthAttribute(string realm)
 {
     Realm   = realm;
     Context = OAuth.GetContext(Realm);
 }
Esempio n. 30
0
        private async void Twitter_Tapped(object sender, TappedRoutedEventArgs e)
        {
            dataBindingSource.progressBarIsIndeterminate = true;

            //Make a POST Request and get the Request Token
            TwitterOauth twitter = new TwitterOauth();
            twitter.oauth_callback = "https://www.facebook.com/connect/login_success.html";
            twitter.oauth_consumer_key = "iNpGqyW7YR6tEGCi8jQw";
            twitter.oauth_consumer_secret = "yIu7O2de1ohn4Wn6TIMoi1PRjMFtuYIlLbzO6lDgJMY";
            twitter.oauth_nonce = Convert.ToBase64String(
                                  Encoding.UTF8.GetBytes(
                                       DateTime.Now.Ticks.ToString()));
            TimeSpan timespan = DateTime.UtcNow
                                  - new DateTime(1970, 1, 1, 0, 0, 0, 0,
                                       DateTimeKind.Utc);
            twitter.oauth_timestamp = Convert.ToInt64(timespan.TotalSeconds).ToString();
            twitter.request_uri = "https://api.twitter.com/oauth/request_token";
            twitter.oauth_version = "1.0";
            twitter.oauth_signature_method = "HMAC-SHA1";

            //Compute Key  and BaseString for implementing the SCHA1 Algorithm
            var compositeKey = string.Concat(WebUtility.UrlEncode(twitter.oauth_consumer_secret),
                         "&");
            string baseString,baseFormat;
            baseFormat = "oauth_callback={0}&oauth_consumer_key={1}&oauth_nonce={2}&oauth_signature={3}" +
                "&oauth_signature_method={4}&oauth_timestamp={5}&oauth_version={6}";
            baseString = String.Format(baseFormat, twitter.oauth_callback, twitter.oauth_consumer_key,
                                        twitter.oauth_nonce, twitter.oauth_signature, twitter.oauth_signature_method,
                                        twitter.oauth_timestamp, twitter.oauth_version);
            baseString = String.Concat("POST&", WebUtility.UrlEncode(twitter.request_uri),"&", WebUtility.UrlEncode(baseString));
            twitter.oauth_signature = Utils.HmacSha1(baseString, compositeKey);
            twitter.authorize_uri = "https://api.twitter.com/oauth/authorize";


            try
            {
                //
                // Acquiring a request token
                //
                TimeSpan SinceEpoch = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
                Random Rand = new Random();
                String TwitterUrl = "https://api.twitter.com/oauth/request_token";
                Int32 Nonce = Rand.Next(1000000000);
                //
                // Compute base signature string and sign it.
                //    This is a common operation that is required for all requests even after the token is obtained.
                //    Parameters need to be sorted in alphabetical order
                //    Keys and values should be URL Encoded.
                //
                String SigBaseStringParams = "oauth_callback=" + Uri.EscapeDataString(twitter.oauth_callback);
                SigBaseStringParams += "&" + "oauth_consumer_key=" + twitter.oauth_consumer_key;
                SigBaseStringParams += "&" + "oauth_nonce=" + Nonce.ToString();
                SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
                SigBaseStringParams += "&" + "oauth_timestamp=" + Math.Round(SinceEpoch.TotalSeconds);
                SigBaseStringParams += "&" + "oauth_version=1.0";
                String SigBaseString = "POST&";
                SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);

                IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(twitter.oauth_consumer_secret + "&", BinaryStringEncoding.Utf8);
                MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
                CryptographicKey MacKey = HmacSha1Provider.CreateKey(KeyMaterial);
                IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(SigBaseString, BinaryStringEncoding.Utf8);
                IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);
                String Signature = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);
                String DataToPost = "OAuth oauth_callback=\"" + Uri.EscapeDataString(twitter.oauth_callback) + "\", oauth_consumer_key=\"" + twitter.oauth_consumer_key + "\", oauth_nonce=\"" + Nonce.ToString() + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + Math.Round(SinceEpoch.TotalSeconds) + "\", oauth_version=\"1.0\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\"";

                PostResponse = await PostData(TwitterUrl, DataToPost, true);

                if (PostResponse != null)
                {
                    String oauth_token = null;
                    String oauth_token_secret = null;
                    String[] keyValPairs = PostResponse.Split('&');

                    for (int i = 0; i < keyValPairs.Length; i++)
                    {
                        String[] splits = keyValPairs[i].Split('=');
                        switch (splits[0])
                        {
                            case "oauth_token":
                                oauth_token = splits[1];
                                break;
                            case "oauth_token_secret":
                                oauth_token_secret = splits[1];
                                break;
                        }
                    }

                    if (oauth_token != null)
                    {

                        TwitterUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth_token;
                        System.Uri StartUri = new Uri(TwitterUrl);
                        System.Uri EndUri = new Uri(twitter.oauth_callback);

                        WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                                                                WebAuthenticationOptions.None,
                                                                StartUri,
                                                                EndUri);
                        if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                        {
                            string oauth_verifier = "";
                            string oauth_token2 = "";
                            string webResponseString = WebAuthenticationResult.ResponseData.ToString();
                            
                            int index_oauth = webResponseString.IndexOf("oauth_token");

                            int i = index_oauth;
                            while (webResponseString[i] != '=')
                            {
                                i++;
                            }
                            i++;

                            while (webResponseString[i] != '&')
                            {
                                oauth_token2 += webResponseString[i];
                                i++;
                            }

                            while (webResponseString[i] != '=')
                            {
                                i++;
                            }
                            i++;
                            
                            while (i != webResponseString.Length)
                            {
                                oauth_verifier += webResponseString[i];
                                i++;
                            }

                            //Get the access token by making a POST request

                            string access_token_post_url = "https://api.twitter.com/oauth/access_token?oauth_verifier=" + oauth_verifier;

                            Signature = Utils.HmacSha1(baseString, compositeKey + oauth_token_secret);

                            string postData = "OAuth oauth_consumer_key=\"" + twitter.oauth_consumer_key + "\", oauth_nonce=\"" + Nonce.ToString() + "\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" +  Math.Round(SinceEpoch.TotalSeconds) + "\", oauth_token=\"" + oauth_token2 + "\", oauth_version=\"1.0\"";

                            string postResponsedata = await PostData(access_token_post_url, postData,true);

                            string accessToken = "", accessSecretKey = "", userID = "", screenName = "";

                            List<string> tokenList = new List<string>(postResponsedata.Split('&'));

                            foreach (string tokenNameValue in tokenList)
                            {
                                List<string> singleTokenList = new List<string>(tokenNameValue.Split('='));
                                if (String.Compare(singleTokenList[0], "oauth_token") == 0)
                                {
                                    accessToken = singleTokenList[1];
                                }
                                else if(String.Compare(singleTokenList[0],"oauth_token_secret") == 0)
                                {
                                    accessSecretKey = singleTokenList[1];
                                }
                                else if (String.Compare(singleTokenList[0], "user_id") == 0)
                                {
                                    userID = singleTokenList[1];
                                }
                                else if (String.Compare(singleTokenList[0], "screen_name") == 0)
                                {
                                    screenName = singleTokenList[1];
                                }

                            }

                            //Getting the user details
                            string userDetailsUrl = "https://api.twitter.com/1.1/account/verify_credentials.json";

                            SigBaseStringParams = "oauth_consumer_key=" + twitter.oauth_consumer_key;
                            SigBaseStringParams += "&" + "oauth_nonce=" + Nonce.ToString();
                            SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
                            SigBaseStringParams += "&" + "oauth_timestamp=" + Math.Round(SinceEpoch.TotalSeconds);
                            SigBaseStringParams += "&" + "oauth_token=" + accessToken;
                            SigBaseStringParams += "&" + "oauth_version=1.0";
                            SigBaseString = "GET&";
                            SigBaseString += Uri.EscapeDataString(userDetailsUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);


                            Signature = Utils.HmacSha1(SigBaseStringParams, compositeKey + accessSecretKey);

                            postData = "OAuth oauth_consumer_key=\"" + twitter.oauth_consumer_key + "\", oauth_nonce=\"" + Nonce.ToString() + "\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + Math.Round(SinceEpoch.TotalSeconds) + "\", oauth_token=\"" + accessToken + "\", oauth_version=\"1.0\"";

                            var context = new OAuthContext(twitter.oauth_consumer_key, twitter.oauth_consumer_secret, "https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/authorize", "https://api.twitter.com/oauth/access_token", twitter.oauth_callback);

                            var client = new Client(context);

                            client.AccessToken = new TokenContainer();

                            client.AccessToken.Token = accessToken;
                            client.AccessToken.Secret = accessSecretKey;

                            String postResponse = await client.MakeRequest("GET")
                                .WithFormEncodedData(new {}) //this will be sent as a key/value in the request body an is included in the OAuth signature
                                .ForResource(client.AccessToken.Token,new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"))
                                .Sign(client.AccessToken.Secret)
                                .ExecuteRequest();


                            Newtonsoft.Json.Linq.JObject twitterUserInfoJObject = Newtonsoft.Json.Linq.JObject.Parse(postResponse);

                            dynamic parameter = new ExpandoObject();
                            try
                            {
                                Newtonsoft.Json.Linq.JToken value;
                                if (twitterUserInfoJObject.TryGetValue("id",out value))
                                {
                                    parameter.id = value.ToString();
                                }
                                if (twitterUserInfoJObject.TryGetValue("screen_name", out value))
                                {
                                    parameter.username = value.ToString();
                                }
                                if (twitterUserInfoJObject.TryGetValue("name", out value))
                                {
                                    parameter.first_name = value.ToString();
                                }
                                if (twitterUserInfoJObject.TryGetValue("profile_image_url_https", out value))
                                {
                                    parameter.picture = value.ToString();
                                }
                                parameter.service = "Twitter";
                            }
                            catch (NullReferenceException ex)
                            {
                                  
                            }
                            UserInfo user = new UserInfo(parameter);

                            Frame.Navigate(typeof(HomePage), (object) user);
                        }
                        else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                        {
                              dataBindingSource.progressBarIsIndeterminate = false;
                              var messageBox = new MessageDialog("Could not connect to the network.Please check your internet connections");
                              messageBox.Commands.Add(new UICommand("OK"));
                              messageBox.DefaultCommandIndex = 0;
                              await messageBox.ShowAsync();
                        }
                        else
                        {
                              //User cancelled login 
                              dataBindingSource.progressBarIsIndeterminate = false;
                        }
                    }
                }
                
            }
            catch (Exception Error)
            {
                throw Error;
            }

        }
Esempio n. 31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BoundParameter"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="context">The context.</param>
 public BoundParameter(string name, OAuthContext context)
 {
     _name    = name;
     _context = context;
 }
        public AccessOutcome AccessProtectedResource(IRequest request)
        {
            OAuthContext context = _contextFactory.FromMonoRailRequest(request);

            return(_provider.VerifyProtectedResourceRequest(context));
        }
Esempio n. 33
0
        private System.Threading.Tasks.Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (!string.IsNullOrEmpty(context.UserName) && !string.IsNullOrEmpty(context.Password))
            {
                var rockContext      = new RockContext();
                var userLoginService = new UserLoginService(rockContext);
                var userName         = context.UserName;

                var userLogin = userLoginService.GetByUserName(userName);
                if (userLogin != null && userLogin.EntityType != null)
                {
                    var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name);
                    if (component != null && component.IsActive &&
                        (!component.RequiresRemoteAuthentication || component.TypeName == "Rock.Security.ExternalAuthentication.SMSAuthentication"))
                    {
                        if (component.Authenticate(userLogin, context.Password))
                        {
                            if ((userLogin.IsConfirmed ?? true) && !(userLogin.IsLockedOut ?? false))
                            {
                                OAuthContext         oAuthContext         = new OAuthContext();
                                ClientScopeService   clientScopeService   = new ClientScopeService(oAuthContext);
                                AuthorizationService authorizationService = new AuthorizationService(oAuthContext);
                                ClientService        clientService        = new ClientService(oAuthContext);

                                var scopes = (context.Scope.FirstOrDefault() ?? "").Split(',');

                                bool     scopesApproved   = false;
                                Client   OAuthClient      = clientService.GetByApiKey(context.ClientId.AsGuid());
                                string[] authorizedScopes = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLogin.UserName == userName && a.Active == true).Select(a => a.Scope.Identifier).ToArray <string>();
                                if (!clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Any() ||
                                    (authorizedScopes != null && scopes.Where(s => !authorizedScopes.Select(a => a.ToLower()).Contains(s.ToLower())).Count() == 0))
                                {
                                    scopesApproved = true;
                                }

                                if (scopesApproved)
                                {
                                    var identity = new ClaimsIdentity(new GenericIdentity(userName, OAuthDefaults.AuthenticationType));

                                    //only allow claims that have been requested and the client has been authorized for
                                    foreach (var scope in scopes.Where(s => clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope.Identifier.ToLower()).Contains(s.ToLower())))
                                    {
                                        identity.AddClaim(new Claim("urn:oauth:scope", scope));
                                    }
                                    UserLoginService.UpdateLastLogin(userName);
                                    context.Validated(identity);
                                    return(System.Threading.Tasks.Task.FromResult(0));
                                }
                                else
                                {
                                    context.Rejected();
                                    context.SetError("Authentication Error", "All scopes are not authorized for this user.");
                                }
                            }
                            if (!userLogin.IsConfirmed ?? true)
                            {
                                context.Rejected();
                                context.SetError("Authentication Error", "Account email is unconfirmed.");
                            }
                            if (userLogin.IsLockedOut ?? false)
                            {
                                context.Rejected();
                                context.SetError("Authentication Error", "Account is locked.");
                            }
                        }
                        else
                        {
                            context.Rejected();
                            context.SetError("Authentication Error", "Invalid Username/Password.");
                        }
                    }
                    else
                    {
                        context.Rejected();
                        context.SetError("Authentication Error", "Invalid Authentication Configuration.");
                    }
                }
                else
                {
                    context.Rejected();
                    context.SetError("Authentication Error", "Invalid Username/Password.");
                }
            }
            else
            {
                context.Rejected();
                context.SetError("Authentication Error", "Invalid Username/Password.");
            }

            return(System.Threading.Tasks.Task.FromResult(0));
        }
 private SigningContext CreateSignatureContextForAuthContext(OAuthContext context)
 {
     return new SigningContext
                {
                    ConsumerSecret = GetConsumerSecretForKey(context.ConsumerKey),
                    Algorithm = GetAlgorithmForConsumer(context.ConsumerKey)
                };
 }
        public void SignContext(OAuthContext context, TokenBase accessToken)
        {
            EnsureStateIsValid();

            if (accessToken.ConsumerKey != ConsumerKey)
                throw Error.SuppliedTokenWasNotIssuedToThisConsumer(ConsumerKey, accessToken.ConsumerKey);

            var signer = new OAuthContextSigner();
            var auth = new NonceGenerator();

            context.UseAuthorizationHeader = UseHeaderForOAuthParameters;
            context.ConsumerKey = accessToken.ConsumerKey;
            context.Token = accessToken.Token;
            context.TokenSecret = accessToken.TokenSecret;
            context.SignatureMethod = SignatureMethod;
            context.Timestamp = DateTime.Now.EpocString();
            context.Nonce = auth.GenerateNonce();
            context.Version = "1.0";

            string signatureBase = context.GenerateSignatureBase();

            Console.WriteLine("signature_base: {0}", signatureBase);

            signer.SignContext(context,
                               new SigningContext
                                   {Algorithm = Key, SignatureBase = signatureBase, ConsumerSecret = ConsumerSecret});

            Console.WriteLine("oauth_singature: {0}", context.Signature);
        }
Esempio n. 36
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var authentication = HttpContext.Current.GetOwinContext().Authentication;

            if (IsAuthenticationNotPermitted())
            {
                Rock.Security.Authorization.SignOut();
                authentication.SignOut("OAuth");
                authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                NavigateToLinkedPage(AttributeKeys.RejectedAuthenticationPage);
                return;
            }

            var    ticket   = authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie).Result;
            var    identity = ticket != null ? ticket.Identity : null;
            string userName = null;

            string[] authorizedScopes = null;
            var      scopes           = (Request.QueryString.Get("scope") ?? "").Split(' ');
            bool     scopesApproved   = false;

            //The user is logged in but does not have OAuth identity
            if (CurrentUser != null && identity == null)
            {
                CreateOAuthIdentity(authentication);
                Response.Redirect(Request.RawUrl, true);
            }
            //The user is not logged in and does not have OAuth identity
            else if (identity == null)
            {
                authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);
                //Send them off to log in
                StoreQueryStringCookie();
                Response.Redirect(OAuthSettings["OAuthLoginPath"], true);
            }
            //The user has an OAuth identity
            else
            {
                OAuthContext  context       = new OAuthContext();
                ClientService clientService = new ClientService(context);
                Client        OAuthClient   = clientService.GetByApiKey(PageParameter(PageParameterKeys.ClientId).AsGuid());
                if (OAuthClient != null)
                {
                    ClientScopeService clientScopeService = new ClientScopeService(context);

                    userName = identity.Name;
                    AuthorizationService authorizationService = new AuthorizationService(context);

                    authorizedScopes = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLogin.UserName == identity.Name && a.Active == true).Select(a => a.Scope.Identifier).ToArray <string>();
                    if (!clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Any() ||
                        (authorizedScopes != null && scopes.Where(s => !authorizedScopes.Select(a => a.ToLower()).Contains(s.ToLower())).Count() == 0))
                    {
                        scopesApproved = true;
                    }

                    if (scopesApproved)
                    {
                        identity = new ClaimsIdentity(identity.Claims, "Bearer", identity.NameClaimType, identity.RoleClaimType);

                        //only allow claims that have been requested and the client has been authorized for
                        foreach (var scope in scopes.Where(s => clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope.Identifier.ToLower()).Contains(s.ToLower())))
                        {
                            identity.AddClaim(new Claim("urn:oauth:scope", scope));
                        }
                        authentication.SignIn(identity);
                    }
                    else
                    {
                        rptScopes.DataSource = clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(s => s.Scope).ToList();
                        rptScopes.DataBind();
                    }

                    lClientName.Text     = OAuthClient.ClientName;
                    lClientName2.Text    = OAuthClient.ClientName;
                    lUsername.Text       = CurrentUser.Person.FullName + " (" + userName + ")";
                    hlLogout.NavigateUrl = Request.RawUrl + "&OAuthLogout=true";
                }
                else
                {
                    throw new Exception("Invalid Client ID for OAuth authentication.");
                }
            }
        }
Esempio n. 37
0
 public OrderRepository()
 {
     _ctx = new OAuthContext();
 }
Esempio n. 38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ScopeService"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 public ScopeService(OAuthContext context) : base(context)
 {
 }
Esempio n. 39
0
 public UnitOfWork()
 {
     dbContext = new OAuthContext();
 }
Esempio n. 40
0
 public OAuthRepository()
 {
     this.authContext = new OAuthContext();
     this.userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(authContext));
     this.roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(authContext));
 }
Esempio n. 41
0
 public AuthRepository()
 {
     authContext = new OAuthContext();
     userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(authContext));
 }
Esempio n. 42
0
 public bool ValidateSignature(OAuthContext authContext, SigningContext signingContext)
 {
     return(authContext.Signature == GenerateSignature(authContext, signingContext));
 }
Esempio n. 43
0
 public SampleService(OAuthContext oAuthContext)
 {
     this.oAuthContext = oAuthContext;
 }
Esempio n. 44
0
        private System.Threading.Tasks.Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (!string.IsNullOrEmpty(context.UserName) && !string.IsNullOrEmpty(context.Password))
            {
                var rockContext      = new RockContext();
                var userLoginService = new UserLoginService(rockContext);
                //Older Avalanche Clients use __PHONENUMBER__+1 prefix vs the newer SMS_ prefix
                //This makes sure we are using the new ROCK external sms authentication
                var userName = context.UserName.Replace("__PHONENUMBER__+1", "SMS_");

                //SMS login does not use the phone number as the username.
                //Instead we need to change it to use the person's id.
                if (userName.StartsWith("SMS_"))
                {
                    string error;
                    var    smsAuthentication = new SMSAuthentication();
                    var    person            = smsAuthentication.GetNumberOwner(userName.Split('_').Last(), rockContext, out error);
                    if (person != null)
                    {
                        userName = string.Format("SMS_{0}", person.Id);
                    }
                    //If we cannot find a person, do nothing and just pass through the existing username
                }
                var userLogin = userLoginService.GetByUserName(userName);
                if (userLogin != null && userLogin.EntityType != null)
                {
                    var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name);
                    if (component != null && component.IsActive &&
                        (!component.RequiresRemoteAuthentication || component.TypeName == "Rock.Security.ExternalAuthentication.SMSAuthentication"))
                    {
                        if (component.Authenticate(userLogin, context.Password))
                        {
                            if ((userLogin.IsConfirmed ?? true) && !(userLogin.IsLockedOut ?? false))
                            {
                                OAuthContext         oAuthContext         = new OAuthContext();
                                ClientScopeService   clientScopeService   = new ClientScopeService(oAuthContext);
                                AuthorizationService authorizationService = new AuthorizationService(oAuthContext);
                                ClientService        clientService        = new ClientService(oAuthContext);

                                var scopes = (context.Scope.FirstOrDefault() ?? "").Split(',');

                                bool     scopesApproved   = false;
                                Client   OAuthClient      = clientService.GetByApiKey(context.ClientId.AsGuid());
                                string[] authorizedScopes = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLogin.UserName == userName && a.Active == true).Select(a => a.Scope.Identifier).ToArray <string>();
                                if (!clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Any() ||
                                    (authorizedScopes != null && scopes.Where(s => !authorizedScopes.Select(a => a.ToLower()).Contains(s.ToLower())).Count() == 0))
                                {
                                    scopesApproved = true;
                                }

                                if (scopesApproved)
                                {
                                    var identity = new ClaimsIdentity(new GenericIdentity(userName, OAuthDefaults.AuthenticationType));

                                    //only allow claims that have been requested and the client has been authorized for
                                    foreach (var scope in scopes.Where(s => clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope.Identifier.ToLower()).Contains(s.ToLower())))
                                    {
                                        identity.AddClaim(new Claim("urn:oauth:scope", scope));
                                    }
                                    UserLoginService.UpdateLastLogin(userName);
                                    context.Validated(identity);
                                    return(System.Threading.Tasks.Task.FromResult(0));
                                }
                                else
                                {
                                    context.Rejected();
                                    context.SetError("Authentication Error", "All scopes are not authorized for this user.");
                                }
                            }
                            if (!userLogin.IsConfirmed ?? true)
                            {
                                context.Rejected();
                                context.SetError("Authentication Error", "Account email is unconfirmed.");
                            }
                            if (userLogin.IsLockedOut ?? false)
                            {
                                context.Rejected();
                                context.SetError("Authentication Error", "Account is locked.");
                            }
                        }
                        else
                        {
                            context.Rejected();
                            context.SetError("Authentication Error", "Invalid Username/Password.");
                        }
                    }
                    else
                    {
                        context.Rejected();
                        context.SetError("Authentication Error", "Invalid Authentication Configuration.");
                    }
                }
                else
                {
                    context.Rejected();
                    context.SetError("Authentication Error", "Invalid Username/Password.");
                }
            }
            else
            {
                context.Rejected();
                context.SetError("Authentication Error", "Invalid Username/Password.");
            }

            return(System.Threading.Tasks.Task.FromResult(0));
        }
        public TokenBase ExchangeRequestTokenForAccessToken(IRequest request)
        {
            OAuthContext context = _contextFactory.FromMonoRailRequest(request);

            return(_provider.ExchangeRequestTokenForAccessToken(context));
        }
 public void SignContext(OAuthContext authContext, SigningContext signingContext)
 {
     signingContext.SignatureBase = authContext.GenerateSignatureBase();
     FindImplementationForAuthContext(authContext).SignContext(authContext, signingContext);
 }
 public AuthorizationCodeFlow(OAuthContext context, 
     AuthorizationCodeStorage authCodeStorage) : base(context)
 {
     _authorizationCodestorage = authCodeStorage;
 }
 public bool ValidateSignature(OAuthContext authContext, SigningContext signingContext)
 {
     signingContext.SignatureBase = authContext.GenerateSignatureBase();
     return FindImplementationForAuthContext(authContext).ValidateSignature(authContext, signingContext);
 }
        public TokenBase GrantRequestToken(IRequest request)
        {
            OAuthContext context = _contextFactory.FromMonoRailRequest(request);

            return(_provider.GrantRequestToken(context));
        }
 public bool ValidateSignature(OAuthContext authContext, SigningContext signingContext)
 {
     return (authContext.Signature == GenerateSignature(authContext, signingContext));
 }
 private string GenerateSignature(OAuthContext authContext, SigningContext signingContext)
 {
     return UriUtility.UrlEncode(string.Format("{0}&{1}", signingContext.ConsumerSecret, authContext.TokenSecret));
 }
Esempio n. 52
0
        /// <summary>
        /// Page load event with oauth token handling
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string channel = string.Empty;
                OContext = OAuthContext.Current;

                if (!IsPostBack && OContext != null)
                {
                    //End authentication and register tokens.
                    OContext.EndAuthenticationAndRegisterTokens();
                    //Retrieve token by verification
                    OContext.GetAccessToken();

                    //Restore tokens from session
                    if (Session["fbAccessToken"] != null)
                        fbAccessToken.Text = Session["fbAccessToken"].ToString();
                    if (Session["twToken"] != null)
                        twToken.Text = Session["twToken"].ToString();
                    if (Session["twTknSecret"] != null)
                        twTknSecret.Text = Session["twTknSecret"].ToString();
                    if (Session["twVerifier"] != null)
                        twVerifier.Text = Session["twVerifier"].ToString();
                    if (Session["gpToken"] != null)
                        gpToken.Text = Session["gpToken"].ToString();
                    if (Session["gpTknSecret"] != null)
                        gpTknSecret.Text = Session["gpTknSecret"].ToString();
                    if (Session["gpVerifier"] != null)
                        gpVerifier.Text = Session["gpVerifier"].ToString();

                    if (Session["channel"] != null)
                        channel = Session["channel"].ToString();

                    if (channel == Channel.Facebook.ToString())
                    {
                        fbAccessToken.Text = OContext.AccessToken;
                        Session["fbAccessToken"] = OContext.AccessToken;
                    }
                    else if (channel == Channel.Twitter.ToString())
                    {
                        twToken.Text = OContext.AccessToken;
                        Session["twToken"] = OContext.AccessToken;

                        twTknSecret.Text = OContext.AccessTokenSecret;
                        Session["twTknSecret"] = OContext.AccessTokenSecret;

                        twVerifier.Text = OContext.Verifier;
                        Session["twVerifier"] = OContext.Verifier;
                    }
                    else if (channel == Channel.GooglePlus.ToString())
                    {
                        gpToken.Text = OContext.AccessToken;
                        Session["gpToken"] = OContext.AccessToken;

                        gpTknSecret.Text = OContext.AccessTokenSecret;
                        Session["gpTknSecret"] = OContext.AccessTokenSecret;

                        gpVerifier.Text = OContext.Verifier;
                        Session["gpVerifier"] = OContext.Verifier;
                    }

                }
            }
            catch (OAuthException ex)
            {
                txtFBResponse.Text = "OAuth Exception occurred " + ex.InnerException.Message;
            }
        }
Esempio n. 53
0
 public UnitOfWork(OAuthContext context)
 {
     dbContext = context;
 }
 public void SignContext(OAuthContext authContext, SigningContext signingContext)
 {
     authContext.Signature = GenerateSignature(authContext, signingContext);
 }
        public HttpResponseMessage ForgotPassword([FromBody] string email)
        {
            OAuthContext  oAuthContext  = new OAuthContext();
            ClientService clientService = new ClientService(oAuthContext);
            var           clientId      = HttpContext.Current.User.Identity.Name;
            Client        oAuthClient   = clientService.GetByApiKey(clientId.AsGuid());

            if (oAuthClient.Active)
            {
                var              response         = new StandardResponse();
                var              rockContext      = new Rock.Data.RockContext();
                PersonService    personService    = new PersonService(rockContext);
                UserLoginService userLoginService = new UserLoginService(rockContext);
                bool             hasAccountWithPasswordResetAbility = false;
                var              results = new List <IDictionary <string, object> >();

                // Check to make sure we have accounts matching the email address given
                foreach (Person person in personService.GetByEmail(email)
                         .Where(p => p.Users.Any()))
                {
                    var users = new List <UserLogin>();
                    foreach (UserLogin user in userLoginService.GetByPersonId(person.Id))
                    {
                        if (user.EntityType != null)
                        {
                            var component = Rock.Security.AuthenticationContainer.GetComponent(user.EntityType.Name);
                            if (component != null && !component.RequiresRemoteAuthentication)
                            {
                                users.Add(user);
                                hasAccountWithPasswordResetAbility = true;
                            }
                        }
                    }

                    var resultsDictionary = new Dictionary <string, object>();
                    resultsDictionary.Add("Person", person);
                    resultsDictionary.Add("Users", users);
                    results.Add(resultsDictionary);
                }
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, null);

                // If we found matching accounts that have the ability to be reset, go ahead and send the email
                if (results.Count > 0 && hasAccountWithPasswordResetAbility)
                {
                    mergeFields.Add("Results", results.ToArray());

                    var emailMessage = new RockEmailMessage(Rock.SystemGuid.SystemCommunication.SECURITY_FORGOT_USERNAME.AsGuid());
                    emailMessage.AddRecipient(RockEmailMessageRecipient.CreateAnonymous(email, mergeFields));
                    emailMessage.AppRoot = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                    emailMessage.CreateCommunicationRecord = false;
                    emailMessage.Send();
                    response.Result  = StandardResponse.ResultCode.Success;
                    response.Message = "Forgot password email has been sent successfully.";
                }
                else
                {
                    // the person either has no user accounts or none of them are allowed to have their passwords reset (Facebook/Google/SMS/etc)
                    response.Result  = StandardResponse.ResultCode.Error;
                    response.Message = "No accounts associated with this email address are able to be reset via email.";
                }
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, response));
            }

            return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden));
        }
Esempio n. 56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DocumentationService{T}"/> class.
 /// </summary>
 public OAuthService(OAuthContext context)
     : base(context)
 {
 }
        public HttpResponseMessage SMSLogin([FromBody] string phoneNumber)
        {
            OAuthContext  oAuthContext  = new OAuthContext();
            ClientService clientService = new ClientService(oAuthContext);
            var           clientId      = HttpContext.Current?.User?.Identity?.Name;

            if (clientId.IsNullOrWhiteSpace())
            {
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden));
            }

            Client oAuthClient = clientService.GetByApiKey(clientId.AsGuid());

            if (oAuthClient != null && oAuthClient.Active)
            {
                Rock.Data.RockContext rockContext = new Rock.Data.RockContext();
                var smsAuth = ( SMSAuthentication )Rock.Security.AuthenticationContainer.GetComponent("Rock.Security.ExternalAuthentication.SMSAuthentication");

                PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);
                var numberOwners = phoneNumberService.Queryable()
                                   .Where(pn => pn.Number == phoneNumber)
                                   .Select(pn => pn.Person)
                                   .DistinctBy(p => p.Id)
                                   .ToList();

                SMSLoginResponse loginResponse = new SMSLoginResponse();
                // If we don't have this phone number
                if (numberOwners.Count == 0)
                {
                    loginResponse.Result  = SMSLoginResponse.ResultCode.NoMatch;
                    loginResponse.Message = "There was an issue with your request";
                }
                // If we match more than 1 person
                else if (numberOwners.Count > 1)
                {
                    loginResponse.Result  = SMSLoginResponse.ResultCode.MultipleMatch;
                    loginResponse.Message = "There was an issue with your request";
                }
                // If we've matched a single person
                else if (numberOwners.Count == 1)
                {
                    var person = numberOwners.FirstOrDefault();
                    // Make sure the person is alive
                    if (person.IsDeceased)
                    {
                        loginResponse.Result  = SMSLoginResponse.ResultCode.NoMatch;
                        loginResponse.Message = "There was an issue with your request";
                        return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, loginResponse));
                    }

                    // Check the age of the person
                    var minimumAge = smsAuth.GetAttributeValue("MinimumAge").AsInteger();
                    if (minimumAge != 0)
                    {
                        if (person.Age == null)
                        {
                            loginResponse.Result  = SMSLoginResponse.ResultCode.Error;
                            loginResponse.Message = string.Format("We could not determine your age. You must be at least {0} years old to log in.", minimumAge);
                            return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, loginResponse));
                        }
                        if (person.Age.Value < minimumAge)
                        {
                            loginResponse.Result  = SMSLoginResponse.ResultCode.Error;
                            loginResponse.Message = string.Format("You must be at least {0} years old to log in.", minimumAge);
                            return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, loginResponse));
                        }
                    }

                    // If we get all the way here, go ahead and attempt to login!
                    var response = smsAuth.SendSMSAuthentication(phoneNumber);
                    if (response)
                    {
                        loginResponse.Result   = SMSLoginResponse.ResultCode.Success;
                        loginResponse.Message  = "We have sent you a code please enter it to login.";
                        loginResponse.Username = "******" + person.Id.ToString();
                    }
                    else
                    {
                        loginResponse.Result  = SMSLoginResponse.ResultCode.Error;
                        loginResponse.Message = "An unknown error occurred.";
                    }
                }
                else
                {
                    loginResponse.Result  = SMSLoginResponse.ResultCode.Error;
                    loginResponse.Message = "An unknown error occurred.";
                }

                return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, loginResponse));
            }

            return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden));
        }
 public AccountRepository()
 {
     _ctx = new OAuthContext();
 }
Esempio n. 59
0
 public ImplicitFlow(OAuthContext context)
     : base(context)
 {
 }