Example #1
0
 public S3Grantee(GrantType type, string?id, string?displayName, string?uri)
 {
     Type        = type;
     Id          = id;
     DisplayName = displayName;
     Uri         = uri;
 }
Example #2
0
            public HttpRequestMessage ToHttpRequestMessage()
            {
                var query = new Dictionary <string, string>()
                {
                    { "grant_type", GrantType.ToString() },
                    { "redirect_uri", RedirectUri },
                    { "client_id", ClientId },
                    { "client_secret", ClientSecret },
                };

                switch (GrantType)
                {
                case GrantType.authorization_code:
                    query.Add("code", Code);
                    break;

                case GrantType.refresh_token:
                    query.Add("refresh_token", RefreshToken);
                    break;
                }
                var message = new HttpRequestMessage(HttpMethod.Post, Constants.URL.API.OAuth.Token)
                {
                    Content = new FormUrlEncodedContent(query), // Content-Type: application/x-www-form-urlencoded
                };

                message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                return(message);
            }
Example #3
0
 public AclEntry(AclScope scope, AclType type, string upnOrObjectId, GrantType grant)
 {
     Scope         = scope;
     AclType       = type;
     UpnOrObjectId = upnOrObjectId;
     Grant         = grant;
 }
        private static string BuildAuthUrl(string baseAuthUrl, GrantType grantType, OAuth2Parameters parameters)
        {
            StringBuilder authUrl = new StringBuilder(baseAuthUrl);

            if (grantType == GrantType.AuthorizationCode)
            {
                authUrl.Append("&response_type=code");
            }
            else if (grantType == GrantType.ImplicitGrant)
            {
                authUrl.Append("&response_type=token");
            }
            if (parameters != null)
            {
                foreach (string parameterName in parameters)
                {
                    string parameterNameEncoded = HttpUtils.UrlEncode(parameterName);
                    foreach (string parameterValue in parameters.GetValues(parameterName))
                    {
                        authUrl.AppendFormat("&{0}={1}", parameterNameEncoded, HttpUtils.UrlEncode(parameterValue));
                    }
                }
            }
            return(authUrl.ToString());
        }
Example #5
0
 public static void CheckAllowGenerateToken(GrantType grantType)
 {
     if (!IsAllowGenerateToken(grantType))
     {
         throw new CoreException(nameof(ErrorCode.GrantTypeInValid), ErrorCode.GrantTypeInValid);
     }
 }
Example #6
0
        private GrantBE Grants_Populate(IDataReader dr, GrantType grantType)
        {
            GrantBE grant = new GrantBE();

            grant.Id     = dr.Read <uint>("grantid");
            grant.PageId = dr.Read <uint>("pageid");
            if (grantType == GrantType.USER)
            {
                grant.UserId = dr.Read <uint>("userid");
            }
            else if (grantType == GrantType.GROUP)
            {
                grant.GroupId = dr.Read <uint>("groupid");
            }
            grant.ExpirationDate       = dr.Read <DateTime>("grant_expire_date", DateTime.MaxValue);
            grant.TimeStamp            = dr.Read <DateTime>("last_edit");
            grant.CreatorUserId        = dr.Read <uint>("grant_creator_userid");
            grant.Role                 = new RoleBE();
            grant.RoleId               = grant.Role.ID = dr.Read <uint>("role_id");
            grant.Role.Name            = dr.Read <string>("role_name", string.Empty);
            grant.Role.PermissionFlags = dr.Read <ulong>("role_perm_flags");
            grant.Role.TimeStamp       = dr.Read <DateTime>("role_last_edit");
            grant.Role.CreatorUserId   = dr.Read <uint>("role_creator_userid");
            grant.Role.Type            = RoleType.ROLE;
            grant.Type                 = grantType;
            return(grant);
        }
Example #7
0
        /// <summary>
        /// Generates the json web token.
        /// </summary>
        /// <param name="user">UserDTO</param>
        /// <returns>A JwtSecurityToken object.</returns>
        private async Task <JwtSecurityToken> GetJwtSecurityToken(User user, GrantType grantType)
        {
            var expiresAfterHours          = _jwtTokenSettings.ExpiresAfterHours;
            IEnumerable <Claim> userClaims = new List <Claim>();
            var principal = await _signInManager.CreateUserPrincipalAsync(user);

            switch (grantType)
            {
            case GrantType.Password:
                userClaims = principal.Claims.Union(GetUserClaims(user)).Distinct();
                break;

            case GrantType.Tenant:
                userClaims = principal.Claims.Union(GetTenantClaims(user)).Distinct();
                //expiresAfterHours = 24;
                break;
            }

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtTokenSettings.SecurityKey));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var token       = new JwtSecurityToken(
                issuer: _jwtTokenSettings.SiteAddress,
                audience: _jwtTokenSettings.Audience,
                claims: userClaims,
                expires: DateTime.UtcNow.AddHours(expiresAfterHours),
                signingCredentials: credentials
                );

            return(token);
        }
