// /oauth/authorize
 public override async Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
 {
     if (context.Request.User != null && context.Request.User.Identity.IsAuthenticated)
     {
         // si l'utilisateur est loggé,
         // on crée un ticket d'authent, on crée un authorization code et on fait le redirect
         var redirectUri = context.Request.Query["redirect_uri"];
         var clientId = context.Request.Query["client_id"];
         var authorizeCodeContext = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(context.OwinContext, context.Options.AuthorizationCodeFormat,
             new Microsoft.Owin.Security.AuthenticationTicket((ClaimsIdentity)context.Request.User.Identity, new Microsoft.Owin.Security.AuthenticationProperties(new Dictionary<string, string>
             {
                 {"client_id", clientId},
                 {"redirect_uri", redirectUri}
             })
             {
                 IssuedUtc = DateTimeOffset.UtcNow,
                 ExpiresUtc = DateTimeOffset.UtcNow.Add(context.Options.AuthorizationCodeExpireTimeSpan)
             }));
         await context.Options.AuthorizationCodeProvider.CreateAsync(authorizeCodeContext);
         
         // clear cookies
         var cookies = context.Request.Cookies.ToList();
         foreach (var c in cookies)
         {
             context.Response.Cookies.Delete(c.Key, new Microsoft.Owin.CookieOptions());
         }
         context.Response.Redirect(redirectUri + "?code=" + Uri.EscapeDataString(authorizeCodeContext.Token));
     }
     else
     {
         // si on n'est pas loggé, on redirige vers la page de login
         context.Response.Redirect("/account/login?returnUrl=" + Uri.EscapeDataString(context.Request.Uri.ToString()));
     }
     context.RequestCompleted();
 }
        // /oauth/authorize
        public override async Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
        {
            if (context.Request.User != null && context.Request.User.Identity.IsAuthenticated)
            {
                // si l'utilisateur est loggé,
                // on crée un ticket d'authent, on crée un authorization code et on fait le redirect
                var redirectUri          = context.Request.Query["redirect_uri"];
                var clientId             = context.Request.Query["client_id"];
                var authorizeCodeContext = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(context.OwinContext, context.Options.AuthorizationCodeFormat,
                                                                                                                       new Microsoft.Owin.Security.AuthenticationTicket((ClaimsIdentity)context.Request.User.Identity, new Microsoft.Owin.Security.AuthenticationProperties(new Dictionary <string, string>
                {
                    { "client_id", clientId },
                    { "redirect_uri", redirectUri }
                })
                {
                    IssuedUtc  = DateTimeOffset.UtcNow,
                    ExpiresUtc = DateTimeOffset.UtcNow.Add(context.Options.AuthorizationCodeExpireTimeSpan)
                }));
                await context.Options.AuthorizationCodeProvider.CreateAsync(authorizeCodeContext);

                // clear cookies
                var cookies = context.Request.Cookies.ToList();
                foreach (var c in cookies)
                {
                    context.Response.Cookies.Delete(c.Key, new Microsoft.Owin.CookieOptions());
                }
                context.Response.Redirect(redirectUri + "?code=" + Uri.EscapeDataString(authorizeCodeContext.Token));
            }
            else
            {
                // si on n'est pas loggé, on redirige vers la page de login
                context.Response.Redirect("/account/login?returnUrl=" + Uri.EscapeDataString(context.Request.Uri.ToString()));
            }
            context.RequestCompleted();
        }
        public async System.Threading.Tasks.Task CreateAsync(Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context)
        {
            var clientId = context.Ticket.Properties.Dictionary["as:client_id"];

            if (string.IsNullOrEmpty(clientId))
            {
                return;
            }
            var refreshTokenId = Guid.NewGuid().ToString("n");

            using (var _repo = new AuthRepository())
            {
                var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime");
                var token = new RefreshToken
                {
                    Id         = Helper.GetHash(refreshTokenId),
                    ClientId   = clientId,
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)),
                    IssuedUtc  = DateTime.UtcNow,
                    Subject    = context.Ticket.Identity.Name
                };
                context.Ticket.Properties.IssuedUtc  = token.IssuedUtc;
                context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;
                token.ProtectedTicket = context.SerializeTicket();
                var result = await _repo.AddRefreshToken(token);

                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
        }
