Esempio n. 1
0
        /// <summary>
        /// 应用授权
        /// </summary>
        /// <returns></returns>
        public static AccessGrant AppAuthorize()
        {
            EnsureInit();
            log.Info("app authorize begin");
            AccessGrant accessGrant = OAuthProvider.AppAuthorize();

            log.InfoFormat("app authorize success. access token: {0}", ag.AccessToken);
            return(accessGrant);
        }
 public ITwitterGateway CreateAuthroizedGateway(OAuthProvider authProvider, string accessToken, string accessTokenSecret)
 {
     return(new TwitterGateway {
         Auth = new TwitterAuth {
             OAuthProvider = authProvider,
             AccessToken = accessToken,
             AccessTokenSecret = accessTokenSecret,
         }
     });
 }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OAuthService"/> class.
        /// </summary>
        public OAuthService()
        {
            var clientProvider = new ClientProvider();
              var tokenProvider = new TokenProvider();
              var passwordProvider = new PasswordProvider();

              var scopes = new List<string>();

              this.oAuthProvider = OAuthFactory.BuildOAuthProvider(clientProvider, tokenProvider, scopes, passwordProvider: passwordProvider);
        }
Esempio n. 4
0
        /// <summary>
        /// OAuth provider.
        /// </summary>
        /// <param name="tokenStore">The token store</param>
        /// <param name="consumerStore">The consumer store</param>
        /// <param name="nonceStore">The nonce store.</param>
        /// <param name="inspectors">The collection of validation inspectors.</param>
        public AuthProvider(ITokenStore tokenStore, IConsumerStore consumerStore, INonceStore nonceStore, params IContextInspector[] inspectors)
        {
            _tokenStore    = tokenStore;
            _consumerStore = consumerStore;
            _nonceStore    = nonceStore;

            ValidateEx();

            // Create a new OAuth provider.
            _oAuthProvider = new OAuthProvider(tokenStore, inspectors);
        }
Esempio n. 5
0
        public override OAuth2Client GetClient()
        {
            var config = OAuthProvider.GetByName("Github").Configuration.Parse <OAuthProviderConfiguration>();

            return(new GitHubClient(new RequestFactory(), new OAuth2.Configuration.ClientConfiguration
            {
                ClientId = config.ClientId.Trim(),
                ClientSecret = config.ClientSecret.Trim(),
                RedirectUri = OAuthProviderHelper.RedirectUrl,
                Scope = "user read:user"
            }));
        }
Esempio n. 6
0
        public override OAuth2Client GetClient()
        {
            var config = OAuthProvider.GetByName("Google").Configuration.Parse <OAuthProviderConfiguration>();

            return(new GoogleClient(new RequestFactory(), new OAuth2.Configuration.ClientConfiguration
            {
                ClientId = config.ClientId.Trim(),
                ClientSecret = config.ClientSecret.Trim(),
                RedirectUri = OAuthProviderHelper.RedirectUrl,
                Scope = "profile email"
            }));
        }
Esempio n. 7
0
        private static IUser LoadOrCreateUserPrivate(OAuthProvider provider, object tokenData, string userId)
        {
            User user;

            using (new SystemAccount())
            {
                user = ContentQuery.Query(SafeQueries.UsersByOAuthId, QuerySettings.AdminSettings, provider.IdentifierFieldName, userId)
                       .Nodes.FirstOrDefault() as User ?? CreateUser(provider, tokenData, userId);
            }

            return(user);
        }
        public void SetUpProvider()
        {
            var tokenStore    = new TestTokenStore();
            var consumerStore = new TestConsumerStore();
            var nonceStore    = new TestNonceStore();

            provider = new OAuthProvider(tokenStore,
                                         new SignatureValidationInspector(consumerStore),
                                         new NonceStoreInspector(nonceStore),
                                         new TimestampRangeInspector(new TimeSpan(1, 0, 0)),
                                         new ConsumerValidationInspector(consumerStore));
        }
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            AppUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                         externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = OAuthProvider.CreateProperties(user);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return(Ok());
        }
