Esempio n. 1
0
        private async Task <LinkedInExternalAccessToken> VerifyExternalAccessToken(string accessToken, string logFile, bool writeLog)
        {
            _linkedInAuthClient = this._authenticationRepository.GetDbContext().LinkedInAuthClients.Where(_linked => _linked.Active).SingleOrDefault();
            LinkedInExternalAccessToken parsedToken = null;
            string file = logFile;

            try
            {
                string verifyTokenEndPoint = "";
                verifyTokenEndPoint = "https://www.linkedin.com/oauth/v2/accessToken";
                string redirectURl = string.Format("{0}/LinkedInMVC/AuthCallBack", System.Configuration.ConfigurationManager.AppSettings["WebSiteUrl"].ToString());

                HttpResponseMessage response;
                Uri uri = new Uri(verifyTokenEndPoint);

                if (writeLog)
                {
                    System.IO.File.AppendAllText(file, Environment.NewLine + System.DateTime.Now.ToString() + "| start verify linked access token...");
                }

                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Host = "www.linkedin.com";
                    var content = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("grant_type", "authorization_code"),
                        new KeyValuePair <string, string>("code", accessToken),
                        new KeyValuePair <string, string>("redirect_uri", redirectURl),
                        new KeyValuePair <string, string>("client_id", _linkedInAuthClient.ClientId),
                        new KeyValuePair <string, string>("client_secret", _linkedInAuthClient.ClientSecret),
                    });

                    content.Headers.ContentType.MediaType = "application/x-www-form-urlencoded";
                    response = await httpClient.PostAsync(uri, content);
                }

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    dynamic jObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(content);
                    parsedToken = new LinkedInExternalAccessToken();
                    parsedToken.access_token = jObj["access_token"];
                    parsedToken.expiry_in    = jObj["expires_in"];
                }
            }
            catch (Exception ex)
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(file, Environment.NewLine + System.DateTime.Now.ToString() + "| Exception during verify linked access token " + ex.ToString());
                }
            }
            return(parsedToken);
        }
Esempio n. 2
0
        // GET: LinkedInMVC
        public ActionResult Index()
        {
            _linkedInAuthClient = this._authenticationRepository.GetDbContext().LinkedInAuthClients.Where(_linked => _linked.Active).SingleOrDefault();
            string rootPath = "";
            bool   writeLog = false;

            if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null)
            {
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false)
                {
                    rootPath = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString();
                    writeLog = true;
                }
            }

            string file = rootPath + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "LNK_Index.txt";

            if (_linkedInAuthClient != null)
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(file, "redirecting to linked login...");
                }

                string state = System.Guid.NewGuid().ToString().Replace("-", "");
                Session["LinkedInState"] = state;
                string clientId    = _linkedInAuthClient.ClientId;
                string callBackUrl = string.Format("{0}/LinkedInMVC/AuthCallBack", System.Configuration.ConfigurationManager.AppSettings["WebSiteUrl"].ToString());
                string scope       = "r_basicprofile%20r_emailaddress";
                string redirectUri = string.Format("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={0}&redirect_uri={1}&state={2}&scope={3}", clientId, callBackUrl, state, scope);
                return(Redirect(redirectUri));
            }
            else
            {
                ViewBag.Result       = false;
                ViewBag.ErrorMessage = "LinkedIn application not configured.";
                return(View("AuthCallBack"));
            }
        }