Example #8
0
        /// <summary>
        /// Get a new access token (and possibly refresh token)
        /// </summary>
        public string GetAccessToken(GrantType grantType, string token, out string refreshToken)
        {
            try
            {
                var client  = new RestClient(this.Endpoint);
                var request = new RestRequest("v1/oauth2/token", Method.POST);
                refreshToken = "";

                //there should be an easier way of sending basic auth? similar to oauth v1:
                //client.Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);

                request.AddHeader("Authorization", "Basic " + EncodedAuthString);

                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("Cache-Control", "no-cache");

                switch (grantType)
                {
                case GrantType.client_credentials:
                    request.AddParameter("grant_type", "client_credentials");
                    break;

                case GrantType.refresh_token:
                    request.AddParameter("grant_type", "refresh_token");
                    request.AddParameter("refresh_token", token);
                    break;

                case GrantType.authorization_code:
                    request.AddParameter("grant_type", "authorization_code");
                    request.AddParameter("code", token);
                    request.AddParameter("redirect_url", RedirectUrl);
                    break;
                }

                var response = client.Execute(request);

                string result = response.Content;
                if (
                    result.Contains("error") ||
                    result.Contains("invalid_request") ||
                    result.Contains("invalid_client") ||
                    result.Contains("invalid_grant") ||
                    result.Contains("invalid") ||
                    result.Contains("unauthorized_client") ||
                    result.Contains("unsupported_grant_type") ||
                    result.Contains("invalid_scope")
                    )
                {
                    string msg = "Error getting access token from Neteller: " + response.Content;
                    logger.Fatal(msg);
                    throw new NetellerException(msg, response);
                }

                return(GetAccessTokenAndRefreshToken(response.Content, out refreshToken));
            }
            catch (Exception ex) {
                logger.Fatal("Error getting access token from Neteller: " + ex.ToString());
                throw;
            }
        }
Example #9
0
        private async Task<TokenResult> AccessTokenAsync(GrantType grantType, string refreshToken = null, string userName = null,
            string password = null, string authorizationCode = null, string redirectUri = null)
        {
            var parameters = new Dictionary<string, string> { { "grant_type", grantType.GetText() } };

            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
            {
                parameters.Add("mobile", userName);
                parameters.Add("password", password);
            }
            if (!string.IsNullOrEmpty(authorizationCode))
            {
                parameters.Add("code", authorizationCode);
                parameters.Add("redirect_uri", redirectUri); //和获取 authorization_code 的 redirect_uri 必须一致,不然会报错
            }
            if (!string.IsNullOrEmpty(refreshToken))
            {
                parameters.Add("refresh_token", refreshToken);
            }

            ClientHelper.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Basic",
                Convert.ToBase64String(Encoding.ASCII.GetBytes(_clientId + ":" + _clientSecret)));

            var response = await ClientHelper.PostAsync(TokenPath, new FormUrlEncodedContent(parameters));
            var responseValue = await response.Content.ReadAsStringAsync();
            if (response.StatusCode == HttpStatusCode.OK)
                return JsonHelper.Json<TokenResult>(responseValue, NamingType.UrlCase);
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(responseValue);
            return null;
        }
Example #10
0
        public ActionResult Create([Bind(Include = "Id, Name, Amount, GrantTypeGroup")] GrantType grantType)
        {
            Db db = new Db(DbServices.ConnectionString);

            if (ModelState.IsValid)
            {
                try
                {
                    GrantTypeServices.Insert(CurrentUser.Id, grantType, db);
                    TempData["Success"] = ResourceServices.GetString(Cf.Data.Resources.ResourceBase.Culture, "UI", "InsertConfirmed");
                    return(RedirectToAction("Index"));
                }
                catch (CfException cfex)
                {
                    TempData["Failure"] = cfex.ErrorDefinition.LocalizedMessage;
                }
                catch (Exception ex)
                {
                    TempData["Failure"] = ex.Message;
                }
            }

            ViewBag.GrantTypeGroupList = new SelectList(GrantTypeGroupServices.List(db), "Id", "Name");
            return(View(grantType));
        }
Example #11
0
        public static void Authorize(GrantType grantType, string key)
        {
            using (WebClient client = new WebClient()) {
                string typeParam = grantType == GrantType.Pin ? "pin" : "refresh_token";
                string clientID  = Settings.Default.ClientID;
                string data      = "client_id=" + clientID + "&" +
                                   "client_secret=" + Settings.Default.ClientSecret + "&" +
                                   "grant_type=" + typeParam + "&" +
                                   typeParam + "=" + key;

                client.Headers["Content-Type"]  = "application/x-www-form-urlencoded";
                client.Headers["Authorization"] = "Client-ID " + clientID;
                string response;
                try {
                    response = client.UploadString(Settings.Default.TokenURL, data);
                }
                catch (Exception ex) {
                    throw new AuthorizationException();
                }
                AuthResponse imgur    = JsonConvert.DeserializeObject <AuthResponse>(response);
                Settings     settings = Settings.Default;
                settings.UserName     = imgur.account_username;
                settings.AccessToken  = imgur.access_token;
                settings.RefreshToken = imgur.refresh_token;
                settings.Save();
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["personKey"] == null)
        {
            Response.Redirect("Default.aspx");
        }

        Community_AssistEntities db = new Community_AssistEntities();

        List <GrantType> queryResult =
            (from gt in db.GrantTypes select gt).ToList <GrantType>();

        foreach (GrantType gt in queryResult)
        {
            GrantType grantType = new GrantType();
            grantType.GrantTypeKey  = gt.GrantTypeKey;
            grantType.GrantTypeName = gt.GrantTypeName;

            grantTypes.Add(grantType);
        }

        List <string> grantNames = new List <string>();

        foreach (var gt in grantTypes)
        {
            grantNames.Add(gt.GrantTypeName);
        }

        if (!Page.IsPostBack)
        {
            DropDownList1.DataSource = grantNames;
            DropDownList1.DataBind();
        }
    }
