/// <summary> /// Create session /// </summary> /// <returns>result of create session operation</returns> public async Task <IHttpActionResult> PostSession() { var postSessionRequest = new PostSessionRequest { InstanceId = "SessionsControllerTests", UserHandle = this.UserHandle, }; return(await this.PostSession(postSessionRequest)); }
public PostWebRequest(PostSessionRequest request) : this() { AddCookies(request.RequestCookies); if ( request.Form != null ) Form.ReadHtmlFormTag(request.Form); RequestHttpSettings = request.RequestHttpSettings; Url = request.Url.ToString(); ID = GenerateID; }
public async Task <IHttpActionResult> PostSession([FromBody] PostSessionRequest request) { string className = "SessionsController"; string methodName = "PostSession"; string logEntry = $"SessionUserHandle = {request?.UserHandle}"; this.LogControllerStart(this.log, className, methodName, logEntry); // Check whether user handle is null if (this.UserHandle == null) { this.log.LogError("Unauthorized because PostSession called without a user handle"); return(this.Unauthorized(ResponseStrings.GenericUnauthorizedError)); } // The auth's user principal must have the same user handle as the one in PostSession request if (this.UserHandle != request.UserHandle) { this.log.LogError(string.Format("Unauthorized because one user handle called PostSession on behalf of another user handle. Auth's UserHandle: {0}, Request's UserHandle: {1}", this.User, request.UserHandle)); return(this.Unauthorized(ResponseStrings.UserUnauthorized)); } // Is user handle registered with this app? var userProfileEntity = await this.usersManager.ReadUserProfile(this.UserHandle, this.AppHandle); if (userProfileEntity == null) { this.log.LogError(string.Format("No user profile found for this app. UserHandle: {0}, AppHandle {1}", this.UserHandle, this.AppHandle)); return(this.NotFound(ResponseStrings.UserNotFound)); } // Generate session token string sessionToken = await this.tokenManager.CreateToken(this.AppPrincipal, this.UserPrincipal, this.sessionTokenDuration); PostSessionResponse response = new PostSessionResponse() { UserHandle = this.UserHandle, SessionToken = sessionToken }; // Log user session start to app metrics this.applicationMetrics.AddActiveUser(); this.LogControllerEnd(this.log, className, methodName, logEntry); return(this.Created <PostSessionResponse>(this.UserHandle, response)); }
public async Task CreateDeleteSessionTest() { SocialPlusClient client = new SocialPlusClient(TestConstants.ServerApiBaseUrl); PostUserResponse postUserResponse = await TestUtilities.DoLogin(client, "Barack", "Obama", "president"); string auth = AuthHelper.CreateSocialPlusAuth(postUserResponse.SessionToken); // Delete session (corresponding to log off) await client.Sessions.DeleteSessionAsync(authorization : auth); // Create session (corresponding to log on) PostSessionRequest postSessionRequest = new PostSessionRequest("E2Etests", postUserResponse.UserHandle); var postSessionResponse = await client.Sessions.PostSessionWithHttpMessagesAsync(postSessionRequest, auth); // Delete user string newAuth = AuthHelper.CreateSocialPlusAuth(postSessionResponse.Body.SessionToken); await client.Users.DeleteUserAsync(authorization : newAuth); }
/// <summary> /// Creates an Embedded Social authorization field /// </summary> /// <param name="aadAuthorization">AAD authorization field</param> /// <param name="userHandle">user handle that corresponds to the AAD authorization field</param> /// <returns>authorization value</returns> private async Task <string> CreateEmbeddedSocialAuth(string aadAuthorization, string userHandle) { PostSessionRequest sessionRequest = new PostSessionRequest() { InstanceId = "OneBusAway Service", UserHandle = userHandle }; HttpOperationResponse <PostSessionResponse> response = await this.client.Sessions.PostSessionWithHttpMessagesAsync(request : sessionRequest, authorization : aadAuthorization); if (response == null || response.Response == null) { throw new Exception("did not get a valid response to POST session"); } else if (!response.Response.IsSuccessStatusCode) { throw new Exception("POST session failed with HTTP code " + response.Response.StatusCode); } else if (response.Body == null || string.IsNullOrWhiteSpace(response.Body.SessionToken)) { throw new Exception("POST session resulted in invalid post session response structure"); } return("SocialPlus TK=" + response.Body.SessionToken); }
/// <summary> /// Create a new session (sign in) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='request'> /// Post session request /// </param> /// <param name='authorization'> /// Format is: "Scheme CredentialsList". Possible values are: /// /// - Anon AK=AppKey /// /// - SocialPlus TK=SessionToken /// /// - Facebook AK=AppKey|TK=AccessToken /// /// - Google AK=AppKey|TK=AccessToken /// /// - Twitter AK=AppKey|RT=RequestToken|TK=AccessToken /// /// - Microsoft AK=AppKey|TK=AccessToken /// /// - AADS2S AK=AppKey|[UH=UserHandle]|TK=AADToken /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <PostSessionResponse> PostSessionAsync(this ISessions operations, PostSessionRequest request, string authorization, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostSessionWithHttpMessagesAsync(request, authorization, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Create a new session (sign in) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='request'> /// Post session request /// </param> /// <param name='authorization'> /// Format is: "Scheme CredentialsList". Possible values are: /// /// - Anon AK=AppKey /// /// - SocialPlus TK=SessionToken /// /// - Facebook AK=AppKey|TK=AccessToken /// /// - Google AK=AppKey|TK=AccessToken /// /// - Twitter AK=AppKey|RT=RequestToken|TK=AccessToken /// /// - Microsoft AK=AppKey|TK=AccessToken /// /// - AADS2S AK=AppKey|[UH=UserHandle]|TK=AADToken /// </param> public static PostSessionResponse PostSession(this ISessions operations, PostSessionRequest request, string authorization) { return(Task.Factory.StartNew(s => ((ISessions)s).PostSessionAsync(request, authorization), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }
/// <summary> /// Create a new session (sign in) /// </summary> /// <param name='request'> /// Post session request /// </param> /// <param name='authorization'> /// Format is: "Scheme CredentialsList". Possible values are: /// /// - Anon AK=AppKey /// /// - SocialPlus TK=SessionToken /// /// - Facebook AK=AppKey|TK=AccessToken /// /// - Google AK=AppKey|TK=AccessToken /// /// - Twitter AK=AppKey|RT=RequestToken|TK=AccessToken /// /// - Microsoft AK=AppKey|TK=AccessToken /// /// - AADS2S AK=AppKey|[UH=UserHandle]|TK=AADToken /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <PostSessionResponse> > PostSessionWithHttpMessagesAsync(PostSessionRequest request, string authorization, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (request == null) { throw new ValidationException(ValidationRules.CannotBeNull, "request"); } if (request != null) { request.Validate(); } if (authorization == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorization"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("request", request); tracingParameters.Add("authorization", authorization); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostSession", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.7/sessions").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (authorization != null) { if (_httpRequest.Headers.Contains("Authorization")) { _httpRequest.Headers.Remove("Authorization"); } _httpRequest.Headers.TryAddWithoutValidation("Authorization", authorization); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (request != null) { _requestContent = SafeJsonConvert.SerializeObject(request, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 401 && (int)_statusCode != 404 && (int)_statusCode != 500) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <PostSessionResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <PostSessionResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }