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));
            }
        }
示例#2
0
        public async Task <IHttpActionResult> RegisterExternalToken(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
            ApplicationUser user = await UserManager.FindByEmailAsync(externalLogin.Email);

            bool hasRegistered = user != null;

            if (!hasRegistered)
            {
                user = new ApplicationUser
                {
                    UserName            = externalLogin.ProviderKey,
                    Email               = externalLogin.Email,
                    ProfilePicture      = externalLogin.ProfilePicture,
                    CoverPicture        = externalLogin.CoverPicture,
                    Gender              = externalLogin.Gender,
                    Verified            = externalLogin.Verified,
                    Name                = externalLogin.Name,
                    FacebookId          = externalLogin.ProviderKey,
                    FacebookAccessToken = model.Token
                };
                var result = await UserManager.CreateAsync(user);

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

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

            Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);



            // 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("userId", user.Id),
                new JProperty("access_token", accessToken),
                new JProperty("token_type", "bearer"),
                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));
        }