Here are the examples of the csharp api System.Uri.EscapeDataString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2209 Examples
19
Source : ChatPeer.cs
with MIT License
from ArcturusZhang
with MIT License
from ArcturusZhang
public virtual void AddAuthParameter(string key, string value)
{
string ampersand = string.IsNullOrEmpty(this.AuthGetParameters) ? string.Empty : "&";
this.AuthGetParameters = string.Format("{0}{1}{2}={3}", this.AuthGetParameters, ampersand, System.Uri.EscapeDataString(key), System.Uri.EscapeDataString(value));
}
19
Source : CoreRequest.cs
with Apache License 2.0
from artemshuba
with Apache License 2.0
from artemshuba
private static Uri GetFullUri(Uri baseUri, Dictionary<string, string> parameters)
{
if (parameters != null && parameters.Count > 0)
{
var paramStr = string.Join("&", parameters.Select(kp => $"{Uri.EscapeDataString(kp.Key)}={Uri.EscapeDataString(kp.Value)}"));
return new Uri(string.Concat(baseUri, "?", paramStr));
}
return baseUri;
}
19
Source : GrooveClient.cs
with Apache License 2.0
from artemshuba
with Apache License 2.0
from artemshuba
private async Task<ContentResponse> SearchApiAsync(
MediaNamespace mediaNamespace,
string query = null,
ContentSource? source = null,
SearchFilter filter =
SearchFilter.Default,
string language = null,
string country = null,
int? maxItems = null,
string continuationToken = null)
{
Dictionary<string, string> requestParameters = FormatRequestParameters(continuationToken, language, country, source);
if (!string.IsNullOrEmpty(query))
requestParameters.Add("q", Uri.EscapeDataString(query));
if (filter != SearchFilter.Default)
requestParameters.Add("filters", filter.ToString().Replace(", ", "+"));
if (maxItems.HasValue)
requestParameters.Add("maxItems", maxItems.ToString());
if (_userTokenManager?.UserIsSignedIn == true)
{
return await ApiCallWithUserAuthorizationHeaderRefreshAsync(
headers => GetAsync<ContentResponse>(
Hostname,
$"/1/content/{mediaNamespace}/search",
new CancellationToken(false),
requestParameters,
headers));
}
else
{
Dictionary<string, string> requestHeaders = await FormatRequestHeadersAsync(null);
return await GetAsync<ContentResponse>(
Hostname,
$"/1/content/{mediaNamespace}/search",
new CancellationToken(false),
requestParameters,
requestHeaders);
}
}
19
Source : LastFmTrackRequest.cs
with Apache License 2.0
from artemshuba
with Apache License 2.0
from artemshuba
public async Task UpdateNowPlaying(string artist, string track, string mbid = null, int duration = 0,
string album = null, int trackNumber = -1, string albumArtist = null)
{
const string method = "track.updateNowPlaying";
var parameters = new Dictionary<string, string>();
parameters.Add("artist", artist);
parameters.Add("track", track);
if (album != null)
parameters.Add("album", album);
if (trackNumber > -1)
parameters.Add("trackNumber", trackNumber.ToString());
if (mbid != null)
parameters.Add("mbid", mbid);
if (duration > 0)
parameters.Add("duration", duration.ToString());
if (albumArtist != null)
parameters.Add("albumArtist", albumArtist);
parameters.Add("api_key", _lastFm.ApiKey);
parameters.Add("sk", _lastFm.SessionKey);
parameters.Add("api_sig", LastFmUtils.BuildSig(_lastFm.ApiSecret, method, parameters));
parameters["track"] = Uri.EscapeDataString(track); //fix ampersand scrobbling
parameters["artist"] = Uri.EscapeDataString(artist); //fix ampersand scrobbling
var response = await new CoreRequest(new Uri(LastFmConst.UrlBaseSecure), null, "POST", parameters).Execute();
LastFmErrorProcessor.ProcessError(response);
}
19
Source : LastFmTrackRequest.cs
with Apache License 2.0
from artemshuba
with Apache License 2.0
from artemshuba
public async Task Scrobble(string artist, string track, string timeStamp, string mbid = null, int duration = 0,
string album = null, int trackNumber = -1, string albumArtist = null)
{
const string method = "track.scrobble";
var parameters = new Dictionary<string, string>();
parameters.Add("artist", artist);
parameters.Add("track", track);
parameters.Add("timestamp", timeStamp);
if (album != null)
parameters.Add("album", album);
if (trackNumber > -1)
parameters.Add("trackNumber", trackNumber.ToString());
if (mbid != null)
parameters.Add("mbid", mbid);
if (albumArtist != null)
parameters.Add("albumArtist", albumArtist);
if (duration > 0)
parameters.Add("duration", duration.ToString());
parameters.Add("api_key", _lastFm.ApiKey);
parameters.Add("sk", _lastFm.SessionKey);
parameters.Add("api_sig", LastFmUtils.BuildSig(_lastFm.ApiSecret, method, parameters));
parameters["track"] = Uri.EscapeDataString(track); //fix ampersand scrobbling
parameters["artist"] = Uri.EscapeDataString(artist); //fix ampersand scrobbling
var response = await new CoreRequest(new Uri(LastFmConst.UrlBaseSecure), null, "POST", parameters).Execute();
LastFmErrorProcessor.ProcessError(response);
}
19
Source : CoreRequest.cs
with Apache License 2.0
from artemshuba
with Apache License 2.0
from artemshuba
private Uri GetFullUri(Dictionary<string, string> parameters)
{
if (parameters != null && parameters.Count > 0)
{
var paramStr = string.Join("&",
parameters.Select(
kp => string.Format("{0}={1}", Uri.EscapeDataString(kp.Key), Uri.EscapeDataString(kp.Value))));
return new Uri(string.Concat(_uri, "&", paramStr));
}
return _uri;
}
19
Source : HttpRequestBuilder.cs
with Apache License 2.0
from Asesjix
with Apache License 2.0
from Asesjix
public HttpRequestBuilder AddQuery(string key, string value)
{
ArgumentCheck.ThrowIfNullOrEmpty(key, nameof(key));
ArgumentCheck.ThrowIfNull(value, nameof(value));
var queryBuilder = new StringBuilder(_requestUriBuilder.Query);
if (queryBuilder.Length == 0)
{
queryBuilder.Append('?');
}
else
{
queryBuilder.Append('&');
}
queryBuilder.AppendFormat("{0}={1}", key, Uri.EscapeDataString(value));
_requestUriBuilder.Query = queryBuilder.ToString();
return this;
}
19
Source : PolrUrlShortener.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<string> ShortenAsync(string url)
{
var request = WebRequest.CreateHttp($"{_domain}/api/v2/action/shorten?key={_apiKey}&url={Uri.EscapeDataString(url)}&is_secret=false");
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}
19
Source : SpotifyClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<string> SearchTrackId(string query)
{
var request = WebRequest.CreateHttp($"https://api.spotify.com/v1/search?q={Uri.EscapeDataString(query)}&type=track&limit=1");
request.Headers.Add("Authorization", $"Bearer {await GetToken()}");
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
dynamic root = JObject.Parse(text);
dynamic item = (root.tracks?.items as JArray)?.FirstOrDefault();
return (string)item?.id;
}
}
19
Source : TranslatorModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
[Command("translate", "Translates a piece of text.")]
[Alias("tr"), Alias("번역")]
[Parameter("From", LanguageRegex, ParameterType.String, "the language of the message")]
[Parameter("To", LanguageRegex, ParameterType.String, "the language to translate into")]
[Parameter("Message", ParameterType.String, ParameterFlags.Remainder, "the word or sentence you want to translate")]
[Comment("Korean = `ko` \nreplacedan = `ja` \nEnglish = `en` \nChinese(Simplified) = `zh-CH` \nChinese(Traditional) = `zh-TW` \nSpanish = `es` \nFrench = `fr` \nGerman = `de` \nRussian = `ru` \nPortuguese = `pt` \nItalian = `it` \nVietnamese = `vi` \nThai = `th` \nIndonesian = `id`")]
[Example("ko en 사랑해")]
public async Task Translate(ICommand command, ILogger logger)
{
await command.Message.Channel.TriggerTypingAsync();
var stringMessage = command["Message"].ToString();
var firstLang = command["From"].ToString();
var lastLang = command["To"].ToString();
var byteDataParams = Encoding.UTF8.GetBytes($"source={Uri.EscapeDataString(firstLang)}&target={Uri.EscapeDataString(lastLang)}&text={Uri.EscapeDataString(stringMessage)}");
try
{
var request = WebRequest.CreateHttp("https://openapi.naver.com/v1/papago/n2mt");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("X-Naver-Client-Id", _integrationOptions.Value.PapagoClientId);
request.Headers.Add("X-Naver-Client-Secret", _integrationOptions.Value.PapagoClientSecret);
request.ContentLength = byteDataParams.Length;
using (var st = request.GetRequestStream())
{
st.Write(byteDataParams, 0, byteDataParams.Length);
}
using (var responseClient = await request.GetResponseAsync())
using (var reader = new StreamReader(responseClient.GetResponseStream()))
{
var parserObject = JObject.Parse(await reader.ReadToEndAsync());
var trMessage = parserObject["message"]["result"]["translatedText"].ToString();
var translateSentence = trMessage.Truncate(EmbedBuilder.MaxDescriptionLength);
EmbedBuilder embedBuilder = new EmbedBuilder()
.Withreplacedle($"Translation from **{firstLang.ToUpper()}** to **{lastLang.ToUpper()}**")
.WithDescription(translateSentence)
.WithColor(new Color(0, 206, 56))
.WithFooter("Powered by Papago");
await command.Reply(embedBuilder.Build());
}
}
catch (WebException ex) when (ex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.BadRequest)
{
throw new IncorrectParametersCommandException("Unsupported language combination.");
}
catch (WebException ex)
{
logger.LogError(ex, "Failed to reach Papago");
await command.Reply($"Couldn't reach Papago (error {(ex.Response as HttpWebResponse)?.StatusCode.ToString() ?? ex.Status.ToString()}). Please try again in a few seconds.");
}
}
19
Source : SpotifyClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<string> SearchTrackUrl(string query)
{
var request = WebRequest.CreateHttp($"https://api.spotify.com/v1/search?q={Uri.EscapeDataString(query)}&type=track&limit=1");
request.Headers.Add("Authorization", $"Bearer {await GetToken()}");
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
dynamic root = JObject.Parse(text);
dynamic item = (root.tracks?.items as JArray)?.FirstOrDefault();
return (string)item?.external_urls?.spotify;
}
}
19
Source : SpotifyController.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
[Authorize]
public IActionResult ConnectBegin()
{
var userIdClaim = User.FindFirst(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
var userNameClaim = User.FindFirst(c => c.Type == ClaimTypes.Name)?.Value;
var id = ulong.Parse(userIdClaim);
_logger.LogInformation($"Initiating Spotify OAuth2 flow for user {id}");
var clientId = Environment.GetEnvironmentVariable("SpotifyClientId");
var scopes = new[]
{
"user-read-currently-playing",
"user-top-read",
"user-read-recently-played"
};
var cookieOptions = new CookieOptions()
{
Path = "/",
Expires = DateTimeOffset.Now + StateCookieLifetime,
MaxAge = StateCookieLifetime,
HttpOnly = true,
Secure = true
};
var redirectUri = GetSpotifyRedirectUri();
var state = GenerateState(id);
Response.Cookies.Append("SpotifyOAuth2State", state, cookieOptions);
return Redirect($"https://accounts.spotify.com/authorize?client_id={clientId}&response_type=code&redirect_uri={Uri.EscapeDataString(redirectUri)}&state={state}&scope={string.Join(" ", scopes)}&show_dialog=true");
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<LastFmArtist> GetArtistInfo(string name)
{
var request = WebRequest.CreateHttp($"{ApiBase}/?method=artist.getInfo&api_key={Key}&artist={Uri.EscapeDataString(name)}&format=json&username={User}");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var artist = JObject.Parse(text)?["artist"];
if (artist == null)
return null;
return new LastFmArtist((string)artist["name"], imageUri: GetLargestImage(artist["image"]));
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<LastFmTrack> GetTrackInfo(string artistName, string name)
{
var request = WebRequest.CreateHttp($"{ApiBase}/?method=track.getInfo&api_key={Key}&artist={Uri.EscapeDataString(artistName)}&track={Uri.EscapeDataString(name)}&format=json&username={User}");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var track = JObject.Parse(text)?["track"];
if (track == null)
return null;
var artist = new LastFmArtist((string)track["artist"]["name"]);
var album = new LastFmAlbum((string)track["album"]?["replacedle"], artist, imageUri: GetLargestImage(track["album"]?["image"]));
return new LastFmTrack((string)track["name"], album, (int?)track["userplaycount"]);
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<LastFmArtistDetail> GetArtistDetail(string artist, LastFmDataPeriod period)
{
try
{
var infoTask = GetArtistInfo(artist);
var request = WebRequest.CreateHttp($"https://www.last.fm/user/{User}/library/music/{Uri.EscapeDataString(artist)}?date_preset={StatsPeriodWebMapping[period]}");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var content = await reader.ReadToEndAsync();
var doc = new HtmlDoreplacedent();
doc.LoadHtml(content);
// Get artist info
var info = await infoTask;
if (info == null)
return null;
// Get avatar (we can't get it via the API because it never actually has the artist's image...)
var image = doc.DoreplacedentNode.Descendants("span")
.FirstOrDefault(x => x.HasClreplaced("library-header-image"))?
.Descendants("img")
.FirstOrDefault()?
.GetAttributeValue("src", null)?
.Replace("avatar70s", "avatar170s");
// Get playcount and count of listened albums and tracks (in that order)
var metadata = doc.DoreplacedentNode
.Descendants("p")
.Where(x => x.HasClreplaced("metadata-display") && x.ParentNode.HasClreplaced("metadata-item"))
.Select(x => int.Parse(x.InnerText, System.Globalization.NumberStyles.Any, new System.Globalization.CultureInfo("en-US")))
.ToList();
var playcount = metadata.ElementAtOrDefault(0);
var albumsListened = metadata.ElementAtOrDefault(1);
var tracksListened = metadata.ElementAtOrDefault(2);
// Get top albums and tracks
IEnumerable<(string name, string url, int playcount)> GetTopLisreplacedems(HtmlNode topList)
{
foreach (var item in topList.Descendants("tr").Where(x => x.HasClreplaced("chartlist-row") || x.HasClreplaced("chartlist-row\n")))
{
var itemNameLink = item.Descendants("td").First(x => x.HasClreplaced("chartlist-name")).Descendants("a").First();
var itemUrl = "https://www.last.fm" + itemNameLink.GetAttributeValue("href", null);
var scrobbleText = item.Descendants("span").First(x => x.HasClreplaced("chartlist-count-bar-value")).InnerText;
var scrobbleCount = int.Parse(Regex.Match(scrobbleText, @"[\d,.\s]+").Value, System.Globalization.NumberStyles.Any, new System.Globalization.CultureInfo("en-US"));
yield return (WebUtility.HtmlDecode(itemNameLink.InnerText), itemUrl, scrobbleCount);
}
}
var topLists = doc.DoreplacedentNode.Descendants("table").Where(x => x.HasClreplaced("chartlist") || x.HasClreplaced("chartlist\n")).ToList();
var topAlbums = Enumerable.Empty<LastFmAlbum>();
if (topLists.Any())
topAlbums = GetTopLisreplacedems(topLists.First()).Select(x => new LastFmAlbum(x.name, info, x.playcount));
var topTracks = Enumerable.Empty<LastFmTrack>();
if (topLists.Skip(1).Any())
topTracks = GetTopLisreplacedems(topLists.Skip(1).First()).Select(x => new LastFmTrack(x.name, new LastFmAlbum(null, info), x.playcount));
var imageUri = string.IsNullOrEmpty(image) ? null : new Uri(image);
return new LastFmArtistDetail(info, imageUri, topAlbums, topTracks, albumsListened, tracksListened, playcount);
}
}
catch (WebException e) when ((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
}
19
Source : ChunkingCookieManager.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
bool pathHasValue = !string.IsNullOrEmpty(options.Path);
bool expiresHasValue = options.Expires.HasValue;
bool sameSiteHasValue = options.SameSite.HasValue;
string escapedKey = Uri.EscapeDataString(key);
string prefix = escapedKey + "=";
string suffix = string.Concat(
!domainHasValue ? null : "; domain=",
!domainHasValue ? null : options.Domain,
!pathHasValue ? null : "; path=",
!pathHasValue ? null : options.Path,
!expiresHasValue ? null : "; expires=",
!expiresHasValue ? null : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss \\G\\M\\T", CultureInfo.InvariantCulture),
!options.Secure ? null : "; secure",
!options.HttpOnly ? null : "; HttpOnly",
!sameSiteHasValue ? null : "; SameSite=",
!sameSiteHasValue ? null : GetStringRepresentationOfSameSite(options.SameSite.Value));
value = value ?? string.Empty;
bool quoted = false;
if (IsQuoted(value))
{
quoted = true;
value = RemoveQuotes(value);
}
string escapedValue = Uri.EscapeDataString(value);
// Normal cookie
IHeaderDictionary responseHeaders = context.Response.Headers;
if (!ChunkSize.HasValue || ChunkSize.Value > prefix.Length + escapedValue.Length + suffix.Length + (quoted ? 2 : 0))
{
string setCookieValue = string.Concat(
prefix,
quoted ? Quote(escapedValue) : escapedValue,
suffix);
responseHeaders.AppendValues(Constants.Headers.SetCookie, setCookieValue);
}
else if (ChunkSize.Value < prefix.Length + suffix.Length + (quoted ? 2 : 0) + 10)
{
// 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX".
// No room for data, we can't chunk the options and name
throw new InvalidOperationException(Resources.Exception_CookieLimitTooSmall);
}
else
{
// Break the cookie down into multiple cookies.
// Key = CookieName, value = "Segment1Segment2Segment2"
// Set-Cookie: CookieName=chunks:3; path=/
// Set-Cookie: CookieNameC1="Segment1"; path=/
// Set-Cookie: CookieNameC2="Segment2"; path=/
// Set-Cookie: CookieNameC3="Segment3"; path=/
int dataSizePerCookie = ChunkSize.Value - prefix.Length - suffix.Length - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid.
int cookieChunkCount = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie);
responseHeaders.AppendValues(Constants.Headers.SetCookie, prefix + "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture) + suffix);
string[] chunks = new string[cookieChunkCount];
int offset = 0;
for (int chunkId = 1; chunkId <= cookieChunkCount; chunkId++)
{
int remainingLength = escapedValue.Length - offset;
int length = Math.Min(dataSizePerCookie, remainingLength);
string segment = escapedValue.Substring(offset, length);
offset += length;
chunks[chunkId - 1] = string.Concat(
escapedKey,
"C",
chunkId.ToString(CultureInfo.InvariantCulture),
"=",
quoted ? "\"" : string.Empty,
segment,
quoted ? "\"" : string.Empty,
suffix);
}
responseHeaders.AppendValues(Constants.Headers.SetCookie, chunks);
}
}
19
Source : ChunkingCookieManager.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
string escapedKey = Uri.EscapeDataString(key);
List<string> keys = new List<string>();
keys.Add(escapedKey + "=");
string requestCookie = context.Request.Cookies[key];
int chunks = ParseChunksCount(requestCookie);
if (chunks > 0)
{
for (int i = 1; i <= chunks + 1; i++)
{
string subkey = escapedKey + "C" + i.ToString(CultureInfo.InvariantCulture);
keys.Add(subkey + "=");
}
}
bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
bool pathHasValue = !string.IsNullOrEmpty(options.Path);
Func<string, bool> rejectPredicate;
Func<string, bool> predicate = value => keys.Any(k => value.StartsWith(k, StringComparison.OrdinalIgnoreCase));
if (domainHasValue)
{
rejectPredicate = value => predicate(value) && value.IndexOf("domain=" + options.Domain, StringComparison.OrdinalIgnoreCase) != -1;
}
else if (pathHasValue)
{
rejectPredicate = value => predicate(value) && value.IndexOf("path=" + options.Path, StringComparison.OrdinalIgnoreCase) != -1;
}
else
{
rejectPredicate = value => predicate(value);
}
IHeaderDictionary responseHeaders = context.Response.Headers;
IList<string> existingValues = responseHeaders.GetValues(Constants.Headers.SetCookie);
if (existingValues != null)
{
responseHeaders.SetValues(Constants.Headers.SetCookie, existingValues.Where(value => !rejectPredicate(value)).ToArray());
}
AppendResponseCookie(
context,
key,
string.Empty,
new CookieOptions
{
Path = options.Path,
Domain = options.Domain,
HttpOnly = options.HttpOnly,
SameSite = options.SameSite,
Secure = options.Secure,
Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
for (int i = 1; i <= chunks; i++)
{
AppendResponseCookie(
context,
key + "C" + i.ToString(CultureInfo.InvariantCulture),
string.Empty,
new CookieOptions
{
Path = options.Path,
Domain = options.Domain,
HttpOnly = options.HttpOnly,
SameSite = options.SameSite,
Secure = options.Secure,
Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
}
}
19
Source : WebUtils.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Disreplacedembled")]
public static string AddQueryString(string uri, string name, string value)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
bool hasQuery = uri.IndexOf('?') != -1;
return uri + (hasQuery ? "&" : "?") + Uri.EscapeDataString(name) + "=" + Uri.EscapeDataString(value);
}
19
Source : WebUtils.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Disreplacedembled")]
public static string AddQueryString(string uri, IDictionary<string, string> queryString)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
if (queryString == null)
{
throw new ArgumentNullException("queryString");
}
var sb = new StringBuilder();
sb.Append(uri);
bool hasQuery = uri.IndexOf('?') != -1;
foreach (var parameter in queryString)
{
sb.Append(hasQuery ? '&' : '?');
sb.Append(Uri.EscapeDataString(parameter.Key));
sb.Append('=');
sb.Append(Uri.EscapeDataString(parameter.Value));
hasQuery = true;
}
return sb.ToString();
}
19
Source : PathString.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Purpose of the method is to return a string")]
public string ToUriComponent()
{
if (!HasValue)
{
return string.Empty;
}
StringBuilder buffer = null;
var start = 0;
var count = 0;
var requiresEscaping = false;
var i = 0;
while (i < _value.Length)
{
var isPercentEncodedChar = PathStringHelper.IsPercentEncodedChar(_value, i);
if (PathStringHelper.IsValidPathChar(_value[i]) || isPercentEncodedChar)
{
if (requiresEscaping)
{
// the current segment requires escape
if (buffer == null)
{
buffer = new StringBuilder(_value.Length * 3);
}
buffer.Append(Uri.EscapeDataString(_value.Substring(start, count)));
requiresEscaping = false;
start = i;
count = 0;
}
if (isPercentEncodedChar)
{
count += 3;
i += 3;
}
else
{
count++;
i++;
}
}
else
{
if (!requiresEscaping)
{
// the current segument doesn't require escape
if (buffer == null)
{
buffer = new StringBuilder(_value.Length * 3);
}
buffer.Append(_value, start, count);
requiresEscaping = true;
start = i;
count = 0;
}
count++;
i++;
}
}
if (count == _value.Length && !requiresEscaping)
{
return _value;
}
else
{
if (count > 0)
{
if (buffer == null)
{
buffer = new StringBuilder(_value.Length * 3);
}
if (requiresEscaping)
{
buffer.Append(Uri.EscapeDataString(_value.Substring(start, count)));
}
else
{
buffer.Append(_value, start, count);
}
}
return buffer.ToString();
}
}
19
Source : SystemWebChunkingCookieManager.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
if (webContext == null)
{
Fallback.AppendResponseCookie(context, key, value, options);
return;
}
bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
bool pathHasValue = !string.IsNullOrEmpty(options.Path);
bool expiresHasValue = options.Expires.HasValue;
bool sameSiteHasValue = options.SameSite.HasValue && SystemWebCookieManager.IsSameSiteAvailable;
string escapedKey = Uri.EscapeDataString(key);
string prefix = escapedKey + "=";
string suffix = string.Concat(
!domainHasValue ? null : "; domain=",
!domainHasValue ? null : options.Domain,
!pathHasValue ? null : "; path=",
!pathHasValue ? null : options.Path,
!expiresHasValue ? null : "; expires=",
!expiresHasValue ? null : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss \\G\\M\\T", CultureInfo.InvariantCulture),
!options.Secure ? null : "; secure",
!options.HttpOnly ? null : "; HttpOnly",
!sameSiteHasValue ? null : "; SameSite=",
!sameSiteHasValue ? null : GetStringRepresentationOfSameSite(options.SameSite.Value)
);
value = value ?? string.Empty;
bool quoted = false;
if (IsQuoted(value))
{
quoted = true;
value = RemoveQuotes(value);
}
string escapedValue = Uri.EscapeDataString(value);
// Normal cookie
if (!ChunkSize.HasValue || ChunkSize.Value > prefix.Length + escapedValue.Length + suffix.Length + (quoted ? 2 : 0))
{
var cookie = new HttpCookie(escapedKey, escapedValue);
SetOptions(cookie, options, domainHasValue, pathHasValue, expiresHasValue);
webContext.Response.AppendCookie(cookie);
}
else if (ChunkSize.Value < prefix.Length + suffix.Length + (quoted ? 2 : 0) + 10)
{
// 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX".
// No room for data, we can't chunk the options and name
throw new InvalidOperationException(Resources.Exception_CookieLimitTooSmall);
}
else
{
// Break the cookie down into multiple cookies.
// Key = CookieName, value = "Segment1Segment2Segment2"
// Set-Cookie: CookieName=chunks:3; path=/
// Set-Cookie: CookieNameC1="Segment1"; path=/
// Set-Cookie: CookieNameC2="Segment2"; path=/
// Set-Cookie: CookieNameC3="Segment3"; path=/
int dataSizePerCookie = ChunkSize.Value - prefix.Length - suffix.Length - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid.
int cookieChunkCount = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie);
var cookie = new HttpCookie(escapedKey, "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture));
SetOptions(cookie, options, domainHasValue, pathHasValue, expiresHasValue);
webContext.Response.AppendCookie(cookie);
int offset = 0;
for (int chunkId = 1; chunkId <= cookieChunkCount; chunkId++)
{
int remainingLength = escapedValue.Length - offset;
int length = Math.Min(dataSizePerCookie, remainingLength);
string segment = escapedValue.Substring(offset, length);
offset += length;
cookie = new HttpCookie(escapedKey + "C" + chunkId.ToString(CultureInfo.InvariantCulture), quoted ? Quote(segment) : segment);
SetOptions(cookie, options, domainHasValue, pathHasValue, expiresHasValue);
webContext.Response.AppendCookie(cookie);
}
}
}
19
Source : SystemWebCookieManager.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public string GetRequestCookie(IOwinContext context, string key)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
if (webContext == null)
{
return Fallback.GetRequestCookie(context, key);
}
var escapedKey = Uri.EscapeDataString(key);
var cookie = webContext.Request.Cookies[escapedKey];
if (cookie == null)
{
return null;
}
return Uri.UnescapeDataString(cookie.Value);
}
19
Source : FacebookAuthenticationHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
protected override Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
{
return Task.FromResult<object>(null);
}
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge != null)
{
string baseUri =
Request.Scheme +
Uri.SchemeDelimiter +
Request.Host +
Request.PathBase;
string currentUri =
baseUri +
Request.Path +
Request.QueryString;
string redirectUri =
baseUri +
Options.CallbackPath;
AuthenticationProperties properties = challenge.Properties;
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = currentUri;
}
// OAuth2 10.12 CSRF
GenerateCorrelationId(Options.CookieManager, properties);
// comma separated
string scope = string.Join(",", Options.Scope);
string state = Options.StateDataFormat.Protect(properties);
string authorizationEndpoint =
Options.AuthorizationEndpoint +
"?response_type=code" +
"&client_id=" + Uri.EscapeDataString(Options.AppId) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&scope=" + Uri.EscapeDataString(scope) +
"&state=" + Uri.EscapeDataString(state);
var redirectContext = new FacebookApplyRedirectContext(
Context, Options,
properties, authorizationEndpoint);
Options.Provider.ApplyRedirect(redirectContext);
}
return Task.FromResult<object>(null);
}
19
Source : OpenidConnectAuthenticationHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
protected override async Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode == 401)
{
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge == null)
{
return;
}
// order for redirect_uri
// 1. challenge.Properties.RedirectUri
// 2. CurrentUri
AuthenticationProperties properties = challenge.Properties;
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = CurrentUri;
}
// this value will be preplaceded to the AuthorizationCodeReceivedNotification
if (!string.IsNullOrWhiteSpace(Options.RedirectUri))
{
properties.Dictionary.Add(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey, Options.RedirectUri);
}
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
}
OpenIdConnectMessage openIdConnectMessage = new OpenIdConnectMessage
{
ClientId = Options.ClientId,
IssuerAddress = _configuration.AuthorizationEndpoint ?? string.Empty,
RedirectUri = Options.RedirectUri,
RequestType = OpenIdConnectRequestType.Authentication,
Resource = Options.Resource,
ResponseType = Options.ResponseType,
Scope = Options.Scope
};
// https://tools.ietf.org/html/rfc7636
if (Options.UsePkce && Options.ResponseType == OpenIdConnectResponseType.Code)
{
using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
using (HashAlgorithm hash = SHA256.Create())
{
byte[] bytes = new byte[32];
randomNumberGenerator.GetBytes(bytes);
string codeVerifier = TextEncodings.Base64Url.Encode(bytes);
// Store this for use during the code redemption.
properties.Dictionary.Add(OAuthConstants.CodeVerifierKey, codeVerifier);
byte[] challengeBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
string codeChallenge = TextEncodings.Base64Url.Encode(challengeBytes);
openIdConnectMessage.Parameters.Add(OAuthConstants.CodeChallengeKey, codeChallenge);
openIdConnectMessage.Parameters.Add(OAuthConstants.CodeChallengeMethodKey, OAuthConstants.CodeChallengeMethodS256);
}
}
openIdConnectMessage.State = OpenIdConnectAuthenticationDefaults.AuthenticationPropertiesKey + "=" + Uri.EscapeDataString(Options.StateDataFormat.Protect(properties));
// Omitting the response_mode parameter when it already corresponds to the default
// response_mode used for the specified response_type is recommended by the specifications.
// See http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes
if (!string.Equals(Options.ResponseType, OpenIdConnectResponseType.Code, StringComparison.Ordinal) ||
!string.Equals(Options.ResponseMode, OpenIdConnectResponseMode.Query, StringComparison.Ordinal))
{
openIdConnectMessage.ResponseMode = Options.ResponseMode;
}
if (Options.ProtocolValidator.RequireNonce)
{
AddNonceToMessage(openIdConnectMessage);
}
var notification = new RedirectToIdenreplacedyProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
{
ProtocolMessage = openIdConnectMessage
};
await Options.Notifications.RedirectToIdenreplacedyProvider(notification);
if (!notification.HandledResponse)
{
string redirectUri = notification.ProtocolMessage.CreateAuthenticationRequestUrl();
if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
{
_logger.WriteWarning("The authenticate redirect URI is malformed: " + redirectUri);
}
Response.Redirect(redirectUri);
}
}
return;
}
19
Source : TwitterAuthenticationHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private async Task<AccessToken> ObtainAccessTokenAsync(string consumerKey, string consumerSecret, RequestToken token, string verifier)
{
// https://dev.twitter.com/docs/api/1/post/oauth/access_token
_logger.WriteVerbose("ObtainAccessToken");
string nonce = Guid.NewGuid().ToString("N");
var authorizationParts = new SortedDictionary<string, string>
{
{ "oauth_consumer_key", consumerKey },
{ "oauth_nonce", nonce },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_token", token.Token },
{ "oauth_timestamp", GenerateTimeStamp() },
{ "oauth_verifier", verifier },
{ "oauth_version", "1.0" },
};
var parameterBuilder = new StringBuilder();
foreach (var authorizationKey in authorizationParts)
{
parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(authorizationKey.Key), Uri.EscapeDataString(authorizationKey.Value));
}
parameterBuilder.Length--;
string parameterString = parameterBuilder.ToString();
var canonicalizedRequestBuilder = new StringBuilder();
canonicalizedRequestBuilder.Append(HttpMethod.Post.Method);
canonicalizedRequestBuilder.Append("&");
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(AccessTokenEndpoint));
canonicalizedRequestBuilder.Append("&");
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString));
string signature = ComputeSignature(consumerSecret, token.TokenSecret, canonicalizedRequestBuilder.ToString());
authorizationParts.Add("oauth_signature", signature);
authorizationParts.Remove("oauth_verifier");
var authorizationHeaderBuilder = new StringBuilder();
authorizationHeaderBuilder.Append("OAuth ");
foreach (var authorizationPart in authorizationParts)
{
authorizationHeaderBuilder.AppendFormat(
"{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value));
}
authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2;
var request = new HttpRequestMessage(HttpMethod.Post, AccessTokenEndpoint);
request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());
var formPairs = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("oauth_verifier", verifier)
};
request.Content = new FormUrlEncodedContent(formPairs);
HttpResponseMessage response = await _httpClient.SendAsync(request, Request.CallCancelled);
if (!response.IsSuccessStatusCode)
{
_logger.WriteError("AccessToken request failed with a status code of " + response.StatusCode);
response.EnsureSuccessStatusCode(); // throw
}
string responseText = await response.Content.ReadreplacedtringAsync();
IFormCollection responseParameters = WebHelpers.ParseForm(responseText);
return new AccessToken
{
Token = Uri.UnescapeDataString(responseParameters["oauth_token"]),
TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]),
UserId = Uri.UnescapeDataString(responseParameters["user_id"]),
ScreenName = Uri.UnescapeDataString(responseParameters["screen_name"])
};
}
19
Source : WsFederationAuthenticationHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
protected override async Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
{
return;
}
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge == null)
{
return;
}
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled);
}
string baseUri =
Request.Scheme +
Uri.SchemeDelimiter +
Request.Host +
Request.PathBase;
string currentUri =
baseUri +
Request.Path +
Request.QueryString;
// Save the original challenge URI so we can redirect back to it when we're done.
AuthenticationProperties properties = challenge.Properties;
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = currentUri;
}
WsFederationMessage wsFederationMessage = new WsFederationMessage()
{
IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
Wtrealm = Options.Wtrealm,
Wctx = WsFederationAuthenticationDefaults.WctxKey + "=" + Uri.EscapeDataString(Options.StateDataFormat.Protect(properties)),
Wa = WsFederationConstants.WsFederationActions.SignIn,
};
if (!string.IsNullOrWhiteSpace(Options.Wreply))
{
wsFederationMessage.Wreply = Options.Wreply;
}
var notification = new RedirectToIdenreplacedyProviderNotification<WsFederationMessage, WsFederationAuthenticationOptions>(Context, Options)
{
ProtocolMessage = wsFederationMessage
};
await Options.Notifications.RedirectToIdenreplacedyProvider(notification);
if (!notification.HandledResponse)
{
string redirectUri = notification.ProtocolMessage.CreateSignInUrl();
if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
{
_logger.WriteWarning("The sign-in redirect URI is malformed: " + redirectUri);
}
Response.Redirect(redirectUri);
}
}
19
Source : ResponseCookieCollection.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void Append(string key, string value)
{
Headers.AppendValues(Constants.Headers.SetCookie, Uri.EscapeDataString(key) + "=" + Uri.EscapeDataString(value) + "; path=/");
}
19
Source : ResponseCookieCollection.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void Append(string key, string value, CookieOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
bool pathHasValue = !string.IsNullOrEmpty(options.Path);
bool expiresHasValue = options.Expires.HasValue;
bool sameSiteHasValue = options.SameSite.HasValue;
string setCookieValue = string.Concat(
Uri.EscapeDataString(key),
"=",
Uri.EscapeDataString(value ?? string.Empty),
!domainHasValue ? null : "; domain=",
!domainHasValue ? null : options.Domain,
!pathHasValue ? null : "; path=",
!pathHasValue ? null : options.Path,
!expiresHasValue ? null : "; expires=",
!expiresHasValue ? null : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss \\G\\M\\T", CultureInfo.InvariantCulture),
!options.Secure ? null : "; secure",
!options.HttpOnly ? null : "; HttpOnly",
!sameSiteHasValue ? null : "; SameSite=",
!sameSiteHasValue ? null : GetStringRepresentationOfSameSite(options.SameSite.Value));
Headers.AppendValues(Constants.Headers.SetCookie, setCookieValue);
}
19
Source : ResponseCookieCollection.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void Delete(string key)
{
Func<string, bool> predicate = value => value.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase);
var deleteCookies = new[] { Uri.EscapeDataString(key) + "=; expires=Thu, 01-Jan-1970 00:00:00 GMT" };
IList<string> existingValues = Headers.GetValues(Constants.Headers.SetCookie);
if (existingValues == null || existingValues.Count == 0)
{
Headers.SetValues(Constants.Headers.SetCookie, deleteCookies);
}
else
{
Headers.SetValues(Constants.Headers.SetCookie, existingValues.Where(value => !predicate(value)).Concat(deleteCookies).ToArray());
}
}
19
Source : SystemWebChunkingCookieManager.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public string GetRequestCookie(IOwinContext context, string key)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
if (webContext == null)
{
return Fallback.GetRequestCookie(context, key);
}
var requestCookies = webContext.Request.Cookies;
var escapedKey = Uri.EscapeDataString(key);
var cookie = requestCookies[escapedKey];
if (cookie == null)
{
return null;
}
var value = cookie.Value;
int chunksCount = ParseChunksCount(value);
if (chunksCount > 0)
{
bool quoted = false;
string[] chunks = new string[chunksCount];
for (int chunkId = 1; chunkId <= chunksCount; chunkId++)
{
cookie = requestCookies[escapedKey + "C" + chunkId.ToString(CultureInfo.InvariantCulture)];
if (cookie == null)
{
if (ThrowForPartialCookies)
{
int totalSize = 0;
for (int i = 0; i < chunkId - 1; i++)
{
totalSize += chunks[i].Length;
}
throw new FormatException(
string.Format(CultureInfo.CurrentCulture, Resources.Exception_ImcompleteChunkedCookie, chunkId - 1, chunksCount, totalSize));
}
// Missing chunk, abort by returning the original cookie value. It may have been a false positive?
return Uri.UnescapeDataString(value);
}
string chunk = cookie.Value;
if (IsQuoted(chunk))
{
// Note: Since we replacedume these cookies were generated by our code, then we can replacedume that if one cookie has quotes then they all do.
quoted = true;
chunk = RemoveQuotes(chunk);
}
chunks[chunkId - 1] = chunk;
}
string merged = string.Join(string.Empty, chunks);
if (quoted)
{
merged = Quote(merged);
}
return Uri.UnescapeDataString(merged);
}
return Uri.UnescapeDataString(value);
}
19
Source : SystemWebCookieManager.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
if (webContext == null)
{
Fallback.AppendResponseCookie(context, key, value, options);
return;
}
bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
bool pathHasValue = !string.IsNullOrEmpty(options.Path);
bool expiresHasValue = options.Expires.HasValue;
var escapedKey = Uri.EscapeDataString(key);
var cookie = new HttpCookie(escapedKey, Uri.EscapeDataString(value));
if (domainHasValue)
{
cookie.Domain = options.Domain;
}
if (pathHasValue)
{
cookie.Path = options.Path;
}
if (expiresHasValue)
{
cookie.Expires = options.Expires.Value;
}
if (options.Secure)
{
cookie.Secure = true;
}
if (options.HttpOnly)
{
cookie.HttpOnly = true;
}
if (IsSameSiteAvailable)
{
SameSiteSetter.Invoke(cookie, new object[]
{
options.SameSite ?? (SameSiteMode)(-1) // Unspecified
});
}
webContext.Response.AppendCookie(cookie);
}
19
Source : FacebookAuthenticationHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
try
{
string code = null;
string state = null;
IReadableStringCollection query = Request.Query;
IList<string> values = query.GetValues("error");
if (values != null && values.Count >= 1)
{
_logger.WriteVerbose("Remote server returned an error: " + Request.QueryString);
}
values = query.GetValues("code");
if (values != null && values.Count == 1)
{
code = values[0];
}
values = query.GetValues("state");
if (values != null && values.Count == 1)
{
state = values[0];
}
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
return null;
}
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(Options.CookieManager, properties, _logger))
{
return new AuthenticationTicket(null, properties);
}
if (code == null)
{
// Null if the remote server returns an error.
return new AuthenticationTicket(null, properties);
}
string requestPrefix = Request.Scheme + "://" + Request.Host;
string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
string tokenRequest = "grant_type=authorization_code" +
"&code=" + Uri.EscapeDataString(code) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&client_id=" + Uri.EscapeDataString(Options.AppId) +
"&client_secret=" + Uri.EscapeDataString(Options.AppSecret);
HttpResponseMessage tokenResponse = await _httpClient.GetAsync(Options.TokenEndpoint + "?" + tokenRequest, Request.CallCancelled);
tokenResponse.EnsureSuccessStatusCode();
string text = await tokenResponse.Content.ReadreplacedtringAsync();
JObject response = JObject.Parse(text);
string accessToken = response.Value<string>("access_token");
if (string.IsNullOrWhiteSpace(accessToken))
{
_logger.WriteWarning("Access token was not found");
return new AuthenticationTicket(null, properties);
}
string expires = response.Value<string>("expires_in");
string graphAddress = WebUtilities.AddQueryString(Options.UserInformationEndpoint, "access_token", accessToken);
if (Options.SendAppSecretProof)
{
graphAddress = WebUtilities.AddQueryString(graphAddress, "appsecret_proof", GenerateAppSecretProof(accessToken));
}
if (Options.Fields.Count > 0)
{
graphAddress = WebUtilities.AddQueryString(graphAddress, "fields", string.Join(",", Options.Fields));
}
HttpResponseMessage graphResponse = await _httpClient.GetAsync(graphAddress, Request.CallCancelled);
graphResponse.EnsureSuccessStatusCode();
text = await graphResponse.Content.ReadreplacedtringAsync();
JObject user = JObject.Parse(text);
var context = new FacebookAuthenticatedContext(Context, user, accessToken, expires);
context.Idenreplacedy = new ClaimsIdenreplacedy(
Options.AuthenticationType,
ClaimsIdenreplacedy.DefaultNameClaimType,
ClaimsIdenreplacedy.DefaultRoleClaimType);
if (!string.IsNullOrEmpty(context.Id))
{
context.Idenreplacedy.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.UserName))
{
context.Idenreplacedy.AddClaim(new Claim(ClaimsIdenreplacedy.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.Email))
{
context.Idenreplacedy.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.Name))
{
context.Idenreplacedy.AddClaim(new Claim("urn:facebook:name", context.Name, XmlSchemaString, Options.AuthenticationType));
// Many Facebook accounts do not set the UserName field. Fall back to the Name field instead.
if (string.IsNullOrEmpty(context.UserName))
{
context.Idenreplacedy.AddClaim(new Claim(ClaimsIdenreplacedy.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
}
}
if (!string.IsNullOrEmpty(context.Link))
{
context.Idenreplacedy.AddClaim(new Claim("urn:facebook:link", context.Link, XmlSchemaString, Options.AuthenticationType));
}
context.Properties = properties;
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Idenreplacedy, context.Properties);
}
catch (Exception ex)
{
_logger.WriteError("Authentication failed", ex);
return new AuthenticationTicket(null, properties);
}
}
19
Source : MicrosoftAccountAuthenticationHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
protected override Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
{
return Task.FromResult<object>(null);
}
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge != null)
{
string baseUri = Request.Scheme + Uri.SchemeDelimiter + Request.Host + Request.PathBase;
string currentUri = baseUri + Request.Path + Request.QueryString;
string redirectUri = baseUri + Options.CallbackPath;
AuthenticationProperties extra = challenge.Properties;
if (string.IsNullOrEmpty(extra.RedirectUri))
{
extra.RedirectUri = currentUri;
}
// OAuth2 10.12 CSRF
GenerateCorrelationId(Options.CookieManager, extra);
// OAuth2 3.3 space separated
string scope = string.Join(" ", Options.Scope);
// LiveID requires a scope string, so if the user didn't set one we go for the least possible.
if (string.IsNullOrWhiteSpace(scope))
{
scope = "https://graph.microsoft.com/user.read";
}
string state = Options.StateDataFormat.Protect(extra);
string authorizationEndpoint =
Options.AuthorizationEndpoint +
"?client_id=" + Uri.EscapeDataString(Options.ClientId) +
"&scope=" + Uri.EscapeDataString(scope) +
"&response_type=code" +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&state=" + Uri.EscapeDataString(state);
var redirectContext = new MicrosoftAccountApplyRedirectContext(
Context, Options,
extra, authorizationEndpoint);
Options.Provider.ApplyRedirect(redirectContext);
}
return Task.FromResult<object>(null);
}
19
Source : OAuthAuthorizationServerHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public Appender Append(string name, string value)
{
_sb.Append(_hasDelimiter ? '&' : _delimiter)
.Append(Uri.EscapeDataString(name))
.Append('=')
.Append(Uri.EscapeDataString(value));
_hasDelimiter = true;
return this;
}
19
Source : TwitterAuthenticationHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private async Task<RequestToken> ObtainRequestTokenAsync(string consumerKey, string consumerSecret, string callBackUri, AuthenticationProperties properties)
{
_logger.WriteVerbose("ObtainRequestToken");
string nonce = Guid.NewGuid().ToString("N");
var authorizationParts = new SortedDictionary<string, string>
{
{ "oauth_callback", callBackUri },
{ "oauth_consumer_key", consumerKey },
{ "oauth_nonce", nonce },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", GenerateTimeStamp() },
{ "oauth_version", "1.0" }
};
var parameterBuilder = new StringBuilder();
foreach (var authorizationKey in authorizationParts)
{
parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(authorizationKey.Key), Uri.EscapeDataString(authorizationKey.Value));
}
parameterBuilder.Length--;
string parameterString = parameterBuilder.ToString();
var canonicalizedRequestBuilder = new StringBuilder();
canonicalizedRequestBuilder.Append(HttpMethod.Post.Method);
canonicalizedRequestBuilder.Append("&");
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(RequestTokenEndpoint));
canonicalizedRequestBuilder.Append("&");
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString));
string signature = ComputeSignature(consumerSecret, null, canonicalizedRequestBuilder.ToString());
authorizationParts.Add("oauth_signature", signature);
var authorizationHeaderBuilder = new StringBuilder();
authorizationHeaderBuilder.Append("OAuth ");
foreach (var authorizationPart in authorizationParts)
{
authorizationHeaderBuilder.AppendFormat(
"{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value));
}
authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2;
var request = new HttpRequestMessage(HttpMethod.Post, RequestTokenEndpoint);
request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());
HttpResponseMessage response = await _httpClient.SendAsync(request, Request.CallCancelled);
response.EnsureSuccessStatusCode();
string responseText = await response.Content.ReadreplacedtringAsync();
IFormCollection responseParameters = WebHelpers.ParseForm(responseText);
if (string.Equals(responseParameters["oauth_callback_confirmed"], "true", StringComparison.InvariantCulture))
{
return new RequestToken { Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), CallbackConfirmed = true, Properties = properties };
}
return new RequestToken();
}
19
Source : TwitterAuthenticationHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private static string ComputeSignature(string consumerSecret, string tokenSecret, string signatureData)
{
using (var algorithm = new HMACSHA1())
{
algorithm.Key = Encoding.ASCII.GetBytes(
string.Format(CultureInfo.InvariantCulture,
"{0}&{1}",
Uri.EscapeDataString(consumerSecret),
string.IsNullOrEmpty(tokenSecret) ? string.Empty : Uri.EscapeDataString(tokenSecret)));
byte[] hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(signatureData));
return Convert.ToBase64String(hash);
}
}
19
Source : SystemWebChunkingCookieManager.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
if (webContext == null)
{
Fallback.DeleteCookie(context, key, options);
return;
}
string escapedKey = Uri.EscapeDataString(key);
var requestCookies = webContext.Request.Cookies;
var cookie = requestCookies[escapedKey];
string requestCookie = (cookie == null ? null : cookie.Value);
int chunks = ParseChunksCount(requestCookie);
AppendResponseCookie(
context,
key,
string.Empty,
new CookieOptions
{
Path = options.Path,
Domain = options.Domain,
HttpOnly = options.HttpOnly,
SameSite = options.SameSite,
Secure = options.Secure,
Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
for (int i = 1; i <= chunks; i++)
{
AppendResponseCookie(
context,
key + "C" + i.ToString(CultureInfo.InvariantCulture),
string.Empty,
new CookieOptions
{
Path = options.Path,
Domain = options.Domain,
HttpOnly = options.HttpOnly,
SameSite = options.SameSite,
Secure = options.Secure,
Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
}
}
19
Source : GoogleOAuth2MiddlewareTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task ReplyPathWillAuthenticateValidAuthorizeCodeAndState()
{
var options = new GoogleOAuth2AuthenticationOptions()
{
ClientId = "Test Id",
ClientSecret = "Test Secret",
BackchannelHttpHandler = new TestHttpMessageHandler
{
Sender = async req =>
{
if (req.RequestUri.AbsoluteUri == "https://oauth2.googleapis.com/token")
{
return await ReturnJsonResponse(new
{
access_token = "Test Access Token",
expire_in = 3600,
token_type = "Bearer"
});
}
else if (req.RequestUri.GetLeftPart(UriPartial.Path) == "https://www.googleapis.com/oauth2/v2/userinfo")
{
return await ReturnJsonResponse(new
{
id = "Test User ID",
name = "Test Name",
given_name = "Test Given Name",
family_name = "Test Family Name",
link = "Profile link",
email = "Test email",
});
}
return null;
}
}
};
var server = CreateServer(options);
var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Google";
var correlationValue = "TestCorrelationId";
properties.Dictionary.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = options.StateDataFormat.Protect(properties);
var transaction = await SendAsync(server,
"https://example.com/signin-google?code=TestCode&state=" + Uri.EscapeDataString(state),
correlationKey + "=" + correlationValue);
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
transaction.Response.Headers.Location.ToString().ShouldBe("/me");
transaction.SetCookie.Count.ShouldBe(2);
transaction.SetCookie[0].ShouldContain(correlationKey);
transaction.SetCookie[1].ShouldContain(".AspNet.Cookie");
var authCookie = transaction.AuthenticationCookieValue;
transaction = await SendAsync(server, "https://example.com/me", authCookie);
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
transaction.FindClaimValue(ClaimTypes.Name).ShouldBe("Test Name");
transaction.FindClaimValue(ClaimTypes.NameIdentifier).ShouldBe("Test User ID");
transaction.FindClaimValue(ClaimTypes.GivenName).ShouldBe("Test Given Name");
transaction.FindClaimValue(ClaimTypes.Surname).ShouldBe("Test Family Name");
transaction.FindClaimValue(ClaimTypes.Email).ShouldBe("Test email");
}
19
Source : GoogleOAuth2MiddlewareTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task ReplyPathWillRejectIfCodeIsInvalid()
{
var options = new GoogleOAuth2AuthenticationOptions()
{
ClientId = "Test Id",
ClientSecret = "Test Secret",
BackchannelHttpHandler = new TestHttpMessageHandler
{
Sender = req =>
{
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest));
}
}
};
var server = CreateServer(options);
var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Google";
var correlationValue = "TestCorrelationId";
properties.Dictionary.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = options.StateDataFormat.Protect(properties);
var transaction = await SendAsync(server,
"https://example.com/signin-google?code=TestCode&state=" + Uri.EscapeDataString(state),
correlationKey + "=" + correlationValue);
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
transaction.Response.Headers.Location.ToString().ShouldContain("error=access_denied");
}
19
Source : GoogleOAuth2MiddlewareTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task ReplyPathWillRejectIfAccessTokenIsMissing()
{
var options = new GoogleOAuth2AuthenticationOptions()
{
ClientId = "Test Id",
ClientSecret = "Test Secret",
BackchannelHttpHandler = new TestHttpMessageHandler
{
Sender = async req =>
{
return await ReturnJsonResponse(new object());
}
}
};
var server = CreateServer(options);
var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Google";
var correlationValue = "TestCorrelationId";
properties.Dictionary.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = options.StateDataFormat.Protect(properties);
var transaction = await SendAsync(server,
"https://example.com/signin-google?code=TestCode&state=" + Uri.EscapeDataString(state),
correlationKey + "=" + correlationValue);
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
transaction.Response.Headers.Location.ToString().ShouldContain("error=access_denied");
}
19
Source : GoogleOAuth2MiddlewareTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task AuthenticatedEventCanGetRefreshToken()
{
var options = new GoogleOAuth2AuthenticationOptions()
{
ClientId = "Test Id",
ClientSecret = "Test Secret",
BackchannelHttpHandler = new TestHttpMessageHandler
{
Sender = async req =>
{
if (req.RequestUri.AbsoluteUri == "https://oauth2.googleapis.com/token")
{
return await ReturnJsonResponse(new
{
access_token = "Test Access Token",
expire_in = 3600,
token_type = "Bearer",
refresh_token = "Test Refresh Token"
});
}
else if (req.RequestUri.GetLeftPart(UriPartial.Path) == "https://www.googleapis.com/oauth2/v2/userinfo")
{
return await ReturnJsonResponse(new
{
id = "Test User ID",
name = "Test Name",
given_name = "Test Given Name",
family_name = "Test Family Name",
link = "Profile link",
email = "Test email",
});
}
return null;
}
},
Provider = new GoogleOAuth2AuthenticationProvider
{
OnAuthenticated = context =>
{
var refreshToken = context.RefreshToken;
context.Idenreplacedy.AddClaim(new Claim("RefreshToken", refreshToken));
return Task.FromResult<object>(null);
}
}
};
var server = CreateServer(options);
var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Google";
var correlationValue = "TestCorrelationId";
properties.Dictionary.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = options.StateDataFormat.Protect(properties);
var transaction = await SendAsync(server,
"https://example.com/signin-google?code=TestCode&state=" + Uri.EscapeDataString(state),
correlationKey + "=" + correlationValue);
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
transaction.Response.Headers.Location.ToString().ShouldBe("/me");
transaction.SetCookie.Count.ShouldBe(2);
transaction.SetCookie[0].ShouldContain(correlationKey);
transaction.SetCookie[1].ShouldContain(".AspNet.Cookie");
var authCookie = transaction.AuthenticationCookieValue;
transaction = await SendAsync(server, "https://example.com/me", authCookie);
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
transaction.FindClaimValue("RefreshToken").ShouldBe("Test Refresh Token");
}
19
Source : MicrosoftAccountMiddlewareTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task AuthenticatedEventCanGetRefreshToken()
{
var options = new MicrosoftAccountAuthenticationOptions()
{
ClientId = "Test Client Id",
ClientSecret = "Test Client Secret",
BackchannelHttpHandler = new TestHttpMessageHandler
{
Sender = async req =>
{
if (req.RequestUri.AbsoluteUri == "https://login.microsoftonline.com/common/oauth2/v2.0/token")
{
return await ReturnJsonResponse(new
{
access_token = "Test Access Token",
expire_in = 3600,
token_type = "Bearer",
refresh_token = "Test Refresh Token"
});
}
else if (req.RequestUri.GetLeftPart(UriPartial.Path) == "https://graph.microsoft.com/v1.0/me")
{
return await ReturnJsonResponse(new
{
id = "Test User ID",
displayName = "Test Name",
givenName = "Test Given Name",
surname = "Test Family Name",
mail = "Test email"
});
}
return null;
}
},
Provider = new MicrosoftAccountAuthenticationProvider
{
OnAuthenticated = context =>
{
var refreshToken = context.RefreshToken;
context.Idenreplacedy.AddClaim(new Claim("RefreshToken", refreshToken));
return Task.FromResult<object>(null);
}
}
};
var server = CreateServer(
app => app.UseMicrosoftAccountAuthentication(options),
context =>
{
var req = context.Request;
var res = context.Response;
Describe(res, new AuthenticateResult(req.User.Idenreplacedy, new AuthenticationProperties(), new AuthenticationDescription()));
return true;
});
var properties = new AuthenticationProperties();
var correlationKey = ".AspNet.Correlation.Microsoft";
var correlationValue = "TestCorrelationId";
properties.Dictionary.Add(correlationKey, correlationValue);
properties.RedirectUri = "/me";
var state = options.StateDataFormat.Protect(properties);
var transaction = await SendAsync(server,
"https://example.com/signin-microsoft?code=TestCode&state=" + Uri.EscapeDataString(state),
correlationKey + "=" + correlationValue);
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
transaction.Response.Headers.Location.ToString().ShouldBe("/me");
transaction.SetCookie.Count.ShouldBe(2);
transaction.SetCookie[0].ShouldContain(correlationKey);
transaction.SetCookie[1].ShouldContain(".AspNet.External");
var authCookie = transaction.AuthenticationCookieValue;
transaction = await SendAsync(server, "https://example.com/me", authCookie);
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
transaction.FindClaimValue("RefreshToken").ShouldBe("Test Refresh Token");
}
19
Source : OAuth2AuthorizationServerAuthorizationCodeGrantTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task IncorrectRedirectUriDoesNotRedirect()
{
var server = new OAuth2TestServer();
OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&redirect_uri=" + Uri.EscapeDataString("http://wrongplace.com/"));
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
transaction.ResponseText.ShouldContain("invalid_request");
}
19
Source : OAuth2AuthorizationServerAuthorizationCodeGrantTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task CodeFlowWillFailIfRedirectUriOriginallyIncorrect()
{
var server = new OAuth2TestServer(s =>
{
s.Options.AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(5);
s.Options.AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60);
s.OnAuthorizeEndpoint = SignInEpsilon;
});
OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code&redirect_uri=" + Uri.EscapeDataString("https://gamma2.com/return"));
transaction.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
}
19
Source : OAuth2AuthorizationServerAuthorizationCodeGrantTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task CodeFlowWillFailIfRedirectUriOriginallyProvidedAndNotRepeated()
{
var server = new OAuth2TestServer(s =>
{
s.Options.AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(5);
s.Options.AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60);
s.OnAuthorizeEndpoint = SignInEpsilon;
});
OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));
NameValueCollection query = transaction.ParseRedirectQueryString();
OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token",
authenticateHeader: new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha:beta"))),
postBody: "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha");
transaction2.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
transaction2.ResponseToken["error"].Value<string>().ShouldBe("invalid_grant");
}
19
Source : OAuth2AuthorizationServerAuthorizationCodeGrantTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task CodeFlowWillFailIfRedirectUriRepeatedIncorrectly()
{
var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });
OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));
NameValueCollection query = transaction.ParseRedirectQueryString();
OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token",
authenticateHeader: new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha:beta"))),
postBody: "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha&redirect_uri=" + Uri.EscapeDataString("https://gamma2.com/return"));
transaction2.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
transaction2.ResponseToken["error"].Value<string>().ShouldBe("invalid_grant");
}
19
Source : OAuth2AuthorizationServerAuthorizationCodeGrantTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task CodeFlowWillSucceedWithCorrectRedirectUriThatIsRepeated()
{
var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });
OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));
NameValueCollection query = transaction.ParseRedirectQueryString();
OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token",
authenticateHeader: new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha:beta"))),
postBody: "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha&redirect_uri=" + Uri.EscapeDataString("https://gamma2.com/return"));
transaction2.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
transaction2.ResponseToken["error"].Value<string>().ShouldBe("invalid_grant");
}
19
Source : OAuth2AuthorizationServerAuthorizationCodeGrantTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task CodeFlowRedirectUriMustMatch()
{
var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });
OAuth2TestServer.Transaction transaction = await server.SendAsync("https://example.com/authorize?client_id=alpha&response_type=code&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));
NameValueCollection query = transaction.ParseRedirectQueryString();
OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/token",
authenticateHeader: new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("alpha:beta"))),
postBody: "grant_type=authorization_code&code=" + query["code"] + "&client_id=alpha&redirect_uri=");
transaction2.Response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
transaction2.ResponseToken["error"].Value<string>().ShouldBe("invalid_grant");
}
19
Source : OAuth2AuthorizationServerImplicitGrantTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task StateMustBePreplacededBackOnError()
{
var server = new OAuth2TestServer();
OAuth2TestServer.Transaction transaction1 = await server.SendAsync("https://example.com/authorize?response_type=token&client_id=unauthorized&state=123&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));
NameValueCollection queryStringWithState = transaction1.ParseRedirectQueryString();
queryStringWithState.Get("access_token").ShouldBe(null);
queryStringWithState.Get("error").ShouldBe("unauthorized_client");
queryStringWithState.Get("state").ShouldBe("123");
OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/authorize?response_type=token&client_id=unauthorized&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));
NameValueCollection queryStringNoState = transaction2.ParseRedirectQueryString();
queryStringNoState.Get("access_token").ShouldBe(null);
queryStringNoState.Get("error").ShouldBe("unauthorized_client");
queryStringNoState.Get("state").ShouldBe(null);
}
19
Source : OAuth2AuthorizationServerImplicitGrantTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task AccessTokenMayBeUsed()
{
var server = new OAuth2TestServer(s => { s.OnAuthorizeEndpoint = SignInEpsilon; });
OAuth2TestServer.Transaction transaction1 = await server.SendAsync("https://example.com/authorize?response_type=token&client_id=alpha&redirect_uri=" + Uri.EscapeDataString("https://gamma.com/return"));
NameValueCollection fragment = transaction1.ParseRedirectFragment();
string accessToken = fragment.Get("access_token");
OAuth2TestServer.Transaction transaction2 = await server.SendAsync("https://example.com/me",
authenticateHeader: new AuthenticationHeaderValue("Bearer", accessToken));
transaction2.Response.StatusCode.ShouldBe(HttpStatusCode.OK);
transaction2.ResponseText.ShouldBe("epsilon");
}
See More Examples