Example #13
0
 public static void CheckAllowAuthorizeFlow(GrantType grantType)
 {
     if (!IsAllowAuthorizeFlow(grantType))
     {
         throw new CoreException(nameof(ErrorCode.GrantTypeInValid), ErrorCode.GrantTypeInValid);
     }
 }
Example #14
0
        private IEnumerable <KeyValuePair <string, string> > BuildRequestFields(GrantType grantType, bool excludeClientIdAndSecret, string code, bool includeRedirectUrl)
        {
            var fields = new Dictionary <string, string>
            {
                { "grant_type", grantType == GrantType.AuthorizationCode ? "authorization_code" : "refresh_token" },
                { grantType == GrantType.AuthorizationCode ? "code" : "refresh_token", code }
            };

            if (includeRedirectUrl)
            {
                fields.Add("redirect_uri", WebUtility.UrlEncode(Definition.RedirectUrl));
            }

            if (!excludeClientIdAndSecret)
            {
                if (!Definition.ExcludeClientIdInTokenRequest)
                {
                    fields.Add("client_id", Definition.ClientId);
                }

                if (!string.IsNullOrEmpty(Definition.ClientSecret) && !Definition.ExcludeClientSecretInTokenRequest)
                {
                    fields.Add("client_secret", Definition.ClientSecret);
                }
            }

            return(fields);
        }
Example #15
0
        public static bool TryParse(string value, out GrantType grantType)
        {
            grantType = GrantType.AuthorizationCode;
            if (String.IsNullOrEmpty(value))
            {
                return(false);
            }

            value = value.ToLower();
            switch (value)
            {
            case "authorization_code":
                grantType = GrantType.AuthorizationCode;
                return(true);

            case "password":
                grantType = GrantType.Password;
                return(true);

            case "refresh_token":
                grantType = GrantType.RefreshToken;
                return(true);

            case "client_credentials":
                grantType = GrantType.ClientCredentials;
                return(true);

            case "user_token":
                grantType = GrantType.UserToken;
                return(true);
            }
            return(false);
        }
Example #16
0
        /// <summary>
        /// Get SSO Token for the v2 Auth flow
        /// </summary>
        public async Task <SsoToken> GetTokenV2(GrantType grantType, string code, string codeVerifier = "", List <string> scopes = null)
        {
            var body = $"grant_type={grantType.ToEsiValue()}";

            body += $"&client_id={_config.ClientId}";

            if (grantType == GrantType.AuthorizationCode)
            {
                body += $"&code={code}";

                var codeVerifierBytes       = Encoding.ASCII.GetBytes(codeVerifier);
                var base64CodeVerifierBytes = Convert.ToBase64String(codeVerifierBytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
                body += $"&code_verifier={base64CodeVerifierBytes}";
            }
            else if (grantType == GrantType.RefreshToken)
            {
                body += $"&refresh_token={code}";

                if (scopes != null)
                {
                    body += $"&scope={string.Join(" ", scopes)}";
                }
            }

            HttpContent postBody = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

            _client.DefaultRequestHeaders.Host = "login.eveonline.com";

            var response = await _client.PostAsync("https://login.eveonline.com/v2/oauth/token", postBody).Result.Content.ReadAsStringAsync();

            var token = JsonConvert.DeserializeObject <SsoToken>(response);

            return(token);
        }
Example #17
0
        /// <summary>
        /// SSO Token helper
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="secretKey"></param>
        /// <param name="grantType"></param>
        /// <param name="code">The authorization_code or the refresh_token</param>
        /// <returns></returns>
        public async Task <SsoToken> GetToken(GrantType grantType, string code)
        {
            var body = $"grant_type={grantType.ToEsiValue()}";

            if (grantType == GrantType.AuthorizationCode)
            {
                body += $"&code={code}";
            }
            else if (grantType == GrantType.RefreshToken)
            {
                body += $"&refresh_token={Uri.EscapeDataString(code)}";
            }

            HttpContent postBody = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _clientKey);

            HttpResponseMessage responseBase = null;

            if (_config.AuthVersion == AuthVersion.v1)
            {
                responseBase = await _client.PostAsync($"{_ssoUrl}/oauth/token", postBody);
            }
            else if (_config.AuthVersion == AuthVersion.v2)
            {
                responseBase = await _client.PostAsync($"{_ssoUrl}/v2/oauth/token", postBody);
            }

            var response = await responseBase.Content.ReadAsStringAsync();

            var token = JsonConvert.DeserializeObject <SsoToken>(response);

            return(token);
        }
 public GenericPermissionGrant(GrantType grantType, GenericNode underlyingNode, int index)
 {
     GrantType      = grantType;
     UnderlyingNode = underlyingNode;
     Index          = index;
     PermissionType = PermissionType.Generic;
 }
        public async Task Authenticate(string refreshToken,
                                       GrantType grantType = GrantType.AuthorizationCode)
        {
            try
            {
                _log.Info("Refreshing token");
                _log.Info("Token type:" + grantType.GetDescription());
                if (refreshToken == null)
                {
                    return;
                }
                var parameters = new Dictionary <string, string>
                {
                    { "grant_type", grantType.GetDescription() },
                    { "redirect_uri", _loginRedirectUrl },
                    { "client_id", AppContracts.ClientId },
                    { "client_secret", AppContracts.ClientSecret }
                };
                if (grantType == GrantType.AuthorizationCode)
                {
                    parameters.Add("code", refreshToken);
                }
                else
                {
                    parameters.Add("refresh_token", refreshToken);
                }
                var postResult =
                    await _authClient.PostAsync(TokenQueryFormat, new FormUrlEncodedContent(parameters)).ConfigureAwait(false);

                var stringResult = await postResult.Content.ReadAsStringAsync().ConfigureAwait(false);

                var token = await Helper.DeserializeStringAsync <Token>(stringResult).ConfigureAwait(false);

                if (token != null)
                {
                    if (grantType == GrantType.RefreshToken)
                    {
                        token.RefreshToken = refreshToken;
                    }
                }
                _settings.SpotifyToken = token;
                if (token != null && token.TokenType != null && token.AccessToken != null)
                {
                    this.DefaultRequestHeaders.Authorization
                        = new AuthenticationHeaderValue(token.TokenType, token.AccessToken);
                    _log.Info("Token refreshed");
                }
                else
                {
                    _log.Info(stringResult);
                }

                _tokenUpdated?.Invoke(token);
            }
            catch (Exception ex)
            {
                _log.FatalException("Update token failed with" + ex.Message, ex);
            }
        }
 public ResourcedPermissionGrant(GrantType grantType, IResourceNode underlyingNode, LNode condition, int index)
 {
     GrantType      = grantType;
     Condition      = condition;
     Index          = index;
     UnderlyingNode = underlyingNode;
     PermissionType = PermissionType.ResourceBound;
 }