Esempio n. 3
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);

            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
                Provider             = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            KaribouAlpha.DAL.KaribouAlphaContext db = new DAL.KaribouAlphaContext();

            LinkedInAuthClient linkedInAuthClient = db.LinkedInAuthClients.SingleOrDefault(_linked => _linked.Active);

            if (linkedInAuthClient != null)
            {
                ILinkedInAuthenticationProvider providerLnk = new KaribouAlpha.Authentication.LinkedInAuthenticationProvider();
                LinkedInAuthenticationOptions = new LinkedInAuthenticationOptions()
                {
                    ClientId     = linkedInAuthClient.ClientId,
                    ClientSecret = linkedInAuthClient.ClientSecret,
                    Provider     = providerLnk,
                    CallbackPath = new PathString("/AuthCallBack."),
                    Scope        = { "r_basicprofile", "r_emailaddress" },
                    //BackchannelHttpHandler = new LinkedInBackChannelHandler()
                };
            }
            //http://www.c-sharpcorner.com/article/implementing-oauth2-0-authorization-for-google-in-asp-net/
            //https://developers.google.com/actions/identity/oauth2-code-flow

            GoogleAuthClient googleClient = db.GoogleAuthClients.SingleOrDefault(_google => _google.Active);

            if (googleClient != null)
            {
                GoogleAuthProvider gProvider = new GoogleAuthProvider();
                googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
                {
                    ClientId     = googleClient.ClientId,
                    ClientSecret = googleClient.ClientSecret,
                    Provider     = gProvider
                };
            }

            KaribouAlpha.Models.FaceBookClient clientFb = db.FaceBookClients.SingleOrDefault(_fb => _fb.Active);
            if (clientFb != null)
            {
                var fbProvider          = new FacebookAuthProvider();
                var facebookAuthOptions = new FacebookAuthenticationOptions()
                {
                    AppId     = clientFb.AppId,
                    AppSecret = clientFb.AppSecret,
                    Provider  = fbProvider,
                };
                app.UseFacebookAuthentication(facebookAuthOptions);
            }
        }
Esempio n. 4
0
        public async Task <ActionResult> AuthCallBack(string code, string state)
        {
            string rootPath = "";
            bool   writeLog = false;

            if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null)
            {
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false)
                {
                    rootPath = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString();
                    writeLog = true;
                }
            }

            string file = rootPath + System.DateTime.Now.ToString("yyyyMMddhhmm") + "LNK_AuthCallBack.txt";

            _linkedInAuthClient = this._authenticationRepository.GetDbContext().LinkedInAuthClients.Where(_linked => _linked.Active).SingleOrDefault();

            if (Session["LinkedInState"] != null)
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(file, System.DateTime.Now.ToString() + " Start Callback Linked Process...");
                }

                string stateOriginal = Session["LinkedInState"].ToString();
                if (stateOriginal == state)
                {
                    LinkedInExternalAccessToken verifiedAccessToken = await VerifyExternalAccessToken(code, file, writeLog);

                    if (verifiedAccessToken == null)
                    {
                        if (writeLog)
                        {
                            System.IO.File.AppendAllText(file, Environment.NewLine + System.DateTime.Now.ToString() + " Linked In  External Access Token not found");
                        }

                        return(Content("Error in validating response. Please close window and try again."));
                    }
                    else
                    {
                        if (writeLog)
                        {
                            System.IO.File.AppendAllText(file, Environment.NewLine + System.DateTime.Now.ToString() + " start to read profile from linkedin...");
                        }
                    }

                    if (verifiedAccessToken != null)
                    {
                        LinkedProfile profileInfo = await GetProfileInfo(verifiedAccessToken.access_token, file, writeLog);

                        if (profileInfo != null)
                        {
                            User user = await this._authenticationRepository.FindAsync(new UserLoginInfo("linkedin", profileInfo.id));

                            bool hasRegistered = user != null;
                            if (hasRegistered == false)
                            {
                                if (writeLog)
                                {
                                    System.IO.File.AppendAllText(file, System.Environment.NewLine + System.DateTime.Now.ToString() + " local account is NOT FOUND for given linked in provider key...");
                                }
                            }
                            else
                            {
                                if (writeLog)
                                {
                                    System.IO.File.AppendAllText(file, System.Environment.NewLine + System.DateTime.Now.ToString() + " local account FOUND for given linked in provider key...");
                                }
                            }

                            ViewBag.Result          = true;
                            ViewBag.ErrorMessage    = "";
                            ViewBag.haslocalaccount = hasRegistered.ToString();
                            ViewBag.Id    = profileInfo.id;
                            ViewBag.Token = verifiedAccessToken.access_token;
                            return(View());
                        }
                    }
                }
                else
                {
                    ViewBag.Result       = false;
                    ViewBag.ErrorMessage = "Invalid state for linkedin response. Please close window and try again to login.";
                    return(View());
                }
            }
            ViewBag.Result       = false;
            ViewBag.ErrorMessage = "Error during validating response. Please close window and try again to login.";
            return(View());
        }