/// <summary> /// Allows OAuth applications to directly exchange Twitter usernames and passwords for OAuth access tokens and secrets. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>A <see cref="OAuthTokenResponse"/> instance.</returns> public static async Task<OAuthTokenResponse> AccessTokensAsync(string consumerKey, string consumerSecret, string username, string password) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException("username"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } OAuthTokenResponse response = new OAuthTokenResponse(); try { WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HttpMethod.Post, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); builder.Parameters.Add("x_auth_username", username); builder.Parameters.Add("x_auth_password", password); builder.Parameters.Add("x_auth_mode", "client_auth"); HttpResponseMessage httpresponse = await builder.ExecuteRequestAsync(); string responseBody = await httpresponse.Content.ReadAsStringAsync(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; if (responseBody.Contains("user_id=")) response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } return response; }
public void Authorise() { try { OAuth.RequestTokenAsync(SettingsData.Instance.TwitterConsumerKey, SettingsData.Instance.TwitterConsumerSecret, "https://twitter.com/FlattyTweet").ContinueWith((Action<Task<OAuthTokenResponse>>)(r => { if (r.Result != null) { if (!(r.Result.Token != string.Empty)) return; this.requestToken = r.Result; if (this.requestToken != null) { string authorisationurl = OAuth.BuildAuthorizationUri(this.requestToken.Token, false).AbsoluteUri; System.Windows.Application.Current.Dispatcher.Invoke((Action)(() => this.URL = authorisationurl), DispatcherPriority.Background); } } else System.Windows.Application.Current.Dispatcher.Invoke((Action)(() => Messenger.Default.Send<DialogMessage>(new DialogMessage(string.Empty, (Action<MessageBoxResult>)(o => { })), (object)DialogType.SignInSomethingWrong))); })); } catch { } }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred while retrieving the user profile."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); identity.AddOptionalClaim(ClaimTypes.NameIdentifier, MailChimpAuthenticationHelper.GetIdentifier(payload), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Name, MailChimpAuthenticationHelper.GetName(payload), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Email, MailChimpAuthenticationHelper.GetEmail(payload), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Role, MailChimpAuthenticationHelper.GetRole(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:mailchimp:dc", MailChimpAuthenticationHelper.GetDataCenter(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:mailchimp:account_name", MailChimpAuthenticationHelper.GetAccountName(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:mailchimp:login_id", MailChimpAuthenticationHelper.GetLoginId(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:mailchimp:login_email", MailChimpAuthenticationHelper.GetLoginEmail(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:mailchimp:login_url", MailChimpAuthenticationHelper.GetLoginUrl(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:mailchimp:api_endpoint", MailChimpAuthenticationHelper.GetApiEndPoint(payload), Options.ClaimsIssuer); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, properties, Options.AuthenticationScheme); var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, payload); await Options.Events.CreatingTicket(context); return(context.Ticket); }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { HttpRequestMessage request = null; HttpResponseMessage response = null; try { request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred while retrieving the user profile."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload); context.RunClaimActions(payload); // When the email address is not public, retrieve it from // the emails endpoint if the user:email scope is specified. if (!string.IsNullOrEmpty(Options.UserEmailsEndpoint) && !identity.HasClaim(claim => claim.Type == ClaimTypes.Email) && Options.Scope.Contains("user:email")) { var address = await GetEmailAsync(tokens); if (!string.IsNullOrEmpty(address)) { identity.AddClaim(new Claim(ClaimTypes.Email, address, ClaimValueTypes.String, Options.ClaimsIssuer)); } } await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); } finally { request?.Dispose(); response?.Dispose(); } }
/// <inheritdoc /> protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] OAuthCodeExchangeContext context) { string shopDns; try { var shopValue = Context.Request.Query["shop"]; var stateValue = Context.Request.Query["state"]; string shop = shopValue.ToString(); // Shop name must end with myshopify.com if (!shop.EndsWith(".myshopify.com", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("shop parameter is malformed. It should end with .myshopify.com"); } // Strip out the "myshopify.com" suffix shopDns = shop.Split('.')[0]; // Verify that the shop name encoded in "state" matches the shop name we used to // request the token. This probably isn't necessary, but it's an easy extra verification. var authenticationProperties = Options.StateDataFormat.Unprotect(stateValue); string shopNamePropertyValue = authenticationProperties.Items[ShopifyAuthenticationDefaults.ShopNameAuthenticationProperty]; if (!string.Equals(shopNamePropertyValue, shopDns, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("Received shop name does not match the shop name specified in the authentication request."); } } catch (Exception ex) { Logger.LogError(ex, "An error occurred while exchanging tokens: {ErrorMessage}", ex.Message); return(OAuthTokenResponse.Failed(ex)); } string uri = string.Format(CultureInfo.InvariantCulture, Options.TokenEndpoint, shopDns); using var request = new HttpRequestMessage(HttpMethod.Post, uri); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); var parameters = new Dictionary <string, string> { ["client_id"] = Options.ClientId, ["client_secret"] = Options.ClientSecret, ["code"] = context.Code }; request.Content = new FormUrlEncodedContent(parameters); using var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving an access token: the remote server returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Success(payload)); }
protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { var queryParams = new Dictionary <string, string>() { { "v", Options.ApiVersion }, { "access_token", tokens.AccessToken }, { "fields", Options.Fields } }; var requestMessage = new HttpRequestMessage(HttpMethod.Get, QueryHelpers.AddQueryString(VkAuthDefaults.UserInformationEndpoint, queryParams)); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await Backchannel.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); response.EnsureSuccessStatusCode(); /*var response = await Backchannel.GetAsync(QueryHelpers.AddQueryString(VkAuthDefaults.AuthorizationEndpoint, queryParams), Context.RequestAborted); * * Console.WriteLine(requestMessage); * if (!response.IsSuccessStatusCode) * { * Logger.LogError($"An error occurred while retrieving the user profile: the remote server " + * $"returned a {response.StatusCode} " + * $"response with the following payload: {response.Headers} " + * $"{await response.Content.ReadAsStringAsync()}."); * throw new HttpRequestException("An error occurred while retrieving the user profile."); * } * * Console.WriteLine(response);*/ var user = JObject.Parse(await response.Content.ReadAsStringAsync())["response"].First as JObject; Console.WriteLine(user); if (tokens.Response["email"] != null) { user.Add("email", tokens.Response["email"]); } var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, user); context.RunClaimActions(user); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); }
public ActionResult GetPostTokenTwitter() { var pcr = _providerConfigurationService.Get("Twitter"); if (pcr == null) { _notifier.Add(NotifyType.Error, T("No twitter account setting added, add one in Settings -> Open Authentication")); return(RedirectToAction("Index", "TwitterAccount", new { area = "Laser.Orchard.Twitter", id = -10 })); } string consumerKey = pcr.ProviderIdKey; string consumerSecret = pcr.ProviderSecret; // il meccanismo utilizzato è il 3-Legged oAuth if (Request["oauth_token"] == null) { string tmpreq = Request.Url.AbsoluteUri; OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, tmpreq); Response.Redirect(string.Format("https://api.twitter.com/oauth/authorize?oauth_token={0}", reqToken.Token)); } else { string requestToken = Request["oauth_token"].ToString(); string verifier = Request["oauth_verifier"].ToString(); var tokens = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, requestToken, verifier); TwitterAccountVM vm = new TwitterAccountVM(); vm.DisplayAs = tokens.ScreenName; vm.UserToken = tokens.Token; vm.UserTokenSecret = tokens.TokenSecret; // conterrà l'account_token_secret #region [recupero immagine] OAuthTokens accessToken = new OAuthTokens(); accessToken.AccessToken = vm.UserToken; accessToken.AccessTokenSecret = vm.UserTokenSecret; accessToken.ConsumerKey = consumerKey; accessToken.ConsumerSecret = consumerSecret; TwitterResponse <TwitterUser> myTwitterUser = TwitterUser.Show(accessToken, tokens.ScreenName); TwitterUser user = myTwitterUser.ResponseObject; var profilePictureUrl = user.ProfileImageLocation; var mediaPath = HostingEnvironment.IsHosted ? HostingEnvironment.MapPath("~/Media/") ?? "" : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Media"); WebClient webClient = new WebClient(); webClient.DownloadFile(profilePictureUrl, mediaPath + _shellSettings.Name + @"\twitter_" + vm.DisplayAs + ".jpg"); #endregion // var avatarFormat = "https://api.twitter.com/1.1/users/show.json?screen_name={0}"; // var avatarUrl = string.Format(avatarFormat, vm.DisplayAs); // HttpWebRequest avatarRequest = (HttpWebRequest)WebRequest.Create(avatarUrl); // var timelineHeaderFormat = "{0} {1}"; // avatarRequest.Headers.Add("Authorization", String.Format("Bearer {0}", vm.UserToken)); //// avatarRequest.Headers.Add("Authorization", //// string.Format(timelineHeaderFormat, "oauth_token", requestToken)); // avatarRequest.Method = "Get"; // WebResponse timeLineResponse = avatarRequest.GetResponse(); // var reader = new StreamReader(timeLineResponse.GetResponseStream()); // var avatarJson = string.Empty; //using (authResponse) { // using (var reader = new StreamReader(timeLineResponse.GetResponseStream())) { // avatarJson = reader.ReadToEnd(); // } //} // Uri profilePictureUrl = new Uri(string.Format("https://api.twitter.com/1.1/users/show.json?screen_name={1}", vm.DisplayAs )); OrchardRegister(vm); } return(RedirectToAction("Index", "TwitterAccount", new { area = "Laser.Orchard.Twitter", id = -10 })); }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { var address = Options.UserInformationEndpoint; // If at least one field is specified, // append the fields to the endpoint URL. if (Options.Fields.Count != 0) { address = address.Insert(address.LastIndexOf("~") + 1, $":({ string.Join(",", Options.Fields)})"); } var request = new HttpRequestMessage(HttpMethod.Get, address); request.Headers.Add("x-li-format", "json"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred while retrieving the user profile."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload); context.RunClaimActions(payload); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred while retrieving the user profile."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); identity.AddOptionalClaim(ClaimTypes.NameIdentifier, YammerAuthenticationHelper.GetId(payload), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.GivenName, YammerAuthenticationHelper.GetFirstName(payload), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Surname, YammerAuthenticationHelper.GetLastName(payload), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Name, YammerAuthenticationHelper.GetName(payload), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Email, YammerAuthenticationHelper.GetEmail(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:yammer:link", YammerAuthenticationHelper.GetLink(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:yammer:job_title", YammerAuthenticationHelper.GetJobTitle(payload), Options.ClaimsIssuer); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, properties, Options.AuthenticationScheme); var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, payload); await Options.Events.CreatingTicket(context); return(context.Ticket); }
public static string GetByKey(this OAuthTokenResponse response, string key) { return(response.Response.RootElement.GetString(key)); }
public static string GetErrorMsg(this OAuthTokenResponse response) { return(response.GetByKey("errmsg")); }
public static string GetErrorCode(this OAuthTokenResponse response) { return(response.GetByKey("errcode")); }
public static string GetScope(this OAuthTokenResponse response) { return(response.GetByKey("scope")); }
public static string GetOpenId(this OAuthTokenResponse response) { return(response.GetByKey("openid")); }
public static string GetUnionId(this OAuthTokenResponse response) { return(response.GetByKey("unionid")); }
/// <summary> /// Refreshes the OAuth2 access token using the refresh token. /// </summary> /// <returns></returns> public static bool Refresh() { HttpWebRequest refreshRequest = WebRequest.CreateHttp(API_OA_BASE + API_EP_OA_REFRESH); refreshRequest.Method = "POST"; refreshRequest.ContentType = API_IMGMEDIA; using (StreamWriter sw = new StreamWriter(refreshRequest.GetRequestStream())) { sw.Write( String.Format( "client_id={0}&client_secret={1}&grant_type={2}&refresh_token={3}", Keys.IMGURv3_CLIENT_ID, Keys.IMGURv3_CLIENT_SECRET, "refresh_token", Settings[SETTING_AUTHREFRESH] ) ); } HttpWebResponse refreshResp = null; try { refreshResp = refreshRequest.GetResponse() as HttpWebResponse; } catch (WebException wex) { refreshResp = wex.Response as HttpWebResponse; } catch (Exception) { return false; } if (refreshResp.StatusCode == HttpStatusCode.OK) { var ser = new DataContractJsonSerializer(typeof(OAuthTokenResponse)); var response = ser.ReadObject(refreshResp.GetResponseStream()) as OAuthTokenResponse; AuthToken = response.AccessToken; AuthExpiry = DateTime.Now.AddSeconds(response.ExpiresIn); Previous = response; return true; } else return false; }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); response.EnsureSuccessStatusCode(); var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); identity.AddOptionalClaim(ClaimTypes.NameIdentifier, FitbitAuthenticationHelper.GetIdentifier(payload), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Name, FitbitAuthenticationHelper.GetLogin(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:fitbit:avatar", FitbitAuthenticationHelper.GetAvatar(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:fitbit:avatar150", FitbitAuthenticationHelper.GetAvatar150(payload), Options.ClaimsIssuer); var context = new OAuthCreatingTicketContext(Context, Options, Backchannel, tokens, payload) { Principal = new ClaimsPrincipal(identity), Properties = properties }; await Options.Events.CreatingTicket(context); if (context.Principal?.Identity == null) { return(null); } return(new AuthenticationTicket(context.Principal, context.Properties, Options.AuthenticationScheme)); }
/// <inheritdoc /> protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { if (identity is null) { throw new ArgumentNullException(nameof(identity)); } if (properties is null) { throw new ArgumentNullException(nameof(properties)); } if (tokens is null) { throw new ArgumentNullException(nameof(tokens)); } var contextId = ProcessIdTokenAndGetContactIdentifier(tokens, properties); string idToken = tokens.Response.RootElement.GetString("id_token"); if (Logger.IsEnabled(LogLevel.Trace)) { Logger.LogTrace("Access Token: {AccessToken}", tokens.AccessToken); Logger.LogTrace("Refresh Token: {RefreshToken}", tokens.RefreshToken); Logger.LogTrace("Token Type: {TokenType}", tokens.TokenType); Logger.LogTrace("Expires In: {ExpiresIn}", tokens.ExpiresIn); Logger.LogTrace("Response: {TokenResponse}", tokens.Response.RootElement); Logger.LogTrace("ID Token: {IdToken}", idToken); } if (string.IsNullOrWhiteSpace(idToken)) { throw new InvalidOperationException("No OneID ID token was returned in the OAuth token response."); } //if (string.IsNullOrEmpty(contextId)) //{ // throw new InvalidOperationException("An error occurred trying to obtain the context identifier from the current user's identity claims."); //} if (Options.ValidateTokens) { var validateIdContext = new OneIdValidateIdTokenContext(Context, Scheme, Options, idToken); //await Options.Events.ValidateIdToken(validateIdContext); } foreach (var claim in ExtractClaimsFromToken(idToken)) { identity.AddClaim(claim); } var principal = new ClaimsPrincipal(identity); var context = new OneIdAuthenticatedContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, tokens.Response.RootElement); List <AuthenticationToken> exactTokens = context.Properties.GetTokens().ToList(); context.HttpContext.Session.SetString("original_username", principal.Identity.Name); // Store the received tokens somewhere, if we should // Store the received tokens somewhere, if we should context.HttpContext.Session.SetString("access_token", context.AccessToken); context.HttpContext.Session.SetString("refresh_token", context.RefreshToken); //if ((Options.TokenSaveOptions & OneIdAuthenticationTokenSave.AccessToken) == OneIdAuthenticationTokenSave.AccessToken) //{ // context.HttpContext.Session.SetString("access_token", context.AccessToken); //} //if ((Options.TokenSaveOptions & OneIdAuthenticationTokenSave.RefreshToken) == OneIdAuthenticationTokenSave.RefreshToken) //{ // context.HttpContext.Session.SetString("refresh_token", context.RefreshToken); //} context.RunClaimActions(); await Events.CreatingTicket(context).ConfigureAwait(false); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); }
protected virtual async Task <OAuthTokenResponse> InternalGetOAuthTokenAsync(HttpClient httpClient, string code, string callbackUri, TokenRequest request, CancellationToken cancellationToken) { string timestamp = DateTime.UtcNow.ToString("yyyy.MM.dd HH:mm:ss +0000"); string state = Options.State.ToString("D"); string scope = String.Join(" ", Options.Scope); string clientSecret = BuildClientSecret(scope, timestamp, Options.ClientId, state); string paramName; string paramValue; string grantType; if (request == TokenRequest.ByRefresh) { paramName = "refresh_token"; paramValue = code; grantType = "refresh_token"; } else if (request == TokenRequest.ByCredential) { paramName = "response_type"; paramValue = "token"; grantType = "client_credentials"; } else { paramName = "code"; paramValue = code; grantType = "authorization_code"; } var requestParams = new Dictionary <string, string> { { "client_id", Options.ClientId }, { paramName, paramValue }, { "grant_type", grantType }, { "state", state }, { "scope", scope }, { "timestamp", timestamp }, { "token_type", "Bearer" }, { "client_secret", clientSecret } }; if (request != TokenRequest.ByCredential) { requestParams.Add("redirect_uri", callbackUri); } // Build request content with params var requestContent = new FormUrlEncodedContent(requestParams); var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); requestMessage.Content = requestContent; var response = await httpClient.SendAsync(requestMessage, cancellationToken); if (response.IsSuccessStatusCode) { var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); return(OAuthTokenResponse.Success(payload)); } string error = "OAuth token endpoint failure: " + await Display(response); return(OAuthTokenResponse.Failed(new Exception(error))); }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { // Note: unlike the other social providers, the userinfo endpoint is user-specific and can't be set globally. // For more information, see https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com var request = new HttpRequestMessage(HttpMethod.Get, tokens.Response.Value <string>("id")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred while retrieving the user from the Salesforce identity service."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); identity.AddOptionalClaim(ClaimTypes.NameIdentifier, SalesforceAuthenticationHelper.GetUserIdentifier(payload), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Name, SalesforceAuthenticationHelper.GetUserName(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:salesforce:email", SalesforceAuthenticationHelper.GetEmail(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:salesforce:thumbnail_photo", SalesforceAuthenticationHelper.GetThumbnailPhoto(payload), Options.ClaimsIssuer) .AddOptionalClaim("urn:salesforce:utc_offset", SalesforceAuthenticationHelper.GetUtcOffset(payload).ToString(), Options.ClaimsIssuer) .AddOptionalClaim("urn:salesforce:rest_url", SalesforceAuthenticationHelper.GetRestUrl(payload), Options.ClaimsIssuer); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, properties, Options.AuthenticationScheme); var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, payload); await Options.Events.CreatingTicket(context); return(context.Ticket); }
/// <summary> /// 根据获取到的 token,来得到登录用户的基本信息,并配对。 /// </summary> protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { var endpoint = Options.UserInformationEndpoint + "?access_token=" + UrlEncoder.Encode(tokens.AccessToken); var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted); response.EnsureSuccessStatusCode(); var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.AuthenticationScheme); var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, payload); var identifier = BaiduHelper.GetId(payload); if (!string.IsNullOrEmpty(identifier)) { identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identifier, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim("urn:baidu:id", identifier, ClaimValueTypes.String, Options.ClaimsIssuer)); } var name = BaiduHelper.GetName(payload); if (!string.IsNullOrEmpty(name)) { identity.AddClaim(new Claim(ClaimTypes.Name, name, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim("urn:baidu:name", name, ClaimValueTypes.String, Options.ClaimsIssuer)); } var portrait = BaiduHelper.GetPortrait(payload); if (!string.IsNullOrEmpty(portrait)) { identity.AddClaim(new Claim("urn:baidu:portrait", portrait, ClaimValueTypes.String, Options.ClaimsIssuer)); } await Options.Events.CreatingTicket(context); return(context.Ticket); }
protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { var endpoint = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "access_token", tokens.AccessToken); if (Options.SendAppSecretProof) { endpoint = QueryHelpers.AddQueryString(endpoint, "appsecret_proof", GenerateAppSecretProof(tokens.AccessToken)); } if (Options.Fields.Count > 0) { endpoint = QueryHelpers.AddQueryString(endpoint, "fields", string.Join(",", Options.Fields)); } var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted); if (!response.IsSuccessStatusCode) { throw new HttpRequestException($"Failed to retrieve Facebook user information ({response.StatusCode}) Please check if the authentication information is correct and the corresponding Facebook Graph API is enabled."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var context = new OAuthCreatingTicketContext(new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, tokens, payload); context.RunClaimActions(); await Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); }
protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { var kimlikJson = JObject.Parse(await GetJson("Kimlik-Dogrula", tokens.AccessToken)); var userJson = JObject.Parse(await GetJson("Ad-Soyad", tokens.AccessToken))["kullaniciBilgileri"]; // Temel-Bilgileri Adres-Bilgileri Iletisim-Bilgileri var claims = new List <Claim>(); claims.Add(new Claim(JwtClaimTypes.Subject, userJson["kimlikNo"].ToString())); claims.Add(new Claim(JwtClaimTypes.Name, userJson["ad"].ToString() + " " + userJson["soyad"].ToString())); claims.Add(new Claim(JwtClaimTypes.GivenName, userJson["ad"].ToString())); claims.Add(new Claim(JwtClaimTypes.FamilyName, userJson["soyad"].ToString())); claims.Add(new Claim(EDevletDefaults.LoginMethodClaimName, kimlikJson["level"].ToString())); claims.Add(new Claim(EDevletDefaults.AccessTokenPropName, tokens.AccessToken)); properties.Items[EDevletDefaults.AccessTokenPropName] = tokens.AccessToken; var scope = properties.Items["scope"].Split(" "); if (scope.Contains("address")) { var adresJson = JObject.Parse(await GetJson("Adres-Bilgileri", tokens.AccessToken))["adresBilgileri"]; claims.Add(new Claim(JwtClaimTypes.Address, adresJson.ToString())); } if (scope.Contains("personal_info")) { var temelJson = JObject.Parse(await GetJson("Temel-Bilgileri", tokens.AccessToken))["kullaniciBilgileri"]; claims.Add(new Claim("marital_status", temelJson["medeniHal"].ToString())); claims.Add(new Claim("mother_name", temelJson["anneAd"].ToString())); claims.Add(new Claim("father_name", temelJson["babaAd"].ToString())); claims.Add(new Claim(JwtClaimTypes.BirthDate, temelJson["dogumTarihi"].ToString())); claims.Add(new Claim(JwtClaimTypes.Gender, temelJson["cinsiyet"].ToString())); } if (scope.Contains("communication_info")) { var iletisimJson = JObject.Parse(await GetJson("Iletisim-Bilgileri", tokens.AccessToken))["kullaniciBilgileri"]; claims.Add(new Claim(JwtClaimTypes.PhoneNumber, iletisimJson["cepTelefon"].ToString())); claims.Add(new Claim(JwtClaimTypes.Email, iletisimJson["eposta"].ToString())); } identity.AddClaims(claims); var principal = new ClaimsPrincipal(identity); return(new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.SignInScheme)); }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue(tokens.TokenType, tokens.AccessToken); var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred when retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred when retrieving the user profile."); } var payload = JArray.Parse(await response.Content.ReadAsStringAsync()); var user = (JObject)payload[0]; identity.AddOptionalClaim(ClaimTypes.NameIdentifier, GitterAuthenticationHelper.GetIdentifier(user), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Name, GitterAuthenticationHelper.GetUsername(user), Options.ClaimsIssuer) .AddOptionalClaim(ClaimTypes.Webpage, GitterAuthenticationHelper.GetLink(user), Options.ClaimsIssuer) .AddOptionalClaim("urn:gitter:displayname", GitterAuthenticationHelper.GetDisplayName(user), Options.ClaimsIssuer) .AddOptionalClaim("urn:gitter:avatarurlsmall", GitterAuthenticationHelper.GetAvatarUrlSmall(user), Options.ClaimsIssuer) .AddOptionalClaim("urn:gitter:avatarurlmedium", GitterAuthenticationHelper.GetAvatarUrlMedium(user), Options.ClaimsIssuer); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, properties, Options.AuthenticationScheme); var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, user); await Options.Events.CreatingTicket(context); return(context.Ticket); }
protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { // Get the Line user var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); var response = await Backchannel.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { throw new HttpRequestException($"An error occurred when retrieving Line user information ({response.StatusCode}). Please check if the authentication information is correct."); } using (var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync())) { var context = new OAuthCreatingTicketContext(new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, tokens, payload.RootElement); context.RunClaimActions(); await Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); } //return await base.CreateTicketAsync(identity, properties, tokens); }
/* * protected new async Task<EHealthOAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri) * { * var content = JsonConvert.SerializeObject(new * { * token = new * { * grant_type = "authorization_code", * code, * client_id = Options.ClientId, * client_secret = Options.ClientSecret, * redirect_uri = redirectUri, * scope = string.Join(" ", Options.Scopes) * } * }, Formatting.None); * var urlEncodedContent = new StringContent(content, Encoding.UTF8, "application/json"); * var response = await Backchannel.SendAsync( * new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint) * { * Headers = { Accept = { new MediaTypeWithQualityHeaderValue("application/json") } }, * Content = urlEncodedContent * }, * Context.RequestAborted); * return response.IsSuccessStatusCode * ? EHealthOAuthTokenResponse.Success(JObject.Parse(await response.Content.ReadAsStringAsync())) * : EHealthOAuthTokenResponse.Failed(new Exception("OAuth token endpoint failure: " + await Display(response))); * } */ /* * protected async Task<AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, * [NotNull] AuthenticationProperties properties, [NotNull] EHealthOAuthTokenResponse tokens) * { * /* * var address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "access_token", tokens.AccessToken); * * if (Options.Scopes.Count != 0) * { * address = QueryHelpers.AddQueryString(address, "scope", string.Join(" ", Options.Scopes)); * } * * var response = await Backchannel.GetAsync(address, Context.RequestAborted); * if (!response.IsSuccessStatusCode) * { * Logger.LogError("An error occurred while retrieving the user profile: the remote server " + * "returned a {Status} response with the following payload: {Headers} {Body}.", * /* Status: #2# response.StatusCode, * /* Headers: #2# response.Headers.ToString(), * /* Body: #2# await response.Content.ReadAsStringAsync()); * * throw new HttpRequestException("An error occurred while retrieving the user profile."); * } * * var container = JObject.Parse(await response.Content.ReadAsStringAsync()); * var payload = container["response"].First as JObject; #1# * * var payload = tokens.Response.Response; * var principal = new ClaimsPrincipal(identity); * var context = new EHealthOAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload); * context.RunClaimActions(payload); * * //!!!await Options.Events.CreatingTicket(context); * return await Task.FromResult(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); * } */ /// <inheritdoc /> protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { /* * var request = new HttpRequestMessage(HttpMethod.Post, Options.UserInformationEndpoint); * request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", $"{tokens.AccessToken},Id {Options.ClientId}"); * request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); * * request.Content = ToJsonContent(new * { * type = "physical", * fields = new[] { "firstName", "middleName", "lastName", "phone", "inn", "clId", "clIdText", "birthDay", "email", "sex", "resident", "dateModification" } * }); * * var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); * if (!response.IsSuccessStatusCode) * { * Logger.LogError("An error occurred while retrieving the user profile: the remote server " + * "returned a {Status} response with the following payload: {Headers} {Body}.", * /* Status: #1# response.StatusCode, * /* Headers: #1# response.Headers.ToString(), * /* Body: #1# await response.Content.ReadAsStringAsync()); * * throw new HttpRequestException("An error occurred while retrieving the user profile."); * } * var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); */ var payload = tokens.Response; var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload); context.RunClaimActions(payload); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); }
protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { //// Get the Automatic user var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); var response = await Backchannel.SendAsync(request, Context.RequestAborted); response.EnsureSuccessStatusCode(); var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload); context.RunClaimActions(payload); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { var address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "access_token", tokens.AccessToken); if (Options.UseSignedRequests) { // Compute the HMAC256 signature. var signature = ComputeSignature(address); // Add the signature to the query string. address = QueryHelpers.AddQueryString(address, "sig", signature); } using var request = new HttpRequestMessage(HttpMethod.Get, address); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); using var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred while retrieving the user profile."); } using var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload.RootElement); context.RunClaimActions(payload.RootElement.GetProperty("data")); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { HttpRequestMessage request = null; HttpResponseMessage response = null; try { request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred while retrieving the user profile."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload); context.RunClaimActions(payload); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); } finally { request?.Dispose(); response?.Dispose(); } }
public async Task <ActionResult> GetRefreshTokenAndTest() { string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value; IEnumerable <OAuthTokenSet> query = from OAuthTokenSet in model.OAuthTokens where OAuthTokenSet.userId == userObjectID select OAuthTokenSet; OAuthTokenSet usertoken = query.First(); model.OAuthTokens.Remove(usertoken); var result = await model.SaveChangesAsync(); string dest = "https://login.microsoftonline.com/b3aa98fb-8679-40e4-a942-6047017aa1a4/oauth2/token"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(dest); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; string postData = String.Format("grant_type=refresh_token&refresh_token={0}&client_id={1}&client_secret={2}&resource={3}", usertoken.refreshToken, Startup.clientId, Startup.appKey, Startup.resourceGroupsId); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] bytes = encoding.GetBytes(postData); req.ContentLength = bytes.Length; Stream nStream = req.GetRequestStream(); nStream.Write(bytes, 0, bytes.Length); nStream.Close(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); System.Runtime.Serialization.Json.DataContractJsonSerializer json = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(OAuthTokenResponse)); OAuthTokenResponse recvtoken = json.ReadObject(resp.GetResponseStream()) as OAuthTokenResponse; OAuthTokenSet token = new OAuthTokenSet(); token.accessToken = recvtoken.access_token; token.tokenType = recvtoken.token_type; token.refreshToken = recvtoken.refresh_token; token.userId = userObjectID; token.accessTokenExpiry = DateTime.Now.AddSeconds(Convert.ToDouble(recvtoken.expires_in)).ToUniversalTime().ToString(DateTimeFormatInfo.CurrentInfo.UniversalSortableDateTimePattern); Random rnd = new Random(); token.Id = rnd.Next(); model.OAuthTokens.Add(token); result = await model.SaveChangesAsync(); string requestUrl = String.Format( CultureInfo.InvariantCulture, Startup.graphUserUrl, HttpUtility.UrlEncode(Startup.tenant)); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.accessToken); HttpResponseMessage response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { ViewBag.RefreshTokenUsedOK = "true"; } string responseString = await response.Content.ReadAsStringAsync(); UserProfile profile = JsonConvert.DeserializeObject <UserProfile>(responseString); // Copy over only the fields recevied from GraphAPI profile.AccessToken = token.accessToken; profile.AccessTokenExpiry = token.accessTokenExpiry; profile.RefreshToken = token.refreshToken; return(View("Index", profile)); }
private async void SignIn() { if (this.requestToken != null) { this.requestToken.VerificationString = AccountManagementViewModel.ParseQuerystringParameter("oauth_verifier", this.URL); try { OAuthTokenResponse response = await OAuth.AccessTokenAsync(SettingsData.Instance.TwitterConsumerKey, SettingsData.Instance.TwitterConsumerSecret, this.requestToken.Token, this.requestToken.VerificationString); if (!string.IsNullOrEmpty(response.TokenSecret)) { this.TwitterAccountID = (Decimal)response.UserId; UserAccountViewModel accountViewModel = new UserAccountViewModel(this.TwitterAccountID); App.AppState.Accounts.Add(accountViewModel); App.AppState.SwitchToAccount(this.TwitterAccountID); Messenger.Default.Send<GenericMessage<TwitViewModel>>(new GenericMessage<TwitViewModel>(accountViewModel.TwitViewModel), (object)ViewModelMessages.AddTwitView); App.AppState.Accounts[this.TwitterAccountID].Settings.TwitterAccountID = (Decimal)response.UserId; App.AppState.Accounts[this.TwitterAccountID].Settings.TwitterAccountName = response.ScreenName; App.AppState.Accounts[this.TwitterAccountID].Settings.UserAuthToken = response.Token; App.AppState.Accounts[this.TwitterAccountID].Settings.UserAuthSecret = response.TokenSecret; App.AppState.Accounts[this.TwitterAccountID].Settings.Save(this.TwitterAccountID); if (!SettingsData.Instance.OOBEScreenDisplayed) SettingsData.Instance.OOBEScreenDisplayed = true; this.requestToken = (OAuthTokenResponse)null; this.CheckifFollowing(); } else { Messenger.Default.Send<DialogMessage>(new DialogMessage(string.Empty, (Action<MessageBoxResult>)(r => { })), (object)DialogType.SignInAuthError); return; } } catch (Exception ex) { Messenger.Default.Send<DialogMessage>(new DialogMessage(ex.Message, (Action<MessageBoxResult>)(r => { })), (object)DialogType.SignInTwitterizerAuthError); return; } } Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)null), (object)ViewModelMessages.CloseCenterModalWindowHost); if (this.IsOOBE) { FollowUsView content = new FollowUsView { DataContext = this }; Messenger.Default.Send<GenericMessage<UserControl>>(new GenericMessage<UserControl>(content), ViewModelMessages.ShowCenterModalWindowHost); } else { App.AppState.Accounts[this.TwitterAccountID].UpdateProfile(true); Messenger.Default.Send<GenericMessage<bool>>(new GenericMessage<bool>(true), (object)this.MultiAccountifyToken((Enum)ViewModelMessages.ReloadTweetViews)); } }
protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); var response = await Backchannel.SendAsync(request, Context.RequestAborted); response.EnsureSuccessStatusCode(); var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.AuthenticationScheme); var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, payload); var identifier = MicrosoftAccountHelper.GetId(payload); if (!string.IsNullOrEmpty(identifier)) { identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identifier, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim("urn:microsoftaccount:id", identifier, ClaimValueTypes.String, Options.ClaimsIssuer)); } var name = MicrosoftAccountHelper.GetDisplayName(payload); if (!string.IsNullOrEmpty(name)) { identity.AddClaim(new Claim(ClaimTypes.Name, name, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim("urn:microsoftaccount:name", name, ClaimValueTypes.String, Options.ClaimsIssuer)); } var givenName = MicrosoftAccountHelper.GetGivenName(payload); if (!string.IsNullOrEmpty(givenName)) { identity.AddClaim(new Claim(ClaimTypes.GivenName, givenName, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim("urn:microsoftaccount:givenname", givenName, ClaimValueTypes.String, Options.ClaimsIssuer)); } var surname = MicrosoftAccountHelper.GetSurname(payload); if (!string.IsNullOrEmpty(surname)) { identity.AddClaim(new Claim(ClaimTypes.Surname, surname, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim("urn:microsoftaccount:surname", surname, ClaimValueTypes.String, Options.ClaimsIssuer)); } var email = MicrosoftAccountHelper.GetEmail(payload); if (!string.IsNullOrEmpty(email)) { identity.AddClaim(new Claim(ClaimTypes.Email, email, ClaimValueTypes.String, Options.ClaimsIssuer)); } await Options.Events.CreatingTicket(context); return(context.Ticket); }
/// <summary> /// Converts a pin into tokens. /// </summary> /// <param name="pin"></param> public static HttpStatusCode Tokenise(string pin, out OAuthTokenResponse response) { HttpWebRequest tokenRequest = WebRequest.CreateHttp(API_OA_BASE + API_EP_OA_REFRESH); tokenRequest.ContentType = API_IMGMEDIA; tokenRequest.Method = "POST"; using (StreamWriter sw = new StreamWriter(tokenRequest.GetRequestStream())) { sw.Write( String.Format( "client_id={0}&client_secret={1}&grant_type={2}&pin={3}", Keys.IMGURv3_CLIENT_ID, Keys.IMGURv3_CLIENT_SECRET, API_OA_GRANTTYPE, pin ) ); } HttpStatusCode responseCode = default(int); HttpWebResponse tokenResponse = null; try { tokenResponse = tokenRequest.GetResponse() as HttpWebResponse; responseCode = tokenResponse.StatusCode; } catch (WebException wex) { tokenResponse = wex.Response as HttpWebResponse; responseCode = tokenResponse.StatusCode; } if (responseCode == HttpStatusCode.OK) { var ser = new DataContractJsonSerializer(typeof(OAuthTokenResponse)); response = ser.ReadObject(tokenResponse.GetResponseStream()) as OAuthTokenResponse; } else { response = null; } return responseCode; }
protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { // Note: unlike the other social providers, the userinfo endpoint is user-specific and can't be set globally. // For more information, see https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com HttpRequestMessage request = null; HttpResponseMessage response = null; try { request = new HttpRequestMessage(HttpMethod.Get, tokens.Response.Value <string>("id")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); if (!response.IsSuccessStatusCode) { Logger.LogError("An error occurred while retrieving the user profile: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ response.StatusCode, /* Headers: */ response.Headers.ToString(), /* Body: */ await response.Content.ReadAsStringAsync()); throw new HttpRequestException("An error occurred while retrieving the user from the Salesforce identity service."); } var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload); context.RunClaimActions(payload); await Options.Events.CreatingTicket(context); return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name)); } finally { request?.Dispose(); response?.Dispose(); } }
/// <summary> /// Gets the access token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="requestToken">The request token.</param> /// <param name="verifier">The pin number or verifier string.</param> /// <returns> /// An <see cref="OAuthTokenResponse"/> class containing access token information. /// </returns> public static async Task<OAuthTokenResponse> AccessTokenAsync(string consumerKey, string consumerSecret, string requestToken, string verifier) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(requestToken)) { throw new ArgumentNullException("requestToken"); } WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HttpMethod.Get, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); if (!string.IsNullOrEmpty(verifier)) { builder.Parameters.Add("oauth_verifier", verifier); } builder.Parameters.Add("oauth_token", requestToken); string responseBody; try { HttpResponseMessage webResponse = await builder.ExecuteRequestAsync(); responseBody = await webResponse.Content.ReadAsStringAsync(); } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } OAuthTokenResponse response = new OAuthTokenResponse(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; return response; }
public ActionResult CheckAuthorization() { var oauth_consumer_key = "dXdz4bXFzCZwhHSZRlqXIQ"; var oauth_consumer_secret = "VQ4ec2t13qGfuQpthuRDMRSQhSrd3LZWYd152JHk"; if (Request["oauth_token"] == null) { OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken( oauth_consumer_key, oauth_consumer_secret, Request.Url.AbsoluteUri); Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}", reqToken.Token)); } else { string requestToken = Request["oauth_token"].ToString(); string pin = Request["oauth_verifier"].ToString(); var tokens = OAuthUtility.GetAccessToken( oauth_consumer_key, oauth_consumer_secret, requestToken, pin); OAuthTokens accesstoken = new OAuthTokens() { AccessToken = tokens.Token, AccessTokenSecret = tokens.TokenSecret, ConsumerKey = oauth_consumer_key, ConsumerSecret = oauth_consumer_secret }; try { TwitterResponse <TwitterStatus> response = TwitterStatus.Update( accesstoken, "@oculy Twit test for OATH. @akunsys "); if (response.Result == RequestResult.Success) { Response.Write("Did it yaar"); } else { Response.Write("Try some other time"); } TwitterResponse <TwitterUser> returnTwit = Twitterizer.TwitterUser.Show(accesstoken, tokens.ScreenName); string ProfilePicture = returnTwit.ResponseObject.ProfileImageLocation; string newProfilePicRoute = string.Empty; Guid UserDataGuid = Guid.NewGuid(); newProfilePicRoute = ImageHelper.MergeImages(Server, ProfilePicture, SiteSettings.PinImageOverlay, UserDataGuid.ToString(), Constants.USERTYPE_TWITTER); if (!string.IsNullOrEmpty(newProfilePicRoute)) { string localPatchImage = Server.MapPath(newProfilePicRoute); newProfilePicRoute = ImageHelper.MergeImages(Server, ProfilePicture, SiteSettings.PinImageOverlay, UserDataGuid.ToString(), Constants.USERTYPE_TWITTER); TwitterResponse <TwitterUser> resp = TwitterAccount.UpdateProfileImage(accesstoken, localPatchImage); } } catch (Exception ex) { } } return(View()); }