Example #21
0
 public bool AddToRole(Role role, Permission permission, GrantType grantOrDeny)
 {
     if (role != null && permission != null && this.CanModifyMembership())
     {
         return(Db.RoleBuilder.Add(role, permission, grantOrDeny));
     }
     return(false);
 }
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
            var currentView = (Auth0LoginPage)e.NewElement;

            _accountService = currentView.AccountService;
            _grantType      = currentView.GrantType;
        }
Example #23
0
 public string BuildAuthenticateUrl(GrantType grantType, OAuth2Parameters parameters)
 {
     if (this.authenticateUrl != null)
     {
         return BuildAuthUrl(this.authenticateUrl, grantType, parameters);
     }
     return this.BuildAuthorizeUrl(grantType, parameters);
 }
Example #24
0
        public ActionResult DeleteConfirmed(int id)
        {
            GrantType grantType = db.GrantTypes.Find(id);

            db.GrantTypes.Remove(grantType);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public bool AddToRole(Role role, Permission permission, GrantType grantOrDeny)
 {
     if (this.inner.AddToRole(role, permission, grantOrDeny))
     {
         RoleMembershipMemorySet.Instance.AddPermissionToRole(role.Id, permission.Id, grantOrDeny == GrantType.Grant);
         return(true);
     }
     return(false);
 }
Example #26
0
 private void Init(string issuer, GrantType grantType, string clientId, string clientSecret, string username = null, string password = null)
 {
     EvalGrantType(grantType);
     _issuer       = issuer;
     _clientId     = clientId;
     _clientSecret = clientSecret;
     _username     = username;
     _password     = password;
 }
Example #27
0
 /**
  *<summary>Constructor of <see cref="BitLySharp"/>, use this one if you want to set the grant_type to password</summary>
  *<param name="clientId">The Client ID of the application</param>
  *<param name="clientSecret">The Client Secret of the application</param>
  *<param name="type">Grant Type using during authentication</param>
  *<param name="pass">Password of the user</param>
  *<param name="user">Username</param>
  *<exception cref="ArgumentException">If client id or client secret is null <see cref="ArgumentException"/> will be thrown</exception>
  */
 public BitLy(string clientId, string clientSecret, GrantType type, string user, string pass) : this(clientId, clientSecret)
 {
     grantType = type;
     if (type == GrantType.Password)
     {
         username = user;
         password = pass;
     }
 }
Example #28
0
        public WrikeAuthorizationRequest(string clientId, string clientSecret, GrantType grantType)
        {
            clientId.ValidateParameter(nameof(clientId));
            clientSecret.ValidateParameter(nameof(clientSecret));

            ClientId     = clientId;
            ClientSecret = clientSecret;
            GrantType    = grantType;
        }
Example #29
0
        public List <GrantType> CreateGrantType(GrantType grantType)
        {
            if (!_grantTypeRepository.List().Exists(grt => grt.Type == grantType.Type))
            {
                _grantTypeRepository.Insert(grantType);
            }

            return(_grantTypeRepository.List());
        }
Example #30
0
 // 发放福利的接口
 public OpRes doGrantBenefit(object param, GrantType type, GMUser user)
 {
     if (!m_items.ContainsKey(type))
     {
         LOG.Info("不存在名称为[{0}]的发放福利功能", type);
         return(OpRes.op_res_failed);
     }
     return(m_items[type].doGrantBenefit(param, user));
 }
        protected async override void OnElementChanged(ElementChangedEventArgs <Page> e)
        {
            base.OnElementChanged(e);
            var currentView = (Auth0LoginPage)e.NewElement;

            _accountService = currentView.AccountService;
            _grantType      = currentView.GrantType;
            await ShowLoginPageAsync();
        }
Example #32
0
 public Request(GrantType grantType, string redirectUri, string clientId, string clientSecret, string code = null, string refreshToken = null)
 {
     GrantType    = grantType;
     RedirectUri  = redirectUri;
     ClientId     = clientId;
     ClientSecret = clientSecret;
     Code         = code;         // required when grant_type is "authorization_code"
     RefreshToken = refreshToken; // required when grant_type is "refresh_token"
 }
Example #33
0
        /// <summary>
        /// Gets the grant_type string for a given grant type.
        /// </summary>
        /// <param name="grantType">The grant type.</param>
        /// <returns>The grant_type string to be used in the request messsage.</returns>
        private string GetGrantTypeValue(GrantType grantType)
        {
            switch (grantType)
            {
                case GrantType.AuthCode:
                    return "authorization_code";

                case GrantType.RefreshToken:
                    return "refresh_token";

                default:
                    throw new OneDriveException("Invalid grant type.");
            }
        }
Example #34
0
 protected static String GetResponseType(GrantType grantType)
 {
     switch (grantType) {
         case GrantType.AuthorizationCode:
             return "code";
         case GrantType.ClientCredentials:
             return "client_credentials";
         case GrantType.Password:
             return "password";
         case GrantType.Implicit:
             return "token";
         default:
             throw new ArgumentOutOfRangeException("grantType");
     }
 }
Example #35
0
 protected static String GetGrantTypeString(GrantType grantType)
 {
     switch (grantType) {
         case GrantType.AuthorizationCode:
             return "authorization_code";
         case GrantType.ClientCredentials:
             return "client_credentials";
         case GrantType.Password:
             return "password";
         case GrantType.Implicit:
             throw new InvalidOperationException("implicit?");
         default:
             throw new ArgumentOutOfRangeException("grantType");
     }
 }
Example #36
0
        internal string GetAccessToken(GrantType type, Dictionary<string, string> parameters)
        {
            List<RequestParameter> config = new List<RequestParameter>()
            {
                new RequestParameter(){ Name= "client_id", Value= ClientID},
                new RequestParameter(){ Name="client_secret", Value=ClientSecret}
            };

            switch (type)
            {
                case GrantType.AuthorizationCode:
                    {
                        config.Add(new RequestParameter() { Name = "grant_type", Value = "authorization_code" });
                        config.Add(new RequestParameter() { Name = "code", Value = parameters["code"] });
                        config.Add(new RequestParameter() { Name = "redirect_uri", Value = parameters["redirect_uri"] });
                    }
                    break;
                case GrantType.Password:
                    {
                        config.Add(new RequestParameter() { Name = "grant_type", Value = "password" });
                        config.Add(new RequestParameter() { Name = "username", Value = parameters["username"] });
                        config.Add(new RequestParameter() { Name = "password", Value = parameters["password"] });
                    }
                    break;
                case GrantType.RefreshToken:
                    {
                        config.Add(new RequestParameter() { Name = "grant_type", Value = "refresh_token" });
                        config.Add(new RequestParameter() { Name = "refresh_token", Value = parameters["refresh_token"] });
                    }
                    break;
            }

            var response = Request(AccessTokenUrl, RequestMethod.Post, config.ToArray());

            if (!string.IsNullOrEmpty(response))
            {
                var json = DynamicJson.Parse(response);
                AccessToken = json.access_token;
                return AccessToken;
            }
            else
            {
                return null;
            }
        }
        public string GetWeChatAccessTokenUrl(string requestUrl, GrantType grantType, string code, string refreshToken, string redirectUrl)
        {
            requestUrl += "token.format";

            if (_postArgumentList == null)
                _postArgumentList = new List<KeyValuePair<string, object>>();

            _postArgumentList.Add(new KeyValuePair<string, object>("grant_type", grantType.ToString().ToLower()));

            if (grantType == GrantType.AuthenticationCode)
            {
                //code 
                _postArgumentList.Add(new KeyValuePair<string, object>("code", code));
                _postArgumentList.Add(new KeyValuePair<string, object>("redirect_uri", redirectUrl));
            }
            else
                _postArgumentList.Add(new KeyValuePair<string, object>("refresh_token", refreshToken));
            return requestUrl;
        }
Example #38
0
 internal OAuthAccessToken GetAccessToken(GrantType grantType, Dictionary<string, string> parameters)
 {
     return GetAccessTokenAsync(grantType, parameters).Result;
 }
Example #39
0
        /// <summary>
        /// Get AccessToken Async
        /// </summary>
        /// <param name="grantType">authorization_code、password、refresh_token</param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        internal async Task<OAuthAccessToken> GetAccessTokenAsync(GrantType grantType, Dictionary<string, string> parameters)
        {
            if (parameters == null || parameters.Count == 0)
            {
                throw new ArgumentException("GetAccessTokenAsync Parameters is invalid.");
            }

            HttpWebRequest request = null;
            try
            {
                request = WebRequest.Create(Settings.AccessTokenUrl) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = new CookieContainer();

                parameters.Add("client_id", Settings.AppKey);
                parameters.Add("client_secret", Settings.AppSecret);

                var grant_type = "";
                switch (grantType)
                {
                    case GrantType.AuthorizationCode:
                        grant_type = "authorization_code";
                        break;
                    case GrantType.Password:
                        grant_type = "password";
                        break;
                    case GrantType.RefreshToken:
                        grant_type = "refresh_token";
                        break;
                    default:
                        grant_type = "authorization_code";
                        break;
                }
                parameters.Add("grant_type", grant_type);

                var postBody = parameters.BuildToUrlString();
                var postData = System.Text.Encoding.UTF8.GetBytes(postBody);
                using (var requestStream = await request.GetRequestStreamAsync())
                {
                    await requestStream.WriteAsync(postData, 0, postData.Length);
                }
                using (var response = await request.GetResponseAsync())
                {
                    using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        var result = await sr.ReadToEndAsync();
                        return ConvertToAccessTokenByRegex(result);
                    }
                }
            }
            finally
            {
                if (request != null)
                    request.Abort();
            }
        }
Example #40
0
 private static string BuildAuthUrl(string baseAuthUrl, GrantType grantType, OAuth2Parameters parameters)
 {
     StringBuilder builder = new StringBuilder(baseAuthUrl);
     if (grantType == GrantType.AuthorizationCode)
     {
         builder.Append("&response_type=code");
     }
     else if (grantType == GrantType.ImplicitGrant)
     {
         builder.Append("&response_type=token");
     }
     if (parameters != null)
     {
         foreach (string str in parameters)
         {
             string str2 = HttpUtils.UrlEncode(str);
             foreach (string str3 in parameters.GetValues(str))
             {
                 builder.AppendFormat("&{0}={1}", str2, HttpUtils.UrlEncode(str3));
             }
         }
     }
     return builder.ToString();
 }
Example #41
0
        protected virtual AuthToken GetAccessToken(GrantType type, Dictionary<string, string> parameters)
        {
            List<RequestOption> accessTokenOptions = new List<RequestOption>()
			{
				new RequestOption(){ Name= "client_id", Value= this.Option.ClientId},
				new RequestOption(){ Name="client_secret", Value = this.Option.ClientSecret}
			};

            switch (type)
            {
                case GrantType.AuthorizationCode:
                    {
                        accessTokenOptions.Add(new RequestOption() { Name = "grant_type", Value = "authorization_code" });
                        accessTokenOptions.Add(new RequestOption() { Name = "code", Value = parameters["code"] });
                        accessTokenOptions.Add(new RequestOption() { Name = "redirect_uri", Value = parameters["redirect_uri"] });
                    }
                    break;
                case GrantType.Password:
                    {
                        accessTokenOptions.Add(new RequestOption() { Name = "grant_type", Value = "password" });
                        accessTokenOptions.Add(new RequestOption() { Name = "username", Value = parameters["username"] });
                        accessTokenOptions.Add(new RequestOption() { Name = "password", Value = parameters["password"] });
                    }
                    break;
                case GrantType.RefreshToken:
                    {
                        accessTokenOptions.Add(new RequestOption() { Name = "grant_type", Value = "refresh_token" });
                        accessTokenOptions.Add(new RequestOption() { Name = "refresh_token", Value = parameters["refresh_token"] });
                    }
                    break;
            }

            String response = Post(this.Option.AccessTokenUrl, accessTokenOptions.ToArray());
            if (!string.IsNullOrEmpty(response))
            {
                ParseAccessToken(response);
            }
            return this.Token;
        }