Esempio n. 10
0
        public OAuthProvider10Tests()
        {
            var tokenStore    = new TestTokenStore();
            var consumerStore = new TestConsumerStore();
            var nonceStore    = new TestNonceStore();

            provider = new OAuthProvider(tokenStore,
                                         new SignatureValidationInspector(consumerStore),
                                         new NonceStoreInspector(nonceStore),
                                         new TimestampRangeInspector(new TimeSpan(1, 0, 0)),
                                         new ConsumerValidationInspector(consumerStore),
                                         new XAuthValidationInspector(ValidateXAuthMode, AuthenticateXAuthUsernameAndPassword));
        }
 /// <value>
 /// The base URL.
 /// </value>
 public IOAuthProviderSettings this[OAuthProvider name]
 {
     get
     {
         lock (Lock)
         {
             if (Providers[name] == null)
             {
                 throw new Exception("Unable to load default context");
             }
         }
         return(Providers[name]);
     }
 }
        public AuthenticationOwinAspNetApplication()
        {
            InitializeComponent();
            InitializeDefaults();
            AuthenticationMixed authenticationMixed = new AuthenticationMixed();

            authenticationMixed.LogonParametersType = typeof(AuthenticationStandardLogonParameters);
            authenticationMixed.AuthenticationProviders.Add(typeof(AuthenticationStandardProvider).Name, new AuthenticationStandardProvider(typeof(OAuthUser)));
            OAuthProvider authProvider = new OAuthProvider(typeof(OAuthUser), securityStrategyComplex1);

            authProvider.CreateUserAutomatically = true;
            authenticationMixed.AuthenticationProviders.Add(typeof(OAuthProvider).Name, authProvider);
            securityStrategyComplex1.Authentication = authenticationMixed;
        }
Esempio n. 13
0
        public async Task <OAuthUserInfo> GetUserInfo(OAuthProvider provider, string authCode)
        {
            string accessToken = await GetGithubAccessToken(authCode).ConfigureAwait(false);

            var userInfo = await GetGithubUser(accessToken).ConfigureAwait(false);

            return(new OAuthUserInfo
            {
                Name = userInfo.name,
                Email = userInfo.email,
                OAuthProvider = provider.ToString(),
                OAuthUsername = userInfo.login,
                OAuthProviderId = userInfo.id.ToString()
            });
        }
Esempio n. 14
0
        /// <summary>
        /// OAuth provider.
        /// </summary>
        /// <param name="tokenStore">The token store</param>
        /// <param name="consumerStore">The consumer store</param>
        /// <param name="nonceStore">The nonce store.</param>
        public AuthResource(ITokenStore tokenStore, IConsumerStore consumerStore, INonceStore nonceStore)
        {
            _tokenStore    = tokenStore;
            _consumerStore = consumerStore;
            _nonceStore    = nonceStore;

            ValidateEx();

            // Create a new OAuth provider.
            _oAuthProvider = new OAuthProvider(tokenStore,
                                               new SignatureValidationInspector(consumerStore),
                                               new NonceStoreInspector(nonceStore),
                                               new TimestampRangeInspector(new TimeSpan(1, 0, 0)),
                                               new ConsumerValidationInspector(consumerStore));
        }
Esempio n. 15
0
        public async Task <IActionResult> Update([FromRoute] string membershipId, [FromRoute] string id, [FromBody] UpdateProviderFormModel model)
        {
            var providerModel = new OAuthProvider
            {
                Id           = id,
                Name         = model.Name,
                Description  = model.Description,
                MembershipId = membershipId
            };

            var utilizer = this.GetUtilizer();
            var provider = await this.providerService.UpdateAsync(utilizer, membershipId, providerModel);

            return(this.Ok(provider));
        }
Esempio n. 16
0
        public override void Load()
        {
            Bind <IOAuthContextBuilder>().To <OAuthContextBuilder>();
            var nonceStoreInspector         = new NonceStoreInspector(new TestNonceStore());
            var consumerStore               = new TestConsumerStore();
            var signatureInspector          = new SignatureValidationInspector(consumerStore);
            var consumerValidationInspector = new ConsumerValidationInspector(consumerStore);
            var timestampInspector          = new TimestampRangeInspector(new TimeSpan(1, 0, 0));
            var tokenRepository             = new TokenRepository();
            var tokenStore    = new SampleMemoryTokenStore(tokenRepository);
            var oauthProvider = new OAuthProvider(tokenStore, consumerValidationInspector, nonceStoreInspector, timestampInspector, signatureInspector);

            Bind <IOAuthProvider>().ToConstant(oauthProvider);
            Bind <TokenRepository>().ToConstant(tokenRepository);
        }
