Esempio n. 1
0
        public async Task <ActionResult> About()
        {
            ViewBag.Message = "Your app description page.";

            var accessToken = Session["access_token"] as string;

            if (String.IsNullOrEmpty(accessToken))
            {
                // we have no token, bounce the browser over to the server's /Authorize endpoint
                return(new UserAuthorizationResult(_authServerClient.PrepareRequestUserAuthorization(_authorizationRequest)));
            }

            // we do have an access_token, so add it as bearer auth header to outgoing requests
            var httpClient = new HttpClient(
                _authServerClient.CreateAuthorizingHandler(accessToken)
                );

            // call the server for data
            var me = await httpClient.GetAsync("http://localhost:9001/Me");

            // show it on the view
            ViewBag.Message = await me.Content.ReadAsStringAsync();

            return(View());
        }
Esempio n. 2
0
        protected void AuthorizeButton_Click(object sender, EventArgs e)
        {
            var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "bio", "notes" });

            userAuthorization.Send(Context);
            Response.End();
        }
Esempio n. 3
0
        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 = TasksService.Scopes.TasksReadonly.GetStringValue();
            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope }, "");

            response.Send(); // Will throw a ThreadAbortException to prevent sending another response.
            return(null);
        }
        public ActionResult Index()
        {
            ViewBag.AccessToken  = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action       = "";
            ViewBag.ApiResponse  = "";

            InitializeWebServerClient();
            var accessToken = Request.Form["AccessToken"];

            if (string.IsNullOrEmpty(accessToken))
            {
                var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
                if (authorizationState != null)
                {
                    ViewBag.AccessToken  = authorizationState.AccessToken;
                    ViewBag.RefreshToken = authorizationState.RefreshToken;
                    ViewBag.Action       = Request.Path;
                }
            }

            if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
            {
                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "bio", "notes" });
                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
            {
                var state = new AuthorizationState
                {
                    AccessToken  = Request.Form["AccessToken"],
                    RefreshToken = Request.Form["RefreshToken"]
                };
                if (_webServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken  = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
            {
                var resourceServerUri = new Uri(Paths.ResourceServerBaseAddress);
                var client            = new HttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));
                var body = client.GetStringAsync(new Uri(resourceServerUri, Paths.MePath)).Result;
                ViewBag.ApiResponse = body;
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApiNetCore")))
            {
                var resourceServerUri = new Uri(Paths.ResourceServerNetCoreBaseAddress);
                var client            = new HttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));
                var body = client.GetStringAsync(new Uri(resourceServerUri, Paths.MeNetCorePath)).Result;
                ViewBag.ApiResponse = body;
            }



            return(View());
        }