Example #42
0
        /// <summary>
        /// Gets a HTTP request message for authorization.
        /// </summary>
        /// <param name="grantType">The type of grant to be used for this request.</param>
        /// <param name="grantValue">The code or token for the grant.</param>
        /// <returns>The HTTP request message.</returns>
        public HttpRequestMessage GetAuthRequest(GrantType grantType, string grantValue)
        {
            var config = PluginConfiguration.Configuration;

            var content = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("client_id", config.OneDriveClientId),
                new KeyValuePair<string, string>("redirect_uri", RedirectUrl),
                new KeyValuePair<string, string>("client_secret", config.OneDriveClientSecret),
                new KeyValuePair<string, string>("grant_type", GetGrantTypeValue(grantType)),
                new KeyValuePair<string, string>(GetGrantKey(grantType), grantValue)
            };

            switch (grantType)
            {
                case GrantType.AuthCode:
                    content.Add(new KeyValuePair<string, string>("code", grantValue));
                    break;

                case GrantType.RefreshToken:
                    content.Add(new KeyValuePair<string, string>("refresh_token", grantValue));
                    break;
            }

            return new HttpRequestMessage(HttpMethod.Post, BaseTokenUrl)
            {
                Content = new FormUrlEncodedContent(content)
            };
        }
Example #43
0
 public string BuildAuthorizeUrl(GrantType grantType, OAuth2Parameters parameters)
 {
     return BuildAuthUrl(this.authorizeUrl, grantType, parameters);
 }
