internal static HttpRequestInfo CreateHttpRequestInfo(string method, IDictionary<string, string> fields) { string query = MessagingUtilities.CreateQueryString(fields); UriBuilder requestUri = new UriBuilder("http://localhost/path"); WebHeaderCollection headers = new WebHeaderCollection(); MemoryStream ms = new MemoryStream(); if (method == "POST") { headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); StreamWriter sw = new StreamWriter(ms); sw.Write(query); sw.Flush(); ms.Position = 0; } else if (method == "GET") { requestUri.Query = query; } else { throw new ArgumentOutOfRangeException("method", method, "Expected POST or GET"); } HttpRequestInfo request = new HttpRequestInfo { HttpMethod = method, UrlBeforeRewriting = requestUri.Uri, Headers = headers, InputStream = ms, }; return request; }
public void UserSetupUrl() { // Construct a V1 immediate request Protocol protocol = Protocol.V11; OpenIdProvider provider = this.CreateProvider(); CheckIdRequest immediateRequest = new CheckIdRequest(protocol.Version, OPUri, DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Immediate); immediateRequest.Realm = RPRealmUri; immediateRequest.ReturnTo = RPUri; immediateRequest.LocalIdentifier = "http://somebody"; AuthenticationRequest request = new AuthenticationRequest(provider, immediateRequest); // Now simulate the request being rejected and extract the user_setup_url request.IsAuthenticated = false; Uri userSetupUrl = ((NegativeAssertionResponse)request.Response).UserSetupUrl; Assert.IsNotNull(userSetupUrl); // Now construct a new request as if it had just come in. HttpRequestInfo httpRequest = new HttpRequestInfo { UrlBeforeRewriting = userSetupUrl }; var setupRequest = AuthenticationRequest_Accessor.AttachShadow(provider.GetRequest(httpRequest)); CheckIdRequest_Accessor setupRequestMessage = setupRequest.RequestMessage; // And make sure all the right properties are set. Assert.IsFalse(setupRequestMessage.Immediate); Assert.AreEqual(immediateRequest.Realm, setupRequestMessage.Realm); Assert.AreEqual(immediateRequest.ReturnTo, setupRequestMessage.ReturnTo); Assert.AreEqual(immediateRequest.LocalIdentifier, setupRequestMessage.LocalIdentifier); Assert.AreEqual(immediateRequest.Version, setupRequestMessage.Version); }
/// <summary> /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="request">The request to search for an embedded message.</param> /// <returns> /// The deserialized message, if one is found. Null otherwise. /// </returns> protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) { Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.HttpMethod, request.UrlBeforeRewriting.AbsoluteUri); var fields = request.QueryStringBeforeRewriting.ToDictionary(); // Also read parameters from the fragment, if it's available. // Typically the fragment is not available because the browser doesn't send it to a web server // but this request may have been fabricated by an installed desktop app, in which case // the fragment is available. string fragment = request.UrlBeforeRewriting.Fragment; if (!string.IsNullOrEmpty(fragment)) { foreach (var pair in HttpUtility.ParseQueryString(fragment.Substring(1)).ToDictionary()) { fields.Add(pair.Key, pair.Value); } } MessageReceivingEndpoint recipient; try { recipient = request.GetRecipient(); } catch (ArgumentException ex) { Logger.Messaging.WarnFormat("Unrecognized HTTP request: ", ex); return null; } return (IDirectedProtocolMessage)this.Receive(fields, recipient); }
public static Uri GetRequestUrlFromContext() { Contract.Requires <InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); HttpContext context = HttpContext.Current; return(HttpRequestInfo.GetPublicFacingUrl(context.Request, context.Request.ServerVariables)); }
/// <summary> /// Reads in a client's request for the Authorization Server to obtain permission from /// the user to authorize the Client's access of some protected resource(s). /// </summary> /// <param name="request">The HTTP request to read from.</param> /// <returns>The incoming request, or null if no OAuth message was attached.</returns> /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> public EndUserAuthorizationRequest ReadAuthorizationRequest(HttpRequestInfo request = null) { if (request == null) { request = this.Channel.GetRequestFromContext(); } EndUserAuthorizationRequest message; this.Channel.TryReadFromRequest(request, out message); return message; }
public void GetPrincipalWithMissingAccessToken() { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); var requestHeaders = new NameValueCollection { { "Authorization", "Bearer " }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); Assert.That(() => resourceServer.GetPrincipalAsync(request).GetAwaiter().GetResult(), Throws.InstanceOf<ProtocolException>()); }
public void GetAccessTokenWithTotallyFakeToken() { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); var requestHeaders = new NameValueCollection { { "Authorization", "Bearer foobar" }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); Assert.That(() => resourceServer.GetAccessToken(request), Throws.InstanceOf<ProtocolException>()); }
public void CtorRequest() { HttpRequest request = new HttpRequest("file", "http://someserver?a=b", "a=b"); ////request.Headers["headername"] = "headervalue"; // PlatformNotSupportedException prevents us mocking this up HttpRequestInfo info = new HttpRequestInfo(request); Assert.AreEqual(request.Headers["headername"], info.Headers["headername"]); Assert.AreEqual(request.Url.Query, info.Query); Assert.AreEqual(request.QueryString["a"], info.QueryString["a"]); Assert.AreEqual(request.Url, info.Url); Assert.AreEqual(request.HttpMethod, info.HttpMethod); }
public void GetAccessTokenWithCorruptedToken() { var accessToken = this.ObtainValidAccessToken(); var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); var requestHeaders = new NameValueCollection { { "Authorization", "Bearer " + accessToken.Substring(0, accessToken.Length - 1) + "zzz" }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); Assert.That(() => resourceServer.GetAccessToken(request), Throws.InstanceOf<ProtocolException>()); }
/// <summary> /// Processes an incoming authorization-granted message from an SP and obtains an access token. /// </summary> /// <param name="request">The incoming HTTP request.</param> /// <returns>The access token, or null if no incoming authorization message was recognized.</returns> public AuthorizedTokenResponse ProcessUserAuthorization(HttpRequestInfo request) { Requires.NotNull(request, "request"); UserAuthorizationResponse authorizationMessage; if (this.Channel.TryReadFromRequest<UserAuthorizationResponse>(request, out authorizationMessage)) { string requestToken = authorizationMessage.RequestToken; string verifier = authorizationMessage.VerificationCode; return this.ProcessUserAuthorization(requestToken, verifier); } else { return null; } }
/// <summary> /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="httpRequest">The request to search for an embedded message.</param> /// <returns>The deserialized message, if one is found. Null otherwise.</returns> public IDirectedProtocolMessage ReadFromRequest(HttpRequestInfo httpRequest) { IDirectedProtocolMessage requestMessage = this.ReadFromRequestInternal(httpRequest); if (requestMessage != null) { Logger.DebugFormat("Incoming request received: {0}", requestMessage); this.VerifyMessageAfterReceiving(requestMessage); } return(requestMessage); }
public void GetAccessTokenWithValidToken() { var accessToken = this.ObtainValidAccessToken(); var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); var requestHeaders = new NameValueCollection { { "Authorization", "Bearer " + accessToken }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); var resourceServerDecodedToken = resourceServer.GetAccessToken(request); Assert.That(resourceServerDecodedToken, Is.Not.Null); }
public TRequest ReadFromRequest <TRequest>(HttpRequestInfo httpRequest) where TRequest : class, IProtocolMessage { TRequest request; if (this.TryReadFromRequest <TRequest>(httpRequest, out request)) { return(request); } else { throw ErrorUtilities.ThrowProtocol(MessagingStrings.ExpectedMessageNotReceived, typeof(TRequest)); } }
/// <summary> /// Gets the protocol message embedded in the given HTTP request, if present. /// </summary> /// <typeparam name="TRequest">The expected type of the message to be received.</typeparam> /// <param name="httpRequest">The request to search for an embedded message.</param> /// <param name="request">The deserialized message, if one is found. Null otherwise.</param> /// <returns>True if the expected message was recognized and deserialized. False otherwise.</returns> /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> /// <exception cref="ProtocolException">Thrown when a request message of an unexpected type is received.</exception> public bool TryReadFromRequest <TRequest>(HttpRequestInfo httpRequest, out TRequest request) where TRequest : class, IProtocolMessage { IProtocolMessage untypedRequest = this.ReadFromRequest(httpRequest); if (untypedRequest == null) { request = null; return(false); } request = untypedRequest as TRequest; ErrorUtilities.VerifyProtocol(request != null, MessagingStrings.UnexpectedMessageReceived, typeof(TRequest), untypedRequest.GetType()); return(true); }
/// <summary> /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="request">The request to search for an embedded message.</param> /// <returns>The deserialized message, if one is found. Null otherwise.</returns> protected virtual IDirectedProtocolMessage ReadFromRequestInternal(HttpRequestInfo request) { ErrorUtilities.VerifyArgumentNotNull(request, "request"); Logger.DebugFormat("Incoming HTTP request: {0}", request.Url.AbsoluteUri); // Search Form data first, and if nothing is there search the QueryString var fields = request.Form.ToDictionary(); if (fields.Count == 0) { fields = request.QueryString.ToDictionary(); } return((IDirectedProtocolMessage)this.Receive(fields, request.GetRecipient())); }
/// <summary> /// Reads in a client's request for the Authorization Server to obtain permission from /// the user to authorize the Client's access of some protected resource(s). /// </summary> /// <param name="request">The HTTP request to read from.</param> /// <returns>The incoming request, or null if no OAuth message was attached.</returns> /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> public EndUserAuthorizationRequest ReadAuthorizationRequest(HttpRequestInfo request = null) { if (request == null) { request = this.Channel.GetRequestFromContext(); } EndUserAuthorizationRequest message; if (this.Channel.TryReadFromRequest(request, out message)) { if (message.ResponseType == EndUserAuthorizationResponseType.AuthorizationCode) { // Clients with no secrets can only request implicit grant types. var client = this.AuthorizationServerServices.GetClientOrThrow(message.ClientIdentifier); ErrorUtilities.VerifyProtocol(!String.IsNullOrEmpty(client.Secret), Protocol.unauthorized_client); } } return message; }
/// <summary> /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="request">The request to search for an embedded message.</param> /// <returns> /// The deserialized message, if one is found. Null otherwise. /// </returns> protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) { if (!string.IsNullOrEmpty(request.Url.Fragment)) { var fields = HttpUtility.ParseQueryString(request.Url.Fragment.Substring(1)).ToDictionary(); MessageReceivingEndpoint recipient; try { recipient = request.GetRecipient(); } catch (ArgumentException ex) { Logger.Messaging.WarnFormat("Unrecognized HTTP request: " + ex.ToString()); return null; } return (IDirectedProtocolMessage)this.Receive(fields, recipient); } return base.ReadFromRequestCore(request); }
/// <summary> /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="request">The request to search for an embedded message.</param> /// <returns> /// The deserialized message, if one is found. Null otherwise. /// </returns> protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) { var fields = new Dictionary<string, string>(); string accessToken; if ((accessToken = SearchForBearerAccessTokenInRequest(request)) != null) { fields["token_type"] = Protocol.AccessTokenTypes.Bearer; fields["access_token"] = accessToken; } if (fields.Count > 0) { MessageReceivingEndpoint recipient; try { recipient = request.GetRecipient(); } catch (ArgumentException ex) { Logger.OAuth.WarnFormat("Unrecognized HTTP request: " + ex.ToString()); return null; } // Deserialize the message using all the data we've collected. var message = (IDirectedProtocolMessage)this.Receive(fields, recipient); return message; } return null; }
/// <summary> /// Checks the incoming HTTP request for an access token request and prepares a response if the request message was found. /// </summary> /// <param name="httpRequestInfo">The HTTP request info.</param> /// <param name="response">The formulated response, or <c>null</c> if the request was not found..</param> /// <returns>A value indicating whether any access token request was found in the HTTP request.</returns> /// <remarks> /// This method assumes that the authorization server and the resource server are the same and that they share a single /// asymmetric key for signing and encrypting the access token. If this is not true, use the <see cref="ReadAccessTokenRequest"/> method instead. /// </remarks> public bool TryPrepareAccessTokenResponse(HttpRequestInfo httpRequestInfo, out IDirectResponseProtocolMessage response) { Contract.Requires<ArgumentNullException>(httpRequestInfo != null); Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<IDirectResponseProtocolMessage>(out response) != null)); var request = this.ReadAccessTokenRequest(httpRequestInfo); if (request != null) { response = this.PrepareAccessTokenResponse(request); return true; } response = null; return false; }
/// <summary> /// Extracts the recipient from an HttpRequestInfo. /// </summary> /// <param name="request">The request to get recipient information from.</param> /// <returns>The recipient.</returns> internal static MessageReceivingEndpoint GetRecipient(this HttpRequestInfo request) { return(new MessageReceivingEndpoint(request.Url, request.HttpMethod == "GET" ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest)); }
private static HttpRequestInfo ConvertToRequestInfo(HttpWebRequest request, Stream postEntity) { HttpRequestInfo info = new HttpRequestInfo { HttpMethod = request.Method, UrlBeforeRewriting = request.RequestUri, RawUrl = request.RequestUri.AbsolutePath + request.RequestUri.Query + request.RequestUri.Fragment, Headers = request.Headers, InputStream = postEntity, }; return info; }
/// <summary> /// Handles incoming HTTP requests. /// </summary> /// <param name="context">The HttpListener context.</param> private void RequestHandler(HttpListenerContext context) { Contract.Requires(context != null); Contract.Requires(context.Response.OutputStream != null); Stream outputStream = context.Response.OutputStream; Contract.Assume(outputStream != null); // CC static verification shortcoming. if (context.Request.Url.AbsolutePath == ProviderPath) { HttpRequestInfo requestInfo = new HttpRequestInfo(context.Request); IRequest providerRequest = this.provider.GetRequest(requestInfo); if (providerRequest == null) { App.Logger.Error("A request came in that did not carry an OpenID message."); context.Response.StatusCode = (int)HttpStatusCode.BadRequest; using (StreamWriter sw = new StreamWriter(outputStream)) { sw.WriteLine("<html><body>This is an OpenID Provider endpoint.</body></html>"); } return; } if (!providerRequest.IsResponseReady) { var authRequest = providerRequest as IAuthenticationRequest; if (authRequest.IsDirectedIdentity) { throw new NotImplementedException(); } authRequest.IsAuthenticated = new Uri(authRequest.ClaimedIdentifier).AbsolutePath == YesIdentity; } this.provider.PrepareResponse(providerRequest).Send(context.Response); } else if (context.Request.Url.AbsolutePath == YesIdentity || context.Request.Url.AbsolutePath == NoIdentity) { using (StreamWriter sw = new StreamWriter(outputStream)) { string providerEndpoint = string.Format("http://localhost:{0}{1}", context.Request.Url.Port, ProviderPath); string localId = null; // string.Format("http://localhost:{0}/user", context.Request.Url.Port); string html = GenerateHtmlDiscoveryDocument(providerEndpoint, localId); sw.WriteLine(html); } context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.OutputStream.Close(); } else { context.Response.StatusCode = (int)HttpStatusCode.NotFound; context.Response.OutputStream.Close(); } }
public ActionResult LogOnPostAssertion(string openid_openidAuthData) { IAuthenticationResponse Response; if (!string.IsNullOrEmpty(openid_openidAuthData)) { Uri Auth = new Uri(openid_openidAuthData); WebHeaderCollection Headers = new WebHeaderCollection(); foreach (string Key in Request.Headers) { Headers[Key] = Request.Headers[Key]; } HttpRequestInfo ResponseInfo = new HttpRequestInfo("GET", Auth, Auth.PathAndQuery, Headers, null); Response = AjaxParty.GetResponse(ResponseInfo); } else Response = AjaxParty.GetResponse(); if (Response != null) { switch(Response.Status) { case AuthenticationStatus.Authenticated: var Claim = Response.GetExtension<ClaimsResponse>(); Authorizer.DataModels.User UserInfo = null; using (IAuthorizerDataService DataService = DataServiceProvider.Instance.CreateAuthorizerDataService()) { DataService.RegisterUserLogIn(new DataModels.User() { EmailFull = Claim.Email, EmailUserName = Claim.MailAddress.User, OpenId = Response.ClaimedIdentifier }); UserInfo = DataService.RetrieveUserInfo(Response.ClaimedIdentifier); FormsAuthenticationTicket Authorization = AuthService.Service.CreateAuthTicket(Response.ClaimedIdentifier , UserInfo != null && UserInfo.Alias != null ? UserInfo.Alias.Name : !string.IsNullOrEmpty(Claim.FullName) ? Claim.FullName : !string.IsNullOrEmpty(Claim.MailAddress.User) ? Claim.MailAddress.User : Response.FriendlyIdentifierForDisplay); string EncryptedAuthorization = FormsAuthentication.Encrypt(Authorization); this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, EncryptedAuthorization)); } return RedirectToAction("Index", "Home", new { area = string.Empty }); case AuthenticationStatus.Canceled: ModelState.AddModelError("OpenID", "You need to complete the authorization process to be logged in"); break; case AuthenticationStatus.Failed: ModelState.AddModelError("OpenID", Response.Exception.Message); break; } } return View("LogOn"); }
/// <summary> /// Scans the incoming request for an authorization response message. /// </summary> /// <param name="actualRedirectUrl">The actual URL of the incoming HTTP request.</param> /// <param name="authorizationState">The authorization.</param> /// <returns>The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected.</returns> public IAuthorizationState ProcessUserAuthorization(Uri actualRedirectUrl, IAuthorizationState authorizationState = null) { Contract.Requires<ArgumentNullException>(actualRedirectUrl != null); if (authorizationState == null) { authorizationState = new AuthorizationState(); } var carrier = new HttpRequestInfo("GET", actualRedirectUrl, actualRedirectUrl.PathAndQuery, new System.Net.WebHeaderCollection(), null); IDirectedProtocolMessage response = this.Channel.ReadFromRequest(carrier); if (response == null) { return null; } EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess; EndUserAuthorizationSuccessAuthCodeResponse authCodeSuccess; EndUserAuthorizationFailedResponse failure; if ((accessTokenSuccess = response as EndUserAuthorizationSuccessAccessTokenResponse) != null) { UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess); } else if ((authCodeSuccess = response as EndUserAuthorizationSuccessAuthCodeResponse) != null) { this.UpdateAuthorizationWithResponse(authorizationState, authCodeSuccess); } else if ((failure = response as EndUserAuthorizationFailedResponse) != null) { authorizationState.Delete(); return null; } return authorizationState; }
/// <summary> /// Extracts the recipient from an HttpRequestInfo. /// </summary> /// <param name="request">The request to get recipient information from.</param> /// <returns>The recipient.</returns> /// <exception cref="ArgumentException">Thrown if the HTTP request is something we can't handle.</exception> internal static MessageReceivingEndpoint GetRecipient(this HttpRequestInfo request) { return(new MessageReceivingEndpoint(request.UrlBeforeRewriting, GetHttpDeliveryMethod(request.HttpMethod))); }
/// <summary> /// Prepares the return value for the GetRequest method in the event of an exception. /// </summary> /// <param name="ex">The exception that forms the basis of the error response. Must not be null.</param> /// <param name="httpRequestInfo">The incoming HTTP request. Must not be null.</param> /// <param name="incomingMessage">The incoming message. May be null in the case that it was malformed.</param> /// <returns> /// Either the <see cref="IRequest"/> to return to the host site or null to indicate no response could be reasonably created and that the caller should rethrow the exception. /// </returns> private IRequest GetErrorResponse(ProtocolException ex, HttpRequestInfo httpRequestInfo, IDirectedProtocolMessage incomingMessage) { Contract.Requires<ArgumentNullException>(ex != null); Contract.Requires<ArgumentNullException>(httpRequestInfo != null); Logger.OpenId.Error("An exception was generated while processing an incoming OpenID request.", ex); IErrorMessage errorMessage; // We must create the appropriate error message type (direct vs. indirect) // based on what we see in the request. string returnTo = httpRequestInfo.QueryString[Protocol.Default.openid.return_to]; if (returnTo != null) { // An indirect request message from the RP // We need to return an indirect response error message so the RP can consume it. // Consistent with OpenID 2.0 section 5.2.3. var indirectRequest = incomingMessage as SignedResponseRequest; if (indirectRequest != null) { errorMessage = new IndirectErrorResponse(indirectRequest); } else { errorMessage = new IndirectErrorResponse(Protocol.Default.Version, new Uri(returnTo)); } } else if (httpRequestInfo.HttpMethod == "POST") { // A direct request message from the RP // We need to return a direct response error message so the RP can consume it. // Consistent with OpenID 2.0 section 5.1.2.2. errorMessage = new DirectErrorResponse(Protocol.Default.Version, incomingMessage); } else { // This may be an indirect request from an RP that was so badly // formed that we cannot even return an error to the RP. // The best we can do is display an error to the user. // Returning null cues the caller to "throw;" return null; } errorMessage.ErrorMessage = ex.ToStringDescriptive(); // Allow host to log this error and issue a ticket #. // We tear off the field to a local var for thread safety. IErrorReporting hostErrorHandler = this.ErrorReporting; if (hostErrorHandler != null) { errorMessage.Contact = hostErrorHandler.Contact; errorMessage.Reference = hostErrorHandler.LogError(ex); } if (incomingMessage != null) { return new AutoResponsiveRequest(incomingMessage, errorMessage, this.SecuritySettings); } else { return new AutoResponsiveRequest(errorMessage, this.SecuritySettings); } }
/// <summary> /// Gets the incoming OpenID request if there is one, or null if none was detected. /// </summary> /// <param name="httpRequestInfo">The incoming HTTP request to extract the message from.</param> /// <returns> /// The request that the hosting Provider should process and then transmit the response for. /// Null if no valid OpenID request was detected in the given HTTP request. /// </returns> /// <remarks> /// Requests may be infrastructural to OpenID and allow auto-responses, or they may /// be authentication requests where the Provider site has to make decisions based /// on its own user database and policies. /// </remarks> /// <exception cref="ProtocolException">Thrown if the incoming message is recognized /// but deviates from the protocol specification irrecoverably.</exception> public IRequest GetRequest(HttpRequestInfo httpRequestInfo) { Contract.Requires<ArgumentNullException>(httpRequestInfo != null); IDirectedProtocolMessage incomingMessage = null; try { incomingMessage = this.Channel.ReadFromRequest(httpRequestInfo); if (incomingMessage == null) { // If the incoming request does not resemble an OpenID message at all, // it's probably a user who just navigated to this URL, and we should // just return null so the host can display a message to the user. if (httpRequestInfo.HttpMethod == "GET" && !httpRequestInfo.UrlBeforeRewriting.QueryStringContainPrefixedParameters(Protocol.Default.openid.Prefix)) { return null; } ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessageReceivedOfMany); } IRequest result = null; var checkIdMessage = incomingMessage as CheckIdRequest; if (checkIdMessage != null) { result = new AuthenticationRequest(this, checkIdMessage); } if (result == null) { var extensionOnlyRequest = incomingMessage as SignedResponseRequest; if (extensionOnlyRequest != null) { result = new AnonymousRequest(this, extensionOnlyRequest); } } if (result == null) { var checkAuthMessage = incomingMessage as CheckAuthenticationRequest; if (checkAuthMessage != null) { result = new AutoResponsiveRequest(incomingMessage, new CheckAuthenticationResponse(checkAuthMessage, this), this.SecuritySettings); } } if (result == null) { var associateMessage = incomingMessage as AssociateRequest; if (associateMessage != null) { result = new AutoResponsiveRequest(incomingMessage, associateMessage.CreateResponse(this.AssociationStore, this.SecuritySettings), this.SecuritySettings); } } if (result != null) { foreach (var behavior in this.Behaviors) { if (behavior.OnIncomingRequest(result)) { // This behavior matched this request. break; } } return result; } throw ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessageReceivedOfMany); } catch (ProtocolException ex) { IRequest errorResponse = this.GetErrorResponse(ex, httpRequestInfo, incomingMessage); if (errorResponse == null) { throw; } return errorResponse; } }
// GetAuthorization /// <summary> /// Gets the authorization object for the client-side flow /// </summary> /// <param name="client">The web server client used for authorization</param> /// <returns>An authorization state that can be used for API queries </returns> private IAuthorizationState GetAuthorization(WebServerClient client) { if (_authstate == null) { if (_refreshToken != null) { _authstate = CreateState(_refreshToken, false); } if (_accessToken != null) { _authstate = CreateState(_accessToken, true); } } // If this user is already authenticated, then just return the auth state. IAuthorizationState state = _authstate; if (state != null) { return state; } // Check if an authorization request already is in progress. HttpRequestInfo reqinfo = new HttpRequestInfo(HttpContext.Current.Request); //if (reqinfo) state = client.ProcessUserAuthorization(reqinfo); // Check to see if we have an access token and use that to generate the state. if (_accessToken != null) { state = CreateState(_accessToken, true); // Check to see if we have a refresh token and use that to get the auth state. } else if (_refreshToken != null) { state = CreateState(_refreshToken); bool worked = client.RefreshToken(state); if (state != null) { return state; } } if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken))) { // Store and return the credentials. HttpContext.Current.Session["AUTH_STATE"] = _authstate = state; _accessToken = state.AccessToken; _refreshToken = state.RefreshToken; return state; } // Otherwise do a new authorization request. string scope = "https://www.googleapis.com/auth/plus.login"; OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope }); response.Send(); // Will throw a ThreadAbortException to prevent sending another response. return null; }
public void ReadFromRequestAuthorizationScattered() { // Start by creating a standard POST HTTP request. var postedFields = new Dictionary<string, string> { { "age", "15" }, }; // Now add another field to the request URL var builder = new UriBuilder(MessagingTestBase.DefaultUrlForHttpRequestInfo); builder.Query = "Name=Andrew"; // Finally, add an Authorization header var authHeaderFields = new Dictionary<string, string> { { "Location", "http://hostb/pathB" }, { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) }, }; var headers = new NameValueCollection(); headers.Add(HttpRequestHeaders.Authorization, CreateAuthorizationHeader(authHeaderFields)); headers.Add(HttpRequestHeaders.ContentType, Channel.HttpFormUrlEncoded); var requestInfo = new HttpRequestInfo("POST", builder.Uri, form: postedFields.ToNameValueCollection(), headers: headers); IDirectedProtocolMessage requestMessage = this.channel.ReadFromRequest(requestInfo); Assert.IsNotNull(requestMessage); Assert.IsInstanceOf<TestMessage>(requestMessage); TestMessage testMessage = (TestMessage)requestMessage; Assert.AreEqual(15, testMessage.Age); Assert.AreEqual("Andrew", testMessage.Name); Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri); }
public ActionResult LogOnPostAssertion(string openid_openidAuthData) { IAuthenticationResponse response; if (!string.IsNullOrEmpty(openid_openidAuthData)) { var auth = new Uri(openid_openidAuthData); var headers = new WebHeaderCollection(); foreach (string header in Request.Headers) { headers[header] = Request.Headers[header]; } // Always say it's a GET since the payload is all in the URL, even the large ones. HttpRequestInfo clientResponseInfo = new HttpRequestInfo("GET", auth, auth.PathAndQuery, headers, null); response = RelyingParty.GetResponse(clientResponseInfo); } else { response = RelyingParty.GetResponse(); } if (response != null) { switch (response.Status) { case AuthenticationStatus.Authenticated: string alias = response.FriendlyIdentifierForDisplay; string email = response.ClaimedIdentifier; var sreg = response.GetExtension<ClaimsResponse>(); if (sreg != null && sreg.MailAddress != null) { alias = sreg.MailAddress.User; email = sreg.MailAddress.Address; } if (sreg != null && !string.IsNullOrEmpty(sreg.FullName)) { alias = sreg.FullName; } FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, //version email, // user name DateTime.Now, //creation DateTime.Now.AddMinutes(30), //Expiration false, //Persistent alias); string encTicket = FormsAuthentication.Encrypt(authTicket); this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); string returnUrl = Request.Form["returnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } case AuthenticationStatus.Canceled: ModelState.AddModelError("OpenID", "It looks like you canceled login at your OpenID Provider."); break; case AuthenticationStatus.Failed: ModelState.AddModelError("OpenID", response.Exception.Message); string errorsAddr = ConfigurationManager.AppSettings["ErrorsTo"]; if (!string.IsNullOrWhiteSpace(errorsAddr)) { MailService.SendMail(errorsAddr, "OpenID Auth Failure", response.Exception.ToStringDescriptive()); } break; } } // If we're to this point, login didn't complete successfully. // Show the LogOn view again to show the user any errors and // give another chance to complete login. return View("LogOn"); }
/// <summary> /// Processes an incoming request at the OpenID Provider endpoint. /// </summary> /// <param name="requestInfo">The request info.</param> /// <param name="response">The response.</param> private void ProcessRequest(HttpRequestInfo requestInfo, HttpListenerResponse response) { IRequest request = this.hostedProvider.Provider.GetRequest(requestInfo); if (request == null) { App.Logger.Error("A request came in that did not carry an OpenID message."); response.ContentType = "text/html"; response.StatusCode = (int)HttpStatusCode.BadRequest; using (StreamWriter sw = new StreamWriter(response.OutputStream)) { sw.WriteLine("<html><body>This is an OpenID Provider endpoint.</body></html>"); } return; } this.Dispatcher.Invoke((Action)delegate { if (!request.IsResponseReady) { var authRequest = request as IAuthenticationRequest; if (authRequest != null) { switch (checkidRequestList.SelectedIndex) { case 0: if (authRequest.IsDirectedIdentity) { authRequest.ClaimedIdentifier = new Uri(this.hostedProvider.UserIdentityPageBase, "directedidentity"); authRequest.LocalIdentifier = authRequest.ClaimedIdentifier; } authRequest.IsAuthenticated = true; break; case 1: authRequest.IsAuthenticated = false; break; case 2: IntPtr oldForegroundWindow = NativeMethods.GetForegroundWindow(); bool stoleFocus = NativeMethods.SetForegroundWindow(this); CheckIdWindow.ProcessAuthentication(this.hostedProvider, authRequest); if (stoleFocus) { NativeMethods.SetForegroundWindow(oldForegroundWindow); } break; } } } }); this.hostedProvider.Provider.PrepareResponse(request).Send(response); }
internal new IProtocolMessage ReadFromRequest(HttpRequestInfo request) { return base.ReadFromRequest(request); }
/// <summary> /// Reads the access token request. /// </summary> /// <param name="requestInfo">The request info.</param> /// <returns>The Client's request for an access token; or <c>null</c> if no such message was found in the request.</returns> public AccessTokenRequestBase ReadAccessTokenRequest(HttpRequestInfo requestInfo = null) { if (requestInfo == null) { requestInfo = this.Channel.GetRequestFromContext(); } AccessTokenRequestBase request; this.Channel.TryReadFromRequest(requestInfo, out request); return request; }
/// <summary> /// Gets the result of a user agent's visit to his OpenId provider in an /// authentication attempt. Null if no response is available. /// </summary> /// <param name="url">The incoming request URL.</param> /// <param name="form">The form data that may have been included in the case of a POST request.</param> /// <returns>The Provider's response to a previous authentication request, or null if no response is present.</returns> public AuthenticationResponseShim ProcessAuthentication(string url, string form) { HttpRequestInfo requestInfo = new HttpRequestInfo { UrlBeforeRewriting = new Uri(url) }; if (!string.IsNullOrEmpty(form)) { requestInfo.HttpMethod = "POST"; requestInfo.InputStream = new MemoryStream(Encoding.Unicode.GetBytes(form)); } var response = relyingParty.GetResponse(requestInfo); if (response != null) { return new AuthenticationResponseShim(response); } return null; }
/// <summary> /// Scans the incoming request for an authorization response message. /// </summary> /// <param name="actualRedirectUrl">The actual URL of the incoming HTTP request.</param> /// <param name="authorizationState">The authorization.</param> /// <returns>The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected.</returns> public IAuthorizationState ProcessUserAuthorization(Uri actualRedirectUrl, IAuthorizationState authorizationState = null) { Requires.NotNull(actualRedirectUrl, "actualRedirectUrl"); if (authorizationState == null) { authorizationState = new AuthorizationState(); } var carrier = new HttpRequestInfo("GET", actualRedirectUrl); IDirectedProtocolMessage response = this.Channel.ReadFromRequest(carrier); if (response == null) { return null; } return this.ProcessUserAuthorization(authorizationState, response); }
public IAuthenticationResponse GetResponse(HttpRequestInfo request) { return relyingParty.GetResponse(request); }
/// <summary> /// Gets the result of a user agent's visit to his OpenId provider in an /// authentication attempt. Null if no response is available. /// </summary> /// <param name="url">The incoming request URL.</param> /// <param name="form">The form data that may have been included in the case of a POST request.</param> /// <returns>The Provider's response to a previous authentication request, or null if no response is present.</returns> public AuthenticationResponseShim ProcessAuthentication(string url, string form) { string method = "GET"; NameValueCollection formMap = null; if (!string.IsNullOrEmpty(form)) { method = "POST"; formMap = HttpUtility.ParseQueryString(form); } HttpRequestBase requestInfo = new HttpRequestInfo(method, new Uri(url), form: formMap); var response = relyingParty.GetResponse(requestInfo); if (response != null) { return new AuthenticationResponseShim(response); } return null; }