Esempio n. 5
0
        public async Task <ActionResult> Index()
        {
            ViewBag.AccessToken  = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action       = "";
            ViewBag.ApiResponse  = "";

            InitializeWebServerClient();
            var accessToken = Request.Form["AccessToken"];

            if (string.IsNullOrEmpty(accessToken))
            {
                var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
                if (authorizationState != null)
                {
                    ViewBag.AccessToken  = authorizationState.AccessToken;
                    ViewBag.RefreshToken = authorizationState.RefreshToken;
                    ViewBag.Action       = Request.Path;
                }
            }

            if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
            {
                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "bio", "notes" });
                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
            {
                var state = new AuthorizationState
                {
                    AccessToken  = Request.Form["AccessToken"],
                    RefreshToken = Request.Form["RefreshToken"]
                };
                if (_webServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken  = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
            {
                Raml.RamlApi api = new Raml.RamlApi("http://localhost:11625");
                api.OAuthAccessToken = accessToken;

                //api.AddDefaultRequestHeader("Authorization", "Bearer " + accessToken);

                var response = await api.ApiMe.Get();

                var body = await response.RawContent.ReadAsStringAsync();

                ViewBag.ApiResponse = body;
            }

            return(View());
        }
Esempio n. 6
0
        // GET: AuthCode
        public ActionResult Index()
        {
            ViewBag.AccessToken  = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action       = "";
            ViewBag.ApiResponse  = "";

            var authServer = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = new Uri(Paths.AuthorizationServerBaseAddress + Paths.AuthorizePath),
                TokenEndpoint         = new Uri(Paths.AuthorizationServerBaseAddress + Paths.TokenPath)
            };
            var webServerClient = new WebServerClient(authServer, Clients.Client1.Id, Clients.Client1.Secret);

            var accessToken = Request.Form["AccessToken"];

            if (string.IsNullOrEmpty(accessToken))
            {
                var authorizationState = webServerClient.ProcessUserAuthorization(Request);
                ViewBag.Action = Request.Path;
                if (authorizationState != null)
                {
                    ViewBag.AccessToken  = authorizationState.AccessToken;
                    ViewBag.RefreshToken = authorizationState.RefreshToken;
                }
            }

            if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
            {
                var userAuthorization = webServerClient.PrepareRequestUserAuthorization(new[] { "bio", "notes" });
                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
            {
                var state = new AuthorizationState
                {
                    AccessToken  = Request.Form["AccessToken"],
                    RefreshToken = Request.Form["RefreshToken"]
                };
                if (webServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken  = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
            {
                var client = new HttpClient(webServerClient.CreateAuthorizingHandler(accessToken));
                var body   = client.GetStringAsync(new Uri(Paths.ResourceUserApiPath)).Result;
                ViewBag.ApiResponse = body;
            }
            return(View());
        }
        private ActionResult InitAuthentication()
        {
            AuthorizationState state = new AuthorizationState();
            string             uri   = Request.Url.AbsoluteUri;

            uri            = RemoveQueryStringFromUri(uri);
            state.Callback = new Uri(uri);

            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(state);

            return(response.AsActionResultMvc5());
        }
Esempio n. 8
0
 /// <summary>
 /// webBrowser1_Navigated
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
 {
     client.ClientIdentifier = "";
     client.PrepareRequestUserAuthorization();
     //{
     //    DialogResult = DialogResult.OK;
     //    Close();
     //}
     //else
     //{
     //    MessageBox.Show("获取acesskey出错");
     //}
 }
Esempio n. 9
0
        public async Task <ActionResult> Index(string acao, string accessToken, string refreshToken)
        {
            ViewBag.AccessToken  = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action       = "";
            ViewBag.ApiResponse  = "";

            if (string.IsNullOrEmpty(acao))
            {
                if (string.IsNullOrEmpty(accessToken))
                {
                    var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
                    if (authorizationState != null)
                    {
                        ViewBag.AccessToken  = authorizationState.AccessToken;
                        ViewBag.RefreshToken = authorizationState.RefreshToken;
                        ViewBag.Action       = Request.Path;
                    }
                }
            }
            else if (acao == "Authorize")
            {
                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "notas", "administracao" });
                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else if (acao == "Refresh")
            {
                var state = new AuthorizationState
                {
                    AccessToken  = accessToken,
                    RefreshToken = refreshToken
                };
                if (_webServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken  = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }
            else if (acao == "Acessar API protegida")
            {
                var resourceServerUri = new Uri(Paths.ResourceServerBaseAddress);
                var client            = new HttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));
                var body = await client.GetStringAsync(new Uri(resourceServerUri, Paths.AlunosPath));

                ViewBag.ApiResponse = body;
            }


            return(View());
        }
        /// <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 = null;
                if (_httpReqMethod != null && _reqUri != null && _rawUrl != null &&
                    _headers != null && _inputStream != null)
                {
                    reqinfo = new HttpRequestInfo(_httpReqMethod, _reqUri, _rawUrl,
                                                  (System.Net.WebHeaderCollection)_headers, _inputStream);
                }

                if (reqinfo == null)
                {
                    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);
        }
Esempio n. 11
0
        /// <summary>
        /// Initializes the request for authorization
        /// </summary>
        /// <returns></returns>
        private ActionResult InitAuth()
        {
            var state = new AuthorizationState();

            var uri = Request.Url.AbsoluteUri;

            uri            = RemoveQueryStringFromUri(uri);
            state.Callback = new Uri(uri);

            //In the scope, please add only a single element, which is the Transaction amount, else the request will be rejected.
            state.Scope.Add("15");

            var r = client.PrepareRequestUserAuthorization(state);

            return(r.AsActionResult());
        }
Esempio n. 12
0
 public ActionResult Index(bool flag)
 {
     if (Authorization == null)
     {
         return(_client.PrepareRequestUserAuthorization().AsActionResult());
     }
     else
     {
         var request = new HttpRequestMessage(new HttpMethod("GET"), "http://localhost:57036/api/values");
         using (var httpClient = new HttpClient(_client.CreateAuthorizingHandler(Authorization)))
         {
             using (var resourceResponse = httpClient.SendAsync(request))
             {
                 ViewBag.Result = resourceResponse.Result.Content.ReadAsStringAsync().Result;
             }
         }
         return(View(Authorization));
     }
 }