Example #44
0
 /**
 *<summary>Constructor of <see cref="BitLySharp"/>, use this one if you want to set the grant_type to password</summary>
 *<param name="clientId">The Client ID of the application</param> 
 *<param name="clientSecret">The Client Secret of the application</param>
 *<param name="type">Grant Type using during authentication</param>
 *<param name="pass">Password of the user</param>
 *<param name="user">Username</param>
 *<exception cref="ArgumentException">If client id or client secret is null <see cref="ArgumentException"/> will be thrown</exception>
 */
 public BitLy(string clientId, string clientSecret, GrantType type, string user, string pass) : this(clientId, clientSecret)
 {
     grantType = type;
     if(type == GrantType.Password)
     {
         username = user;
         password = pass;
     }      
    
 }
Example #45
0
        /// <summary>
        /// Gets an OAuth token for requested grant type. 
        /// </summary>
        /// <param name="grantType">The type of grant request</param>
        /// <param name="scopes">List of scopes that is requested</param>
        /// <param name="basicAuthUsername">If you supply this, the basicAuthUsername and basicAuthPassword will be passed as credentials in BasicAuthentication format.  (Needed to generate a token for an addon)</param>
        /// <param name="basicAuthPassword">If you supply this, the basicAuthUsername and basicAuthPassword will be passed as credentials in BasicAuthentication format. </param>
        /// <param name="username">The user name to generate a token on behalf of.  Only valid in
        /// the 'Password' and 'ClientCredentials' grant types.</param>
        /// <param name="code">The authorization code to exchange for an access token.  Only valid in the 'AuthorizationCode' grant type</param>
        /// <param name="redirectUri">The Url that was used to generate an authorization code, and it must match that value.  Only valid in the 'AuthorizationCode' grant.</param>
        /// <param name="password">The user's password to use for authentication when creating a token.  Only valid in the 'Password' grant.</param>
        /// <param name="refreshToken">The refresh token to use to generate a new access token.  Only valid in the 'RefreshToken' grant.</param>
        public HipchatGenerateTokenResponse GenerateToken(
            GrantType grantType, 
            IEnumerable<TokenScope> scopes,
            string basicAuthUsername = null, 
            string basicAuthPassword = null, 
            string username = null,  
            string code = null, 
            string redirectUri = null, 
            string password = null, 
            string refreshToken = null)
        {
            using (JsonSerializerConfigScope())
            {
                var request = new GenerateTokenRequest
                {
                    Username = username,
                    Code = code,
                    GrantType = grantType,
                    Password = password,
                    RedirectUri = redirectUri,
                    RefreshToken = refreshToken,
                    Scope = string.Join(" ", scopes.Select(x => x.ToString()))
                };

                Action<HttpWebRequest> requestFilter = x => { };
                if (!basicAuthUsername.IsEmpty() && !basicAuthPassword.IsEmpty())
                {
                    var auth = string.Format("{0}:{1}", basicAuthUsername, basicAuthPassword);
                    var encrypted = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
                    var creds = string.Format("{0} {1}", "Basic", encrypted);
                    requestFilter = x => x.Headers[HttpRequestHeader.Authorization] = creds;
                }

                var endpoint = HipchatEndpoints.GenerateTokenEndpoint;

                var form = request.FormEncodeHipchatRequest();
                try
                {
                    var response = endpoint
                        .PostToUrl(request.FormEncodeHipchatRequest(), requestFilter: requestFilter)
                        .FromJson<HipchatGenerateTokenResponse>();
                    return response;
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "");

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "GenerateToken");
                }
            }
        }
 private static string BuildAuthUrl(string baseAuthUrl, GrantType grantType, OAuth2Parameters parameters)
 {
     StringBuilder authUrl = new StringBuilder(baseAuthUrl);
     if (grantType == GrantType.AuthorizationCode)
     {
         authUrl.Append("&response_type=code");
     }
     else if (grantType == GrantType.ImplicitGrant)
     {
         authUrl.Append("&response_type=token");
     }
     if (parameters != null)
     {
         foreach (string parameterName in parameters)
         {
             string parameterNameEncoded = HttpUtils.UrlEncode(parameterName);
             foreach (string parameterValue in parameters.GetValues(parameterName))
             {
                 authUrl.AppendFormat("&{0}={1}", parameterNameEncoded, HttpUtils.UrlEncode(parameterValue));
             }
         }
     }
     return authUrl.ToString();
 }
Example #47
0
 public JDCBOAuth2TokenFactory()
 {
     GrantType = OAuthLib.GrantType.AuthorizationCode;
 }