Exemple #4
0
        private Dictionary <string, string> GenerateTokenResponse(AppUser appUser, List <UserRoles> userRoles, string deviceId, DeviceType deviceType)
        {
            var            tokenExpiration = Convert.ToDouble(ConfigurationManager.AppSettings["AccessTokenExpireTime"]);
            ClaimsIdentity identity        = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, appUser.UserName));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, appUser.Id.ToString()));
            identity.AddClaim(new Claim("displayName", appUser.Name));


            foreach (var userrole in userRoles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, userrole.RoleName));
            }
            var props = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromMinutes(tokenExpiration)),
            };
            var ticket  = new AuthenticationTicket(identity, props);
            var context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                Request.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket);

            var accessToken          = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
            var refreshTokenId       = Guid.NewGuid().ToString("n");
            var refreshTokenLifeTime = Convert.ToDouble(ConfigurationManager.AppSettings["RefreshTokenExpireTime"]);
            var refreshToken         = new RefreshToken()
            {
                RefreshTokenId = GenerateHash.GetHash(refreshTokenId),
                UserId         = appUser.Id,
                IssuedUtc      = DateTime.UtcNow,
                ExpiresUtc     = DateTime.UtcNow.AddMinutes(refreshTokenLifeTime),
                DeviceId       = deviceId,
                DeviceType     = deviceType
            };

            context.Ticket.Properties.IssuedUtc  = refreshToken.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = refreshToken.ExpiresUtc;
            Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
            refreshToken.ProtectedTicket = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket));

            //Save new token
            refreshTokenRepository.SaveRefreshToken(refreshToken);

            Dictionary <string, string> tokenResponse = new Dictionary <string, string>();

            tokenResponse.Add("access_token", accessToken);
            tokenResponse.Add("token_type", "bearer");
            tokenResponse.Add("expires_in", TimeSpan.FromMinutes(tokenExpiration).TotalSeconds.ToString());
            tokenResponse.Add("issued", ticket.Properties.IssuedUtc.Value.ToString("R"));
            tokenResponse.Add("expires", ticket.Properties.ExpiresUtc.Value.ToString("R"));
            tokenResponse.Add("refresh_token", refreshTokenId);
            tokenResponse.Add("user_name", appUser.UserName);
            tokenResponse.Add("display_name", appUser.Name);
            return(tokenResponse);
        }
Exemple #5
0
        public async Task <IHttpActionResult> Logon(WindowsLogonModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string authenticatedUserName = System.Web.HttpContext.Current.User.Identity.Name;

            // Generate the bearer token
            var identity = new ClaimsIdentity(model.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, authenticatedUserName));
            identity.AddClaim(new Claim("sub", authenticatedUserName));
            identity.AddClaim(new Claim("role", "user"));

            var props = new AuthenticationProperties(new Dictionary <string, string>()
            {
                { "as:client_id", model.ClientId ?? String.Empty },
                { "userName", authenticatedUserName }
            });

            var ticket = new AuthenticationTicket(identity, props);

            var context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                Request.GetOwinContext(),
                Startup.OAuthServerOptions.AccessTokenFormat, ticket);

            string strToken = context.SerializeTicket();

            using (AuthRepository _repo = new AuthRepository())
            {
                // retrieve client from database
                var client = _repo.FindClient(model.ClientId);
                // only generate refresh token if client is registered
                if (client != null)
                {
                    var contextRefresh = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                        Request.GetOwinContext(),
                        Startup.OAuthServerOptions.RefreshTokenFormat, ticket);

                    // Set this two context parameters or it won't work!!
                    contextRefresh.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
                    contextRefresh.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

                    // Generate the refresh toke
                    await Startup.OAuthServerOptions.RefreshTokenProvider.CreateAsync(contextRefresh);

                    return(Json(new { access_token = strToken, userName = authenticatedUserName, refresh_token = contextRefresh.Token, useRefreshTokens = true }));
                }
            }

            return(Json(new { access_token = strToken, userName = authenticatedUserName, refresh_token = "", useRefreshTokens = false }));
        }
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new ApplicationUser()
            {
                UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, IsActive = true
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            var tokenExpiration = TimeSpan.FromDays(14); //same as local accounts;
            var identity        = await user.GenerateUserIdentityAsync(_repo.UserManager, "JWT");

            var props = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            var ticket      = new AuthenticationTicket(identity, props);
            var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

            Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
                new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                    Request.GetOwinContext(),
                    Startup.OAuthOptions.AccessTokenFormat, ticket);

            await new RefreshTokenProvider().CreateAsync(context);

            var pocoUser = new UsersBuilder(_repo).GetUser(user.Id);

            var tokenResponse = new
            {
                access_token  = accessToken,
                refresh_token = context.Token,
                token_type    = "bearer",
                expires_in    = tokenExpiration.TotalSeconds.ToString(),
                user          = JsonConvert.SerializeObject(pocoUser),
            };

            return(Ok(tokenResponse));
        }
        public static AuthenticationProperties auth(Users user, HttpRequestMessage req)
        {
            if (user == null || req == null)
            {
                return(null);
            }

            // set token expiration time
            var tokenExpiration = TimeSpan.FromHours(12);

            // create new claims identity
            ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, user.name));
            identity.AddClaim(new Claim("user_id", user.id.ToString()));

            // set auth properties
            var props = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            // new ticket
            var ticket = new AuthenticationTicket(identity, props);

            // create auth context
            var context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                req.GetOwinContext(),
                Startup.OAuthBearerOptions.AccessTokenFormat, ticket);

            // get refresh token
            var refresh_token = Startup.oAuthAuthorizationServerOptions.RefreshTokenFormat.Protect(ticket);

            props.Dictionary.Add("refresh_token", refresh_token);

            // get access token
            var access_token = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

            props.Dictionary.Add("access_token", access_token);

            return(props);
        }
Exemple #8
0
        private JObject GenerateLocalAccessTokenResponse(string userName)
        {
            var tokenExpiration = TimeSpan.FromDays(1);

            ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, userName));
            identity.AddClaim(new Claim("role", "user"));

            var props = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            var ticket = new AuthenticationTicket(identity, props);

            var context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                Request.GetOwinContext(),
                Startup.OAuthBearerOptions.AccessTokenFormat, ticket);

            Startup.OAuthBearerOptions.AccessTokenProvider.CreateAsync((context));
            context.Ticket.Properties.Dictionary.Add("refresh_token", context.Token);
            Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();

            var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

            JObject tokenResponse = new JObject(
                new JProperty("userName", userName),
                new JProperty("access_token", accessToken),
                new JProperty("resfresh_token", context.Token),
                new JProperty("token_type", "bearer"),
                new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
                new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
                );

            return(tokenResponse);
        }
        public async Task <IHttpActionResult> CheckForExistingAccount(RegisterExternalTokenBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //validate token
            ExternalLoginData externalLogin = await ExternalLoginData.FromToken(model.Provider, model.Token);


            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != model.Provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(InternalServerError());
            }
            //if we reached this point then token is valid
            // Original from tutorial >>>>> ApplicationUser user = await UserManager.FindByEmailAsync(model.Email);

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

            bool hasRegistered = user != null;


            if (hasRegistered)
            {
                //authenticate
                var identity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

                IEnumerable <Claim> claims = externalLogin.GetClaims();
                identity.AddClaims(claims);
                Authentication.SignIn(identity);

                ClaimsIdentity oAuthIdentity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

                DateTime currentUtc = DateTime.UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan);

                string accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);



                Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
                    new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                        Request.GetOwinContext(),
                        Startup.OAuthOptions.AccessTokenFormat, ticket);

                await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);

                // properties.Dictionary.Add("refresh_token", context.Token); original 2
                ticket.Properties.Dictionary.Add("UserName", user.UserName);

                Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); ///already there in solution



                // Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
                JObject token = new JObject(
                    new JProperty("userName", user.UserName),
                    new JProperty("nationality", user.Nationality),
                    new JProperty("workStatus", user.WorkStatus),
                    new JProperty("userId", user.Id),
                    new JProperty("profilePhoto", user.ProfilePicture),
                    new JProperty("access_token", accessToken),
                    new JProperty("token_type", "bearer"),
                    new JProperty("refresh_token", context.Token),
                    new JProperty("expires_in", Startup.OAuthOptions.AccessTokenExpireTimeSpan.TotalSeconds.ToString()),
                    new JProperty("issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
                    new JProperty("expires", currentUtc.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
                    );

                return(Ok(token));
            }
            else
            {
                JObject token1 = new JObject(
                    new JProperty("userName", "Not Registered")
                    );

                return(Ok(token1));
            }
        }
        public async Task <IHttpActionResult> LocalLogin(Login model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            ApplicationUser user = await UserManager.FindAsync(model.UserName, model.Password);

            if (user == null)
            {
                return(BadRequest("The user name or password is incorrect."));
            }


            //authenticate
            var identity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

            //IEnumerable<Claim> claims = externalLogin.GetClaims();
            //identity.AddClaims(claims);
            Authentication.SignIn(identity);

            ClaimsIdentity oAuthIdentity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

            DateTime currentUtc = DateTime.UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan);

            string accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);



            Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
                new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                    Request.GetOwinContext(),
                    Startup.OAuthOptions.AccessTokenFormat, ticket);

            await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);

            // properties.Dictionary.Add("refresh_token", context.Token); original 2
            ticket.Properties.Dictionary.Add("UserName", user.UserName);

            Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);     ///already there in solution



            // Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
            JObject token = new JObject(
                new JProperty("userName", user.UserName),
                new JProperty("nationality", user.Nationality),
                new JProperty("workStatus", user.WorkStatus),
                new JProperty("userId", user.Id),
                new JProperty("profilePhoto", user.ProfilePicture),
                new JProperty("access_token", accessToken),
                new JProperty("token_type", "bearer"),
                new JProperty("refresh_token", context.Token),
                new JProperty("expires_in", Startup.OAuthOptions.AccessTokenExpireTimeSpan.TotalSeconds.ToString()),
                new JProperty("issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
                new JProperty("expires", currentUtc.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
                );

            return(Ok(token));
        }
Exemple #11
0
        public IHttpActionResult GetAccessToken(RefreshTokenModel refreshTokenModel)
        {
            ApiResponse apiResponse = new ApiResponse();

            apiResponse.Message = "Your session has expired. Kindly login again.";
            try
            {
                var getHashToken           = GenerateHash.GetHash(refreshTokenModel.RefreshToken);
                var getRefreshTokenDetails = refreshTokenRepository.GetRefreshTokenDetail(getHashToken);
                if (getRefreshTokenDetails != null && getRefreshTokenDetails.ExpiresUtc > DateTime.UtcNow && !string.IsNullOrEmpty(getRefreshTokenDetails.ProtectedTicket))
                {
                    if (getRefreshTokenDetails.DeviceType == refreshTokenModel.DeviceType)
                    {
                        var currentTime = DateTime.UtcNow;
                        Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
                        var getSecurityClaims = serializer.Deserialize(System.Text.Encoding.Default.GetBytes(getRefreshTokenDetails.ProtectedTicket));

                        //Generate New Refresh Token and Access Token
                        var tokenExpiration = Convert.ToDouble(ConfigurationManager.AppSettings["AccessTokenExpireTime"]);
                        var props           = new AuthenticationProperties()
                        {
                            IssuedUtc  = currentTime,
                            ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromMinutes(tokenExpiration)),
                        };

                        var ticket  = new AuthenticationTicket(getSecurityClaims.Identity, props);
                        var context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                            Request.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket);
                        context.Ticket.Properties.Dictionary.Add(new KeyValuePair <string, string>("device_id", getRefreshTokenDetails.DeviceId));
                        var accessToken          = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
                        var refreshTokenId       = Guid.NewGuid().ToString("n");
                        var refreshTokenLifeTime = Convert.ToDouble(ConfigurationManager.AppSettings["RefreshTokenExpireTime"]);


                        var refreshToken = new RefreshToken()
                        {
                            RefreshTokenId = GenerateHash.GetHash(refreshTokenId),
                            DeviceId       = getRefreshTokenDetails.DeviceId,
                            DeviceType     = refreshTokenModel.DeviceType,
                            UserId         = getRefreshTokenDetails.UserId,
                            IssuedUtc      = currentTime,
                            ExpiresUtc     = currentTime.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)),
                        };
                        context.Ticket.Properties.IssuedUtc  = refreshToken.IssuedUtc;
                        context.Ticket.Properties.ExpiresUtc = refreshToken.ExpiresUtc;
                        refreshToken.ProtectedTicket         = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket));

                        //SAVE Refresh token
                        refreshTokenRepository.SaveRefreshToken(refreshToken);

                        Dictionary <string, string> tokenResponse = new Dictionary <string, string>();
                        tokenResponse.Add("access_token", accessToken);
                        tokenResponse.Add("token_type", "bearer");
                        tokenResponse.Add("expires_in", TimeSpan.FromMinutes(tokenExpiration).TotalSeconds.ToString());
                        tokenResponse.Add("issued", ticket.Properties.IssuedUtc.Value.ToString("R"));
                        tokenResponse.Add("expires", ticket.Properties.ExpiresUtc.Value.ToString("R"));
                        tokenResponse.Add("refresh_token", refreshTokenId);
                        return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, tokenResponse)));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(ResponseMessage(Request.CreateResponse(HttpStatusCode.Gone, apiResponse)));
        }
        public async Task <IHttpActionResult> RegisterFacebook(string facebookToken)
        {
            if (String.IsNullOrEmpty(facebookToken))
            {
                return(BadRequest("Facebook Token Cannot be empty"));
            }
            var facebookId = "";
            var email      = "";
            var first      = "";
            var last       = "";

            try
            {
                var client = new FacebookClient(facebookToken);
                var result = client.Get("/me?fields=id,first_name, last_name,email");
                var me     = JsonConvert.DeserializeObject <JObject>(result.ToString());
                facebookId = me["id"].ToString();

                email = me["email"]?.ToString();
                if (string.IsNullOrEmpty(email))
                {
                    return(BadRequest("FanWord does not have access to your Facebook email. Please go into your Facebook settings and allow FanWord to access your email to continue"));
                }
                first = me["first_name"].ToString();
                last  = me["last_name"].ToString();
            }
            catch (FacebookOAuthException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                return(BadRequest("Error " + ex.Message));
            }

            // Get user by facebook id
            var existing = UserManager.Users.FirstOrDefault(m => m.Logins.Any(j => j.ProviderKey == facebookId));

            if (existing == null)
            {
                // User not found by facebook id
                // Try e-mail (the user may already exist via regular login)
                existing = UserManager.Users.Include(m => m.ContentSource).FirstOrDefault(m => m.Email == email);

                if (existing == null)
                {
                    existing                = new ApplicationUser();
                    existing.Email          = email;
                    existing.UserName       = email;
                    existing.DateCreatedUtc = DateTime.UtcNow;
                    existing.FirstName      = first;
                    existing.LastName       = last;
                    existing.IsActive       = true;
                    var result = await UserManager.CreateAsync(existing);

                    if (!result.Succeeded)
                    {
                        return(GetErrorResult(result));
                    }
                    try
                    {
                        await UserManager.AddLoginAsync(existing.Id, new UserLoginInfo("Facebook", facebookId));

                        await UserManager.AddClaimAsync(existing.Id, new Claim("FacebookAccessToken", facebookToken));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }
                else
                {
                    return(BadRequest("An account with your Facebook e-mail address already exists. Please login using your e-mail and password instead."));
                }
            }

            var tokenExpiration = TimeSpan.FromDays(14); //same as local accounts;

            var identity = await existing.GenerateUserIdentityAsync(_repo.UserManager, "JWT");

            var props = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            var ticket      = new AuthenticationTicket(identity, props);
            var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

            Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
                new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                    Request.GetOwinContext(),
                    Startup.OAuthOptions.AccessTokenFormat, ticket);

            await new RefreshTokenProvider().CreateAsync(context);

            var user          = new UsersBuilder(_repo).GetUser(existing.Id);
            var tokenResponse = new
            {
                access_token  = accessToken,
                refresh_token = context.Token,
                token_type    = "bearer",
                expires_in    = tokenExpiration.TotalSeconds.ToString(),
                user          = JsonConvert.SerializeObject(user),
            };

            return(Ok(tokenResponse));
        }
 public void Create(Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context)
 {
     throw new NotImplementedException();
 }