Esempio n. 13
0
        public ActionResult Authorize()
        {
            var authorizationServerUri = new Uri("http://localhost:57585");
            var authorizationServer    = new AuthorizationServerDescription
            {
                AuthorizationEndpoint = new Uri(authorizationServerUri, "/OAuth/Authorize"),
                TokenEndpoint         = new Uri(authorizationServerUri, "/OAuth/Token")
            };
            var webServerClient = new WebServerClient(authorizationServer, this._clientId);
            var scope           = new List <string>()
            {
                "GeneralUser", "Admin"
            };
            var client = webServerClient.PrepareRequestUserAuthorization(scope, new Uri("http://localhost:13082/OAuth/Redirect"));

            client.Send(HttpContext);
            Response.End();
            return(this.View("Index"));
        }
Esempio n. 14
0
        public ActionResult Index()
        {
            ViewBag.AccessToken  = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action       = "";
            ViewBag.ApiResponse  = "";

            InitializeWebServerClient();
            var accessToken = Request.Form["AccessToken"];

            if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
            {
                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "Email", "Name" }, new Uri(ConfigurationManager.AppSettings["ClientRedirectUrl"]));
                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
            {
                var state = new AuthorizationState
                {
                    AccessToken  = Request.Form["AccessToken"],
                    RefreshToken = Request.Form["RefreshToken"]
                };

                if (_webServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken  = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
            {
                var resourceServerUri = new Uri(ConfigurationManager.AppSettings["ResourceServerBaseAddress"]);
                var client            = new HttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));
                var body = client.GetStringAsync(new Uri(resourceServerUri, ConfigurationManager.AppSettings["MePath"])).Result;
                ViewBag.ApiResponse = body;
            }

            return(View());
        }
Esempio n. 15
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);
        }
Esempio n. 16
0
        // GetAuthorization
        /// <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>
        private 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.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(_authState.Scope);

            response.Send();
            // Note: response.send will throw a ThreadAbortException to
            // prevent sending another response.
            return(null);
        }
Esempio n. 17
0
        // 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());
        }
Esempio n. 18
0
        //
        // GET: /Show/

        public async Task <ActionResult> Me()
        {
            var accessToken = Session["access_token"] as string;

            if (String.IsNullOrEmpty(accessToken))
            {
                // we have no token, bounce the browser over to the server's /Authorize endpoint, and come back to /Return
                var response = _authServerClient.PrepareRequestUserAuthorization(
                    returnTo: new Uri("http://localhost:9002/Show/Return"));

                return(new UserAuthorizationResult(response));
            }

            // we do have an access_token, so add it as bearer auth header to outgoing requests
            var httpClient = new HttpClient(_authServerClient.CreateAuthorizingHandler(accessToken));

            // call the server for data
            var me = await httpClient.GetAsync("http://localhost:9001/Me");

            // show it on the view
            ViewBag.Me = await me.Content.ReadAsStringAsync();

            return(View());
        }
Esempio n. 19
0
        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")));
        }