Example #48
0
        internal QqConnectAccessToken GetAccessToken(GrantType type, Dictionary<string, string> parameters)
        {
            var config = new List<RequestParam>(){
                                                    new RequestParam(){Name = "client_id", Value = AppKey},
                                                    new RequestParam(){Name = "client_secret", Value = AppSecret}
                                                };

            switch(type) {
                case GrantType.AuthorizationCode: {
                        config.Add(new RequestParam() { Name = "grant_type", Value = "authorization_code" });
                        config.Add(new RequestParam() { Name = "code", Value = parameters["code"] });
                        config.Add(new RequestParam() { Name = "redirect_uri", Value = parameters["redirect_uri"] });
                    }
                    break;
                case GrantType.Password: {
                        config.Add(new RequestParam() { Name = "grant_type", Value = "password" });
                        config.Add(new RequestParam() { Name = "username", Value = parameters["username"] });
                        config.Add(new RequestParam() { Name = "password", Value = parameters["password"] });
                    }
                    break;
                case GrantType.RefreshToken: {
                        config.Add(new RequestParam() { Name = "grant_type", Value = "refresh_token" });
                        config.Add(new RequestParam() { Name = "refresh_token", Value = parameters["refresh_token"] });
                    }
                    break;
            }

            var response = OAuth.DoRequest(AccessTokenUrl, RequestMethod.Post, config.ToArray());

            if(!string.IsNullOrEmpty(response)) {
                var queryParameter = HttpUtility.ParseQueryString(response);
                var token = new QqConnectAccessToken();
                if(!string.IsNullOrEmpty(queryParameter["access_token"])) {
                    token.Token = queryParameter["access_token"];
                }
                if(!string.IsNullOrEmpty(queryParameter["expires_in"])) {
                    token.ExpiresIn = Convert.ToInt32(queryParameter["expires_in"]);
                }
                AccessToken = token.Token;
                return token;
            } else {
                return null;
            }
        }
Example #49
0
        public HipchatGenerateTokenResponse GenerateToken(
            GrantType grantType, 
            IEnumerable<TokenScope> scopes,
            string username = null,  
            string code = null, 
            string redirectUri = null, 
            string password = null, 
            string refreshToken = null)
        {
            using (JsonSerializerConfigScope())
            {
                var request = new GenerateTokenRequest
                {
                    Username = username,
                    Code = code,
                    GrantType = grantType,
                    Password = password,
                    RedirectUri = redirectUri,
                    RefreshToken = refreshToken,
                    Scope = string.Join(" ", scopes.Select(x => x.ToString()))
                };

                try
                {
                    return HipchatEndpoints.GenerateTokenEndpoint
                        .AddHipchatAuthentication(_authToken)
                        .PostJsonToUrl(request)
                        .FromJson<HipchatGenerateTokenResponse>();
                }
                catch (Exception exception)
                {
                    if (exception is WebException)
                        throw ExceptionHelpers.WebExceptionHelper(exception as WebException, "");

                    throw ExceptionHelpers.GeneralExceptionHelper(exception, "GenerateToken");
                }
            }
        }
Example #50
0
File: OAuth.cs Project: thk-liu/-
        private AccessToken GetAccessToken(GrantType type, Dictionary<String, String> parameters)
        {
            parameters.Add("client_id", AppKey);
            parameters.Add("client_secret", AppSecret);
            parameters.Add("scope", "read");
            parameters.Add("state", "swkeji");

            switch (type)
            {
                case GrantType.AuthorizationCode:
                    parameters.Add("grant_type", "authorization_code");
                    break;
                case GrantType.Password:
                    parameters.Add("grant_type", "password");
                    break;
                case GrantType.RefreshToken:
                    parameters.Add("grant_type", "refresh_token");
                    break;
            }

            WebUtils webUtil = new WebUtils();
            var response = DoAccessTokenPost(parameters);
            if (!String.IsNullOrEmpty(response))
            {
                AccessToken token = JsonConvert.DeserializeObject<AccessToken>(response);
                token.CreateTime = DateTime.Now;
                AccessToken = token.Token;
                return token;
            }
            else
            {
                return null;
            }
        }
Example #51
-1
        internal AccessToken GetAccessToken(GrantType type, Dictionary<string, string> parameters)
        {
            List<WeiboParameter> config = new List<WeiboParameter>()
            {
                new WeiboParameter(){ Name= "client_id", Value= AppKey},
                new WeiboParameter(){ Name="client_secret", Value=AppSecret}
            };

            switch (type)
            {
                case GrantType.AuthorizationCode:
                    {
                        config.Add(new WeiboParameter() { Name = "grant_type", Value = "authorization_code" });
                        config.Add(new WeiboParameter() { Name = "code", Value = parameters["code"] });
                        config.Add(new WeiboParameter() { Name = "redirect_uri", Value = parameters["redirect_uri"] });
                    }
                    break;
                case GrantType.Password:
                    {
                        config.Add(new WeiboParameter() { Name = "grant_type", Value = "password" });
                        config.Add(new WeiboParameter() { Name = "username", Value = parameters["username"] });
                        config.Add(new WeiboParameter() { Name = "password", Value = parameters["password"] });
                    }
                    break;
                case GrantType.RefreshToken:
                    {
                        config.Add(new WeiboParameter() { Name = "grant_type", Value = "refresh_token" });
                        config.Add(new WeiboParameter() { Name = "refresh_token", Value = parameters["refresh_token"] });
                    }
                    break;
            }

            var response = Request(ACCESS_TOKEN_URL, RequestMethod.Post, config.ToArray());

            if (!string.IsNullOrEmpty(response))
            {
                AccessToken token = JsonConvert.DeserializeObject<AccessToken>(response);
                AccessToken = token.Token;
                return token;
            }
            else
            {
                return null;
            }
        }