Esempio n. 17
0
        public IEnumerable <OAuthProvider> GetOAuthProviders()
        {
            var accounts  = OAuthWebSecurity.RegisteredClientData;
            var providers = new List <OAuthProvider>();

            foreach (var acct in accounts)
            {
                var pro = new OAuthProvider();
                pro.ProviderName        = acct.AuthenticationClient.ProviderName;
                pro.ProviderDisplayName = acct.DisplayName;
                providers.Add(pro);
            }

            return(providers);
        }
Esempio n. 18
0
        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind <IOAuthContextBuilder>().To <OAuthContextBuilder>();
            var nonceStoreInspector         = new NonceStoreInspector(new TestNonceStore());
            var consumerStore               = new TestConsumerStore();
            var signatureInspector          = new SignatureValidationInspector(consumerStore);
            var consumerValidationInspector = new ConsumerValidationInspector(consumerStore);
            var timestampInspector          = new TimestampRangeInspector(new TimeSpan(1, 0, 0));
            var tokenRepository             = new TokenRepository();
            var tokenStore    = new SampleMemoryTokenStore(tokenRepository);
            var oauthProvider = new OAuthProvider(tokenStore, consumerValidationInspector, nonceStoreInspector, timestampInspector, signatureInspector);

            kernel.Bind <IOAuthProvider>().ToConstant(oauthProvider);
            kernel.Bind <TokenRepository>().ToConstant(tokenRepository);
        }
Esempio n. 19
0
        private async Task LinkWithApple()
        {
            var user = _auth.CurrentUser;

            if (user == null)
            {
                return;
            }

            try
            {
                IAuthResult result;

                var(idToken, rawNonce) = await _appleService.GetCredentialAsync();

                if (idToken != null)
                {
                    var credential = CrossFirebaseAuth.Current
                                     .OAuthProvider
                                     .GetCredential("apple.com", idToken, rawNonce: rawNonce);

                    result = await user.LinkWithCredentialAsync(credential);
                }
                else
                {
                    var porvider = new OAuthProvider("apple.com")
                    {
                        Scopes = new[] { "email", "name" }
                    };

                    result = await user.LinkWithProviderAsync(porvider);
                }

                Update(user);

                await _pageDialogService.DisplayAlertAsync("Success", result.User.DisplayName, "OK");
            }
            catch (FirebaseAuthException e)
            {
                await ResolveAsync(e);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);

                await _pageDialogService.DisplayAlertAsync("Failure", e.Message, "OK");
            }
        }
        public void DidComplete(ASAuthorizationController controller, ASAuthorization authorization)
        {
            var credential = authorization.GetCredential <ASAuthorizationAppleIdCredential>();

            if (credential != null && !string.IsNullOrEmpty(currentNonce))
            {
                appleToken = credential.IdentityToken.ToString();
                var firebaseCredential = OAuthProvider.GetCredentialWithRawNonce("apple.com", credential.IdentityToken.ToString(), currentNonce);
                Auth.DefaultInstance.SignInWithCredential(firebaseCredential, SignInOnCompletion);
            }
            else
            {
                appleToken = string.Empty;
                SetVerificationStatus(VerificationStatus.Failed, "Sign in failed");
            }
        }
Esempio n. 21
0
        public IEnumerable <OAuthProvider> GetOAuthAccountsForUser(string username)
        {
            var accounts  = OAuthWebSecurity.GetAccountsFromUserName(username);
            var providers = new List <OAuthProvider>();

            foreach (var acct in accounts)
            {
                var pro = new OAuthProvider();
                pro.ProviderName        = acct.Provider;
                pro.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(acct.Provider).DisplayName;
                pro.ProviderUserId      = acct.ProviderUserId;
                providers.Add(pro);
            }

            return(providers);
        }