Esempio n. 20
0
        //
        // GET: /Manage/Index
        //public async Task<ActionResult> Index(ManageMessageId? message)
        //{
        //    ViewBag.StatusMessage =
        //        message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
        //        : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
        //        : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
        //        : message == ManageMessageId.Error ? "An error has occurred."
        //        : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
        //        : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
        //        : "";

        //    var userId = User.Identity.GetUserId();
        //    var model = new IndexViewModel
        //    {
        //        HasPassword = HasPassword(),
        //        PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
        //        TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
        //        Logins = await UserManager.GetLoginsAsync(userId),
        //        BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
        //    };
        //    return View(model);
        //}


        public async Task <ActionResult> Index(ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
            : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
            : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
            : message == ManageMessageId.Error ? "An error has occurred."
            : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
            : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
            : "";

            var userId = User.Identity.GetUserId();
            var model  = new IndexViewModel
            {
                HasPassword       = HasPassword(),
                PhoneNumber       = await UserManager.GetPhoneNumberAsync(userId),
                TwoFactor         = await UserManager.GetTwoFactorEnabledAsync(userId),
                Logins            = await UserManager.GetLoginsAsync(userId),
                BrowserRemembered = await AuthenticationManager.
                                    TwoFactorBrowserRememberedAsync(userId)
            };

            ViewBag.AccessToken  = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action       = "";
            ViewBag.ApiResponse  = "";

            InitializeWebServerClient();
            var accessToken = Request.Form["AccessToken"];

            if (string.IsNullOrEmpty(accessToken))
            {
                var authorizationState = _webServerClient.ProcessUserAuthorization(
                    Request);
                if (authorizationState != null)
                {
                    ViewBag.AccessToken  = authorizationState.AccessToken;
                    ViewBag.RefreshToken = authorizationState.RefreshToken;
                    ViewBag.Action       = Request.Path;
                }
            }

            if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
            {
                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(
                    new[] { "bio", "notes" });
                userAuthorization.Send(HttpContext);
                Response.End();
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
            {
                var state = new AuthorizationState
                {
                    AccessToken  = Request.Form["AccessToken"],
                    RefreshToken = Request.Form["RefreshToken"]
                };
                if (_webServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken  = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
            {
                var resourceServerUri = new Uri(Paths.ResourceServerBaseAddress);
                var client            = new HttpClient(_webServerClient.CreateAuthorizingHandler
                                                           (accessToken));
                var body = client.GetStringAsync(new Uri(resourceServerUri,
                                                         Paths.MePath)).Result;
                ViewBag.ApiResponse = body;
            }

            return(View(model));
        }
Esempio n. 21
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = this.Init(authService, ref session, request);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request?.AccessToken != null)
            {
                if (VerifyAccessToken == null)
                {
                    throw new NotImplementedException($"VerifyAccessToken is not implemented by {Provider}");
                }

                if (!VerifyAccessToken(request.AccessToken))
                {
                    return(HttpError.Unauthorized($"AccessToken is not for the configured {Provider} App"));
                }

                var failedResult = AuthenticateWithAccessToken(authService, session, tokens, request.AccessToken);
                var isHtml       = authService.Request.IsHtml();
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            var authServer = new AuthorizationServerDescription {
                AuthorizationEndpoint = new Uri(this.AuthorizeUrl), TokenEndpoint = new Uri(this.AccessTokenUrl)
            };

            AuthServerFilter?.Invoke(authServer);

            var authClient = new WebServerClient(authServer, this.ConsumerKey)
            {
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(this.ConsumerSecret),
            };

            AuthClientFilter?.Invoke(authClient);

            var authState = ProcessUserAuthorization(authClient, authServer, authService);

            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.Cookies.Add(cookie.ToCookie());
                        }
                    }

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

            var accessToken = authState.AccessToken;

            if (accessToken != null)
            {
                tokens.RefreshToken       = authState.RefreshToken;
                tokens.RefreshTokenExpiry = authState.AccessTokenExpirationUtc;
            }

            if (accessToken != null)
            {
                try
                {
                    return(AuthenticateWithAccessToken(authService, session, tokens, accessToken)
                           ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1"))));
                }
                catch (WebException we)
                {
                    var statusCode = ((HttpWebResponse)we.Response).StatusCode;
                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
                    }
                }
            }

            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "RequestTokenFailed"))));
        }
