PrepareRequestUserAuthorization() public méthode

Prepares a request for user authorization from an authorization server.
public PrepareRequestUserAuthorization ( IAuthorizationState authorization ) : DotNetOpenAuth.Messaging.OutgoingWebResponse
authorization IAuthorizationState The authorization state to associate with this particular request.
Résultat DotNetOpenAuth.Messaging.OutgoingWebResponse
        // GET: Account
        public ActionResult Login(string returnUrl)
        {
            _webServerClient = OAuthConfiguration.InitializeWebServerClient();

            var result = _webServerClient.ProcessUserAuthorization(Request);
            if (result == null)
            {

                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization();

                //Clear returnUrl

                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else
            {
                var username = OAuthConfiguration.GetMe(result.AccessToken);
                var user = UserManager.FindByName(username);
                if (user != null)
                {
                    SignInManager.SignIn(user, false, false);
                }
                else
                {
                    var newuser = new ApplicationUser { UserName = username, Email = username };
                    UserManager.Create(newuser);
                    SignInManager.SignIn(newuser, false, false);
                }

                return RedirectToLocal(returnUrl);
            }

            return View();
        }
        public ActionResult AuthorizationCodeGrant(AuthorizationCodeGrantViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var client = new WebServerClient(_authServerDescription, viewModel.ClientId, viewModel.ClientSecret);

                var request = client.PrepareRequestUserAuthorization(new[] { viewModel.Scope });

                request.Send();
            }

            return View(viewModel);
        }
Exemple #3
0
        // for getting initial access and renewal tokens via OAuth handshake
        IAuthorizationState GetGoogleTokens(WebServerClient client)
        {
            // check if authorization request already is in progress
            IAuthorizationState state = client.ProcessUserAuthorization(new HttpRequestInfo(System.Web.HttpContext.Current.Request));
            if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
            {   // store refresh token
                string username = System.Web.HttpContext.Current.User.Identity.Name;
                UserStorageContext storage = Storage.NewUserContext;
                User user = storage.Users.Include("UserCredentials").Single<User>(u => u.Name == username);
                user.AddCredential(UserCredential.GoogleConsent, state.AccessToken, state.AccessTokenExpirationUtc, state.RefreshToken);
                storage.SaveChanges();
                return state;
            }

            // otherwise make a new authorization request
            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(GoogleClient.Scopes);
            response.Headers["Location"] += "&access_type=offline&approval_prompt=force";
            response.Send();    // will throw a ThreadAbortException to prevent sending another response
            return null;
        }
Exemple #4
0
        /// <summary>The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally. Overridable so you can provide your own Auth implementation.</summary>
        ///
        /// <param name="authService">The authentication service.</param>
        /// <param name="session">    The session.</param>
        /// <param name="request">    The request.</param>
        ///
        /// <returns>An object.</returns>
        public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
        {
            var tokens = this.Init(authService, ref session, request);

            var authServer = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri(this.AuthorizeUrl), TokenEndpoint = new Uri(this.AccessTokenUrl) };
            var authClient = new WebServerClient(authServer, this.ConsumerKey) {
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.ConsumerSecret),
            };

            var authState = authClient.ProcessUserAuthorization();
            if (authState == null)
            {
                try
                {
                    var authReq = authClient.PrepareRequestUserAuthorization(this.Scopes, new Uri(this.CallbackUrl));
                    var authContentType = authReq.Headers[HttpHeaders.ContentType];
                    var httpResult = new HttpResult(authReq.ResponseStream, authContentType) { StatusCode = authReq.Status, StatusDescription = "Moved Temporarily" };
                    foreach (string header in authReq.Headers)
                    {
                        httpResult.Headers[header] = authReq.Headers[header];
                    }

                    foreach (string name in authReq.Cookies)
                    {
                        var cookie = authReq.Cookies[name];

                        if (cookie != null)
                        {
                            httpResult.SetSessionCookie(name, cookie.Value, cookie.Path);
                        }
                    }

                    authService.SaveSession(session, this.SessionExpiry);
                    return httpResult;
                }
                catch (ProtocolException ex)
                {
                    Log.Error("Failed to login to {0}".Fmt(this.Provider), ex);
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
                }
            }

            var accessToken = authState.AccessToken;
            if (accessToken != null)
            {
                try
                {
                    tokens.AccessToken = accessToken;
                    tokens.RefreshToken = authState.RefreshToken;
                    tokens.RefreshTokenExpiry = authState.AccessTokenExpirationUtc;
                    session.IsAuthenticated = true;
                    var authInfo = this.CreateAuthInfo(accessToken);
                    this.OnAuthenticated(authService, session, tokens, authInfo);
                    return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"));
                }
                catch (WebException we)
                {
                    var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "AccessTokenFailed"));
                    }
                }
            }

            return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "RequestTokenFailed"));
        }
        // 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;
        }
Exemple #6
0
        /// <summary>
        /// Gets the authorization object for the client-side flow.
        /// </summary>
        /// <param name="client">The client used for authorization.
        /// </param>
        /// <returns>An authorization state that can be used for API queries.
        /// </returns>
        protected IAuthorizationState GetAuthorization(WebServerClient client)
        {
            // If we don't yet have user, use the client to perform
            // authorization.
            if (_authState != null)
            {
                HttpRequestInfo reqinfo =
                    new HttpRequestInfo(HttpContext.Current.Request);
                client.ProcessUserAuthorization(reqinfo);
            }

            // Check for a cached session state.
            if (_authState == null)
            {
                _authState = (IAuthorizationState)HttpContext.Current.
                        Session["AUTH_STATE"];
            }

            // Check if we need to refresh the authorization state and refresh
            // it if necessary.
            if (_authState != null)
            {
                if (_authState.RefreshToken.IsNotNullOrEmpty() && (_authState.AccessToken == null ||
                    DateTime.UtcNow > _authState.AccessTokenExpirationUtc))
                {
                    client.RefreshToken(_authState);
                }
                return _authState;
            }

            // If we fall through to here, perform an authorization request.
            OutgoingWebResponse response =
                client.PrepareRequestUserAuthorization();

            response.Send();
            // Note: response.send will throw a ThreadAbortException to
            // prevent sending another response.
            return null;
        }
        private IAuthorizationState GetAuthorization(WebServerClient client)
        {
            // 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.
            state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
            if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
            {
                // Store and return the credentials.
                HttpContext.Current.Session["AUTH_STATE"] = _state = state;
                return state;
            }

            // Otherwise do a new authorization request.
            string scope = "https://www.googleapis.com/auth/plus.me";
            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope });
            response.Send(); // Will throw a ThreadAbortException to prevent sending another response.
            return null;
        }
    private IAuthorizationState GetAuthorization(WebServerClient myWebServerClient)
    {
        var state = HttpContext.Current.Session["GA_AUTH_STATE"] as IAuthorizationState;

        if (state != null)
        {
            return state;
        }

        state = myWebServerClient.ProcessUserAuthorization(
            new HttpRequestInfo(HttpContext.Current.Request)
        );

        if (state != null && (state.AccessToken.IsNotEmpty() || state.RefreshToken.IsNotEmpty()))
        {
            HttpContext.Current.Session["GA_AUTH_STATE"] = state;
            return state;
        }

        var scopes = new[] {
            "https://www.google.com/analytics/feeds/",
            "https://www.googleapis.com/auth/analytics.readonly" };

        myWebServerClient.PrepareRequestUserAuthorization(scopes).Send();

        return null;
    }