Esempio n. 22
0
 public WebApiCtx()
 //: this(new Uri("http://ipv4.fiddler:555/"))
     : this(OAuthConfiguration.Configuration.ServiceSettings.Realm)
     //: this(new Uri("http://localhost:555/svc/"))
 {
     OAuthProvider.RegisterDataService(this);
     this.SendingRequest    += Container_SendingRequest;
     this.ReceivingResponse += Container_ReceivingResponse;
     this.IgnoreResourceNotFoundException = true;
     this.ResolveName = new global::System.Func <global::System.Type, string>(this.ResolveNameFromType);
     this.ResolveType = new global::System.Func <string, global::System.Type>(this.ResolveTypeFromName);
     this.OnContextCreated();
     //this.Format.LoadServiceModel = LoadModel;
     //this.Format.UseJson();
     //this.Format.UseAtom();
 }
Esempio n. 23
0
        /// <summary>
        /// OAuth provider.
        /// </summary>
        /// <param name="tokenStore">The token store</param>
        /// <param name="consumerStore">The consumer store</param>
        /// <param name="nonceStore">The nonce store.</param>
        public AuthProvider(ITokenStore tokenStore, IConsumerStore consumerStore, INonceStore nonceStore)
        {
            _tokenStore    = tokenStore;
            _consumerStore = consumerStore;
            _nonceStore    = nonceStore;

            ValidateEx();

            // Create a new OAuth provider.
            _oAuthProvider = new OAuthProvider(tokenStore,
                                               new SignatureValidationInspector(consumerStore),
                                               new NonceStoreInspector(nonceStore),
                                               new TimestampRangeInspector(new TimeSpan(1, 0, 0)),
                                               new ConsumerValidationInspector(consumerStore),
                                               new XAuthValidationInspector(ValidateXAuthMode, AuthenticateXAuthUsernameAndPassword));
        }
Esempio n. 24
0
        public RestApi(ushort apiPort)
        {
            StartOptions = new StartOptions();

            Configuration = ApiConfiguration.Create();

            Configuration.Hosts.ToList().ForEach(host => StartOptions.Urls?.Add(host));

            if (apiPort > 0)
            {
                StartOptions.Urls?.Clear();
                StartOptions.Urls?.Add("http://*:" + apiPort + "/");
            }

            AuthenticationProvider = new OAuthProvider(Configuration);
        }
        public static IAuthProvider Create(OAuthProvider provider)
        {
            switch (provider.Id.ToLower())
            {
            case "qq":
                return(new QqAuthProvider(provider));

            case "weixin":
                return(new WeixinAuthProvider(provider));

            case "sina":
                return(new SinaAuthProvider(provider));

            default: throw new NotSupportedException();
            }
        }
Esempio n. 26
0
        public async Task <IActionResult> Create([FromRoute] string membershipId, [FromBody] CreateProviderFormModel model)
        {
            var membership = await this.membershipService.GetAsync(membershipId);

            if (membership == null)
            {
                return(this.MembershipNotFound(membershipId));
            }

            var providerModel = new OAuthProvider
            {
                Name         = model.Name,
                Description  = model.Description,
                MembershipId = membershipId
            };

            var utilizer = this.GetUtilizer();
            var provider = await this.providerService.CreateAsync(utilizer, membershipId, providerModel);

            return(this.Created($"{this.Request.Scheme}://{this.Request.Host}{this.Request.Path}/{provider.Id}", provider));
        }
Esempio n. 27
0
        private async Task SignInWithProvider(string providerId)
        {
            try
            {
                var porvider = new OAuthProvider(providerId);

                var result = await CrossFirebaseAuth.Current.Instance.SignInWithProviderAsync(porvider);

                await _pageDialogService.DisplayAlertAsync("Success", result.User.DisplayName, "OK");
            }
            catch (FirebaseAuthException e)
            {
                await ResolveAsync(e);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);

                await _pageDialogService.DisplayAlertAsync("Failure", e.Message, "OK");
            }
        }
Esempio n. 28
0
        protected void SetupInspectors()
        {
            //inspectors.Add(new NonceStoreInspector (NonceStore));
            inspectors.Add(new OAuth10AInspector(TokenStore));

            // request tokens may only be 36 hour old
            // HACK this will compare client & server times. if the client time is of
            // by more than 36 ours, the request will fail totally
            inspectors.Add(new TimestampRangeInspector(new TimeSpan(36, 0, 0)));

            // TODO HACK signature validation currently fails
            // this is not so bad, as we rely on SSL for encryption, we just have to make sure
            // the access token is valid elsewhere
            //inspectors.Add(new SignatureValidationInspector (ConsumerStore));

            // will check the consumer_key to be known
            // might be disabled since our consumer_key is public (="anyone")
            // new ConsumerValidationInspector (ConsumerStore)

            Provider = new OAuthProvider(TokenStore, inspectors.ToArray());
        }
Esempio n. 29
0
        public async Task <ActionResult> RefreshToken([FromBody] RefreshTokenRequest model)
        {
            var           cp            = _authService.ResolveClaimsFromToken(model.AccessToken);
            string        userId        = cp.GetUserId();
            OAuthProvider oauthProvider = cp.GetOAuthProvider();

            ValidateRequest(model, userId);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _usersService.FindUserByIdAsync(userId);

            var oauth = _authService.FindOAuthByProvider(userId, oauthProvider);
            var roles = await _usersService.GetRolesAsync(user);

            var responseView = await _authService.CreateTokenAsync(RemoteIpAddress, user, oauth, roles);

            return(Ok(responseView));
        }
Esempio n. 30
0
        protected void SetupInspectors()
        {
            inspectors.Add(new NonceStoreInspector(NonceStore));
            inspectors.Add(new OAuth10AInspector(TokenStore));

            // request tokens may only be 36 hour old
            // HACK this will compare client & server times. if the client time is of
            // by more than 36 ours, the request will fail totally
            inspectors.Add(new TimestampRangeInspector(new TimeSpan(36, 0, 0)));

            // TODO signature validation currently fails
            // don't know if it makes sense to enable this since this
            // verifies the get request_token step, but our conumser_key and consumer_secret are
            // publically known
            // new SignatureValidationInspector (ConsumerStore),

            // will check the consumer_key to be known
            // might be disabled since our consumer_key is public
            // new ConsumerValidationInspector (ConsumerStore)

            Provider = new OAuthProvider(TokenStore, inspectors.ToArray());
        }
Esempio n. 31
0
        public async Task <IActionResult> OAuthProviderDetail(string i, OAuthProvider model)
        {
            var now    = DateTime.Now;
            var result = new Result();

            if (i.IsNullOrEmpty() && model.Id.IsNullOrEmpty())
            {
                result.Error("请输入Id");
                return(Json(result));
            }
            if (model.Name.IsNullOrEmpty())
            {
                result.Error("请输入名称");
                return(Json(result));
            }
            if (model.ClientId.IsNullOrEmpty())
            {
                result.Error("请输入ClientId");
                return(Json(result));
            }
            if (model.ClientSecret.IsNullOrEmpty())
            {
                result.Error("请输入ClientSecret");
                return(Json(result));
            }

            if (!i.IsNullOrEmpty())
            {
                var old = DefaultStorage.OAuthProviderGet(i);
                if (old == null)
                {
                    result.Message = "数据不存在";
                    return(Json(result));
                }

                var status = await TryUpdateModelAsync(old);

                if (status)
                {
                    result.Status = DefaultStorage.OAuthProviderUpdate(old);
                    if (!result.Status)
                    {
                        result.Message = "更新失败";
                    }
                }
                else
                {
                    result.Message = "参数有误";
                }
                return(Json(result));
            }
            var exist = DefaultStorage.OAuthProviderExist(model.Id.Trim());

            if (exist)
            {
                result.Message = "Id已存在";
                return(Json(result));
            }

            model.CreatedOn  = now;
            model.ModifiedBy = string.Empty;
            model.ModifiedOn = now;
            result.Status    = DefaultStorage.OAuthProviderCreate(model);

            if (result.Status)
            {
                result.Success();
            }

            return(Json(result));
        }
 public ExternalLoginResult(OAuthProvider oAuthProvider, string returnUrl)
 {
     Provider = oAuthProvider.ToString().ToLower();
     ReturnUrl = returnUrl;
 }