Esempio n. 22
0
        public void SendAuthRequest(HttpContext context, Uri returnTo = null)
        {
            var userAuth = _webServerClient.PrepareRequestUserAuthorization(returnTo: returnTo);

            userAuth.Send(context);
        }
        public override async Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default)
        {
            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),
            };

            /*
             * Because we are exceeding the default max depth (2) we need to increase the quota.
             * http://stackoverflow.com/questions/14691358/how-do-i-set-jsonreaderquotas-property-on-the-dotnetopenauth-oauth2clientchan
             * */
            authClient.JsonReaderQuotas.MaxDepth = 10;

            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);
                        }
                    }

                    await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait();

                    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);
                    await this.OnAuthenticatedAsync(authService, session, tokens, authInfo, token).ConfigAwait();

                    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")));
        }
        public ActionResult Index()
        {
            ViewBag.AccessToken  = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action       = "";
            ViewBag.ApiResponse  = "";

            InitializeWebServerClient();
            var accessToken = Request.Form["AccessToken"];

            if (string.IsNullOrEmpty(accessToken))
            {
                //Get AccessToken&Refersh Token after getting Authorization Code
                var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
                if (authorizationState != null)
                {
                    ViewBag.AccessToken  = authorizationState.AccessToken;
                    ViewBag.RefreshToken = authorizationState.RefreshToken;
                    ViewBag.Action       = Request.Path;
                }
            }
            //Get Authorization Code
            if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
            {
                var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "read" });
                userAuthorization.Send(HttpContext);
                Response.End();
            }
            //Refresh Token
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
            {
                var state = new AuthorizationState
                {
                    AccessToken  = Request.Form["AccessToken"],
                    RefreshToken = Request.Form["RefreshToken"]
                };
                if (_webServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken  = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }
            //Call Sophtron API
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
            {
                var resourceServerUri = new Uri(ServerInfo.ResourceServerBaseAddress);

                //try healthcheck, results as  "this is online."
                var client   = new HttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));
                var response = client.GetAsync(new Uri(resourceServerUri, "/api/Institution/HealthCheckAuth")).Result;
                var contents = response.Content.ReadAsStringAsync();
                ViewBag.ApiResponse = contents.Result;

                //try get userinstitution list results
                StringContent content = new StringContent("{\"UserID\": \"17AD9654-2915-4F5F-A311-A306B901931A\"}", System.Text.Encoding.UTF8, "application/json");
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                response = client.PostAsync(new Uri(resourceServerUri, "/api/UserInstitution/GetUserInstitutionsByUser"), content).Result;

                contents             = response.Content.ReadAsStringAsync();
                ViewBag.ApiResponse += contents.Result;
            }

            return(View());
        }
Esempio n. 25
0
        // GET: Home
        public ActionResult Index()
        {
            ViewBag.AccessToken  = Request.Form["AccessToken"] ?? "";
            ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
            ViewBag.Action       = "";
            ViewBag.ApiResponse  = "";

            InitializeWebServerClient();
            var accessToken       = Request.Form["AccessToken"];
            var resourceServerUri = new Uri(AppSettingValue("ResourceServerUrl"));

            if (string.IsNullOrEmpty(accessToken))
            {
                var authState = mWebServerClient.ProcessUserAuthorization(Request);
                if (authState != null)
                {
                    ViewBag.AccessToken  = authState.AccessToken;
                    ViewBag.RefreshToken = authState.RefreshToken;
                    ViewBag.Action       = Request.Path;
                }
            }

            if (!String.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
            {
                var userAuth = mWebServerClient.PrepareRequestUserAuthorization(new[] { "profile", "family" });
                userAuth.Send(HttpContext);
                Response.End();
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
            {
                var state = new AuthorizationState
                {
                    AccessToken  = Request.Form["AccessToken"],
                    RefreshToken = Request.Form["RefreshToken"]
                };
                if (mWebServerClient.RefreshAuthorization(state))
                {
                    ViewBag.AccessToken  = state.AccessToken;
                    ViewBag.RefreshToken = state.RefreshToken;
                }
            }



            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
            {
                try
                {
                    var meEndpoint = string.Format("{0}api/oauth/profile", AppSettingValue("ResourceServerBaseEndpoint"));
                    var client     = new HttpClient(mWebServerClient.CreateAuthorizingHandler(accessToken));
                    var body       = client.GetStringAsync(new Uri(resourceServerUri, meEndpoint)).Result;
                    ViewBag.ApiResponse = body;
                }
                catch (Exception ex)
                {
                    ViewBag.ApiResponse = new Uri(resourceServerUri, string.Format("{0}api/me", AppSettingValue("ResourceServerBaseEndpoint"))).ToString();
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApiFamily")))
            {
                var familyEndpoint = string.Format("{0}api/oauth/family", AppSettingValue("ResourceServerBaseEndpoint"));
                var client         = new HttpClient(mWebServerClient.CreateAuthorizingHandler(accessToken));
                var body           = client.GetStringAsync(new Uri(resourceServerUri, familyEndpoint)).Result;
                ViewBag.ApiResponse = body;
            }
            else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApiPerson")))
            {
                var familyEndpoint = string.Format("{0}api/people/1", AppSettingValue("ResourceServerBaseEndpoint"));
                var client         = new HttpClient(mWebServerClient.CreateAuthorizingHandler(accessToken));
                var body           = client.GetStringAsync(new Uri(resourceServerUri, familyEndpoint)).Result;
                ViewBag.ApiResponse = body;
            }

            return(View());
        }