public string Authenticate(string Email, string Password)
        {
            AuthenticateService service = new AuthenticateService(_container);

            if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password))
            {
                var user = service.Authenticate(Email, Password);
                if (user != null)
                {
                    var authentication = Request.GetOwinContext().Authentication;
                    var identity = new ClaimsIdentity("Bearer");
                    identity.AddClaim(new Claim("name", user.Name));
                    identity.AddClaim(new Claim("email", user.Email));
                    identity.AddClaim(new Claim("userid", user.Id.ToString()));
                    identity.AddClaim(new Claim("usertype", user.UserType.ToString()));
                    identity.AddClaim(new Claim("companyid", user.Company.Id.ToString()));
                    identity.AddClaim(new Claim("companyname", user.Company.Name));

                    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc = currentUtc;
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
                    var token = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);

                    authentication.SignIn(identity);

                    return token;
                }
            }

            return "false";
        }
示例#2
0
        public Models.AccessGrantDto GenerateAccessGrant(User user, CredentialsDto credentials)
        {
            var tokenExpirationTimeSpan = TimeSpan.FromDays(14);
            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, user.Id, null, credentials.Provider));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, null, "LOCAL_AUTHORITY"));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
            var accesstoken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

            Authentication.SignIn(identity);
            AccessGrantDto grant = new AccessGrantDto
            {
                AccessToken = accesstoken,
                Expires     = ticket.Properties.ExpiresUtc.Value.DateTime,
                ExpiresIn   = tokenExpirationTimeSpan.Seconds.ToString(),
                Issued      = ticket.Properties.IssuedUtc.Value.DateTime,
                ID          = user.Id,
                UserName    = user.UserName,
                TokenType   = TOKEN_TYPE
            };

            return(grant);
        }
示例#3
0
        //[HttpGet]
        //[Route("CountryList")]
        //public IHttpActionResult CountryList()
        //{
        //    try
        //    {
        //        GeneralBusiness generalBusiness = new GeneralBusiness(false);
        //        var listCountries = generalBusiness.GetAllCountries();

        //        responseData.success = true;
        //        responseData.code = 200;
        //        responseData.message = "country list updated successfully";
        //        responseData.data = listCountries;
        //        return Ok(responseData);
        //    }
        //    catch (Exception ex)
        //    {
        //        responseData.message = "server error";
        //        return Ok(responseData);
        //    }
        //}
        //[HttpGet]
        //[Route("StateList/{countryId}")]
        //public IHttpActionResult StateList(Guid countryId)
        //{
        //    try
        //    {
        //        GeneralBusiness generalBusiness = new GeneralBusiness(false);
        //        var listStates = generalBusiness.GetStatesByCountry(countryId);

        //        responseData.success = true;
        //        responseData.code = 200;
        //        responseData.message = "states list updated successfully";
        //        responseData.data = listStates;
        //        return Ok(responseData);
        //    }
        //    catch (Exception ex)
        //    {
        //        responseData.message = "server error";
        //        return Ok(responseData);
        //    }
        //}
        //[HttpGet]
        //[Route("CityList/{stateId}")]
        //public IHttpActionResult CityList(Guid stateId)
        //{
        //    try
        //    {
        //        GeneralBusiness generalBusiness = new GeneralBusiness(false);
        //        var listCities = generalBusiness.GetCitiesByState(stateId);

        //        responseData.success = true;
        //        responseData.code = 200;
        //        responseData.message = "cities list updated successfully";
        //        responseData.data = listCities;
        //        return Ok(responseData);
        //    }
        //    catch (Exception ex)
        //    {
        //        responseData.message = "server error";
        //        return Ok(responseData);
        //    }
        //}

        /// <summary>
        /// Create access token and refresh token for user login with facebook or google
        /// </summary>
        /// <param name="objUser">User Model Object</param>
        /// <returns>Return Json object with access_token and refresh_token</returns>
        private UserTokenViewModel GenerateAccessTokenForUser(UsersModel userVM)
        {
            var tokenExpirationTimeSpan = TimeSpan.FromDays(1);
            // var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
            //identity.AddClaim(new Claim(ClaimTypes.Role, userVM.UserType));
            //identity.AddClaim(new Claim(ClaimTypes.Email, userVM.EmailID));
            //identity.AddClaim(new Claim(ClaimTypes.Name, Convert.ToString(userVM.UserID)));

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

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, Convert.ToString(userVM.RefType)));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Sid, Convert.ToString(userVM.RefID)));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Convert.ToString(userVM.UserID)));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Email, userVM.Email));

            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
            var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
            AuthenticationTokenCreateContext rtokenContext = new AuthenticationTokenCreateContext(HttpContext.Current.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket);

            AuthenticationTokenProvider rtokenProvider = new AuthenticationTokenProvider();
            var refresh_token            = rtokenProvider.CreateRefreshToken(rtokenContext);
            UserTokenViewModel userToken = new UserTokenViewModel();

            userToken.access_token  = accessToken;
            userToken.expires_in    = tokenExpirationTimeSpan.TotalSeconds.ToString();
            userToken.refresh_token = refresh_token;
            return(userToken);
        }
示例#4
0
        public string Authenticate(string Email, string Password)
        {
            AuthenticateService service = new AuthenticateService(_container);

            if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password))
            {
                var user = service.Authenticate(Email, Password);
                if (user != null)
                {
                    var authentication = Request.GetOwinContext().Authentication;
                    var identity       = new ClaimsIdentity("Bearer");
                    identity.AddClaim(new Claim("name", user.Name));
                    identity.AddClaim(new Claim("email", user.Email));
                    identity.AddClaim(new Claim("userid", user.Id.ToString()));
                    identity.AddClaim(new Claim("usertype", user.UserType.ToString()));
                    identity.AddClaim(new Claim("companyid", user.Company.Id.ToString()));
                    identity.AddClaim(new Claim("companyname", user.Company.Name));

                    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc  = currentUtc;
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
                    var token = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);

                    authentication.SignIn(identity);

                    return(token);
                }
            }

            return("false");
        }
        private string GetToken(ApplicationUser userIdentity)
        {
            if (userIdentity != null)
            {
                var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, userIdentity.Email));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
                AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
                string AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

                //ClaimsIdentity identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
                //identity.AddClaim(new Claim(ClaimTypes.Name, userIdentity.UserName));
                //identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
                //AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                //DateTime currentUtc = DateTime.UtcNow;
                //ticket.Properties.IssuedUtc = currentUtc;
                //ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
                //string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

                return(AccessToken);
            }

            return("no token");
        }
示例#6
0
        public bool Post(LoginUser loginUser)
        {
            if (!string.IsNullOrEmpty(loginUser.Email) && !string.IsNullOrEmpty(loginUser.Password))
            {
                var user = _userService.Login(loginUser.Email, loginUser.Password);
                if (user != null)
                {
                    var authentication = Request.GetOwinContext().Authentication;
                    var identity       = new ClaimsIdentity();
                    identity.AddClaim(new Claim("name", user.Name));
                    identity.AddClaim(new Claim("email", user.Email));
                    identity.AddClaim(new Claim("userid", user.UserID.ToString()));
                    identity.AddClaim(new Claim("isadmin", user.IsAdministrator.ToString()));



                    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc  = currentUtc;
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
                    var token = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);

                    authentication.SignIn(identity);

                    return(true);
                }
            }

            return(false);
        }
示例#7
0
        private async Task <AuthenticationTicket> CreateAuthenticationTicket(IOwinContext owinContext, ClaimsIdentity oAuthIdentity)
        {
            ILogServiceAsync <ILogServiceSettings> logService = GlobalConfiguration.Configuration.DependencyResolver.GetService <ILogServiceAsync <ILogServiceSettings> >();

            var sqlUserManager = owinContext.GetUserManager <ApplicationUserManager>();
            var sqlUser        = await sqlUserManager.FindByNameAsync(oAuthIdentity.Name);

            //http://www.c-sharpcorner.com/UploadFile/ff2f08/angularjs-enable-owin-refresh-tokens-using-asp-net-web-api/
            var newIdentity = new ClaimsIdentity(oAuthIdentity);

            //SqlServerClaimsGenerator claimsGenerator = new SqlServerClaimsGenerator(
            //    sqlUser,
            //    oAuthIdentity,
            //    owinContext.Get<RepoBase<SystemUser>>());

            //claimsGenerator.GenerateClaims();

            oAuthIdentity.AddClaim(new Claim("projectRequestRole", JsonConvert.SerializeObject(new SimpleRoleClaim
            {
                UserId                = 2154,                //_user.SystemUserID,
                DomainLogin           = "******",  //_user.DomainLogin.Trim(),
                UserName              = "******",      //_user.DomainLogin.Trim(),
                EmailAddress          = "*****@*****.**", //_user.EmailAddress.Trim(),
                DepartmentDescription = "some dp des",       //_user.DepartmentDescr,
                DepartmentId          = 33,                  //_user.DepartmentID,
                IsActive              = true,                //_user.boolIsActive,
                Role = "user",                               //_user.AppRole
            })));

            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;

            AuthenticationProperties properties = CreateProperties(sqlUser);
            AuthenticationTicket     ticket     = new AuthenticationTicket(newIdentity, properties);

            ticket.Properties.IssuedUtc    = DateTime.UtcNow;
            ticket.Properties.ExpiresUtc   = currentUtc.Add(TimeSpan.FromDays(365));//TODO: configure token expiration time in web config
            ticket.Properties.AllowRefresh = true;

            var principal = new ClaimsPrincipal(new[] { oAuthIdentity });

            owinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            logService.LogMessage(new
            {
                type     = "claimsRefreshed",
                endpoint = owinContext.Request.Uri,
                userName = oAuthIdentity.Name,
                data     = new
                {
                    orgUsers = principal.GetClaim <SimpleRoleClaim>("projectRequestRole"),
                }
            });

            return(ticket);
        }
示例#8
0
 public void getToken(string token)
 {
     var tokenExpirationTimeSpan = TimeSpan.FromDays(14);
     ApplicationUser user = null;
     // Get the fb access token and make a graph call to the /me endpoint
     // Check if the user is already registered
     // If yes retrieve the user
     // If not, register it
     // Finally sign-in the user: this is the key part of the code that creates the bearer token and authenticate the user
     var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
     identity.AddClaim(new Claim(ClaimTypes.Name, user.Id, null, "Facebook"));
     // This claim is used to correctly populate user id
     identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, null, "LOCAL_AUTHORITY"));
     AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
     var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
     ticket.Properties.IssuedUtc = currentUtc;
     ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
     var accesstoken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
      //  Authentication.SignIn(identity);
 }
示例#9
0
        public void getToken(string token)
        {
            var             tokenExpirationTimeSpan = TimeSpan.FromDays(14);
            ApplicationUser user = null;
            // Get the fb access token and make a graph call to the /me endpoint
            // Check if the user is already registered
            // If yes retrieve the user
            // If not, register it
            // Finally sign-in the user: this is the key part of the code that creates the bearer token and authenticate the user
            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, user.Id, null, "Facebook"));
            // This claim is used to correctly populate user id
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, null, "LOCAL_AUTHORITY"));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
            var accesstoken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
            //  Authentication.SignIn(identity);
        }
示例#10
0
        public async Task <IHttpActionResult> FacebookLogin(string token, string token_type, string expires_in, string state)
        {
            var             tokenExpirationTimeSpan = TimeSpan.FromDays(14);
            ApplicationUser user = null;
            // Get the fb access token and make a graph call to the /me endpoint
            // Check if the user is already registered
            string username;

            try {
                var url = string.Format("https://graph.facebook.com/v2.2/me?access_token={0}&format=json&method=get&pretty=0&suppress_http_code=1", token);

                var request = WebRequest.Create(url);
                Request.Method = HttpMethod.Get;

                using (var response = request.GetResponse())
                    using (var stream = response.GetResponseStream())
                    {
                        var serializer = new JsonSerializer();

                        using (var sr = new StreamReader(stream))
                            using (var jsonTextReader = new JsonTextReader(sr))
                            {
                                var result = serializer.Deserialize(jsonTextReader);
                            }
                    }
            }
            catch (Exception e)
            {
                var lool = e;
            }

            // If yes retrieve the user
            // If not, register it
            // Finally sign-in the user: this is the key part of the code that creates the bearer token and authenticate the user
            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, user.Id, null, "Facebook"));
            // This claim is used to correctly populate user id
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, null, "LOCAL_AUTHORITY"));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
            var accesstoken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

            Authentication.SignIn(identity);

            // Create the response
            JObject blob = new JObject(
                new JProperty("userName", user.UserName),
                new JProperty("access_token", accesstoken),
                new JProperty("token_type", "bearer"),
                new JProperty("expires_in", tokenExpirationTimeSpan.TotalSeconds.ToString()),
                new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
                );

            var json = Newtonsoft.Json.JsonConvert.SerializeObject(blob);

            // Return OK
            return(Ok(blob));
        }
示例#11
0
        //http://blog.valeriogheri.com/asp-net-webapi-identity-system-how-to-login-with-facebook-access-token
        public async Task <IHttpActionResult> GoogleLogin(AddExternalLoginBindingModel model)
        {
            if (string.IsNullOrEmpty(model.ExternalAccessToken))
            {
                return(BadRequest("Invalid OAuth access token"));
            }
            ApplicationUser user = null;

            // Get the fb access token and make a graph call to the /me endpoint
            VerifyToken verifyToken = new VerifyToken();
            var         fbUser      = await verifyToken.VerifyGoogleAccessToken(null, model.ExternalAccessToken);

            if (fbUser == null)
            {
                return(BadRequest("Invalid OAuth access token"));
            }
            if (!fbUser.aud.Equals(VerifyToken.CLIENT_ID))
            {
                return(BadRequest("Invalid OAuth access token"));
            }

            try
            {
                using (var dbTransaction = db.Database.BeginTransaction())
                {
                    if (model.Email != null)
                    {
                        // model.Email is an application account's email, not google login's email
                        user = await UserManager.FindByEmailAsync(model.Email);

                        if (user == null)
                        {
                            return(BadRequest("Invalid Email"));
                        }
                        //
                        bool isGoogleLoginAlreadyBelongToTheUser = false;
                        var  userLogins = await UserManager.GetLoginsAsync(user.Id);

                        foreach (UserLoginInfo userLoginInfo in userLogins)
                        {
                            if (userLoginInfo.LoginProvider.Equals("Google") && userLoginInfo.ProviderKey.Equals(fbUser.sub))
                            {
                                isGoogleLoginAlreadyBelongToTheUser = true;
                                break;
                            }
                        }
                        if (!isGoogleLoginAlreadyBelongToTheUser)
                        {
                            bool isGoogleLoginAlreadyBelongToSomeOtherUser = db.Users.Where(u => u.Logins.Any(l => l.LoginProvider.Equals("Google") && l.ProviderKey.Equals(fbUser.sub))).Count() > 0;
                            if (isGoogleLoginAlreadyBelongToSomeOtherUser)
                            {
                                return(BadRequest("Invalid OAuth access token"));
                            }
                            else
                            {
                                if (!user.EmailConfirmed && !user.Email.ToLower().Equals(fbUser.Email.ToLower()))
                                {
                                    return(BadRequest("Application account's email is not confirmed yet"));
                                }
                                //add login
                                //user.Logins.Add(new IdentityUserLogin() { LoginProvider = "Google", ProviderKey = fbUser.sub });

                                IdentityResult result = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo("Google", fbUser.sub));

                                if (!result.Succeeded)
                                {
                                    return(GetErrorResult(result));
                                }
                                //make email confirmed
                                user.EmailConfirmed = true;
                            }
                        }
                        else
                        {
                            //nothing to do
                        }
                    }
                    else
                    {
                        //try to find user
                        user = db.Users.Where(u => u.Logins.Any(l => l.LoginProvider.Equals("Google") && l.ProviderKey.Equals(fbUser.sub))).SingleOrDefault();
                        if (user == null)
                        {
                            // user not found so
                            //create user and add login
                            string randomPassword;

                            //At least one lower case letter
                            Regex r1 = new Regex("[a-z]+");
                            //At least one upper case letter
                            Regex r2 = new Regex("[A-Z]+");
                            //At least one digit
                            Regex r3 = new Regex("[0-9]+");

                            string NewPassword = System.Web.Security.Membership.GeneratePassword(10, 5);

                            while (!(r1.IsMatch(NewPassword) && r2.IsMatch(NewPassword) && r3.IsMatch(NewPassword)))
                            {
                                //regenerate new password
                                NewPassword = System.Web.Security.Membership.GeneratePassword(10, 5);
                            }
                            randomPassword = NewPassword;
                            user           = new ApplicationUser()
                            {
                                UserName = fbUser.Email, Email = fbUser.Email, EmailConfirmed = true
                            };
                            IdentityResult result = await UserManager.CreateAsync(user, randomPassword);

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

                            //user.Logins.Add(new IdentityUserLogin() { LoginProvider = "Google", ProviderKey = fbUser.sub });

                            IdentityResult result2 = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo("Google", fbUser.sub));

                            if (!result2.Succeeded)
                            {
                                return(GetErrorResult(result2));
                            }
                        }
                        else
                        {
                            //nothing to do
                        }
                    }
                    db.SaveChanges();
                    dbTransaction.Commit();
                }
            }
            catch (Exception e)
            {
                return(Conflict());
            }
            // Finally sign-in the user: this is the key part of the code that creates the bearer token and authenticate the user
            var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, null, ClaimsIdentity.DefaultIssuer));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName, null, ClaimsIdentity.DefaultIssuer));
            identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", null, ClaimsIdentity.DefaultIssuer));
            identity.AddClaim(new Claim("AspNet.Identity.SecurityStamp", user.SecurityStamp, null, ClaimsIdentity.DefaultIssuer));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;

            ticket.Properties.IssuedUtc = currentUtc;
            var tokenExpirationTimeSpan = TimeSpan.FromDays(14);

            ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
            var accesstoken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

            Authentication.SignIn(identity);

            // Create the response
            JObject blob = new JObject(
                new JProperty("userName", user.UserName),
                new JProperty("access_token", accesstoken),
                new JProperty("token_type", "bearer"),
                new JProperty("expires_in", (long)tokenExpirationTimeSpan.TotalSeconds),
                new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
                );
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(blob);

            // Return OK
            return(Ok(blob));
        }
示例#12
0
        public async Task<IHttpActionResult> Post(LoginModel loginModel) 
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var tokenExpirationTimeSpan = TimeSpan.FromDays(14);
            ApplicationUser user = null; 

            var fbUser = await VerifyFacebookAccessToken(loginModel.authAccessToken);
            if (fbUser == null)
            {
                return BadRequest("Invalid OAuth access token");
            }


            UserLoginInfo loginInfo = new UserLoginInfo("Facebook", fbUser.id);

            user = await UserManager.FindAsync(loginInfo);

            if(user == null)
            {
                user = new ApplicationUser() {  UserName = fbUser.name, Email = fbUser.email, firstName = fbUser.first_name, photo = fbUser.userPicture };
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, loginInfo);
                    if (!result.Succeeded)
                        return BadRequest("cannot add facebook login");
                }
                else
                {
                    return BadRequest("cannot create user");
                }
            }
            
            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, user.Id, null, "Facebook"));
            // This claim is used to correctly populate user id
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, null, "LOCAL_AUTHORITY"));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
            var accesstoken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
            Authentication.SignIn(identity);

            LoginModel loginDto = new LoginModel() {
                authServer = "facebook",
                authServerId = fbUser.id,
                bearerAccessToken = accesstoken,
                expiresIn = tokenExpirationTimeSpan.TotalSeconds.ToString(),
                issued = ticket.Properties.IssuedUtc.ToString(),
                expires = ticket.Properties.ExpiresUtc.ToString()
            };

            return Ok(loginDto);
        }
        public async Task <IHttpActionResult> Register(dtoRegistration user)
        {
            if (user == null)
            {
                return(BadRequest("Invalid Request"));
            }

            if (string.IsNullOrEmpty(user.Email))
            {
                return(BadRequest("Invalid email address"));
            }

            if (string.IsNullOrEmpty(user.PostalCode))
            {
                return(BadRequest("Invalid post/zip code"));
            }

            if (string.IsNullOrEmpty(user.Telephone))
            {
                return(BadRequest("Invalid telephone number"));
            }

            var userIdentity = UserManager.FindByEmailAsync(user.Email).Result;

            if (userIdentity != null)
            {
                return(BadRequest("A user for that e-mail address already exists. Please enter a different e-mail address."));
            }

            var newUser = new ApplicationUser()
            {
                Email       = user.Email,
                UserName    = user.Email,
                PhoneNumber = user.Telephone
            };

            var result = await UserManager.CreateAsync(newUser, user.Password);

            if (result.Succeeded)
            {
                var code = await UserManager.GenerateEmailConfirmationTokenAsync(newUser.Id);

                var callbackUrl = this.Url.Link("Default", new { Controller = "Account", Action = "ConfirmEmail", userId = newUser.Id, code = code });
                await UserManager.SendEmailAsync(newUser.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">Activate Account</a>");

                var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Email));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, newUser.Id));
                AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

                dtoRegistered registered = new dtoRegistered
                {
                    UserName   = user.Email,
                    Token      = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket),
                    IssuedUtc  = ticket.Properties.IssuedUtc,
                    ExpiresUtc = ticket.Properties.ExpiresUtc
                };

                return(Ok(registered));
            }

            var errors = string.Join(",", result.Errors);

            return(BadRequest(errors));
        }
示例#14
0
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            var usernameObj = context.Identity.Claims.Where(c => c.Type == Database.Username).Single();

            var appnameObj = context.Identity.Claims.Where(c => c.Type == Database.AppName).Single();

            if (usernameObj != null && appnameObj != null)
            {
                string username = usernameObj.Value;
                if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Items.Contains(Database.Username))
                {
                    username = System.Web.HttpContext.Current.Items[Database.Username].ToString();
                }
                string appname = appnameObj.Value;

                context.AdditionalResponseParameters.Add("appName", appname);
                context.AdditionalResponseParameters.Add("username", username);


                try
                {
                    Durados.Web.Mvc.Map map = Durados.Web.Mvc.Maps.Instance.GetMap(appname);
                    var currentUtc          = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;

                    int expiration = map.Database.TokenExpiration;
                    if (expiration == 0 || expiration == 8640)
                    {
                        expiration = 86400;
                    }
                    context.Properties.IssuedUtc  = currentUtc;
                    context.Properties.ExpiresUtc = currentUtc.Add(System.TimeSpan.FromSeconds(expiration));

                    string role          = map.Database.GetUserRole2(username);
                    int    backandUserId = map.Database.GetUserID(username);
                    object userId        = map.Database.GetCurrentUserId();

                    context.AdditionalResponseParameters.Add("role", role);
                    try
                    {
                        string firstName = map.Database.GetUserFirstName();
                        context.AdditionalResponseParameters.Add("firstName", firstName);
                        string lastName = map.Database.GetUserLastName();
                        context.AdditionalResponseParameters.Add("lastName", lastName);
                        string fullName = map.Database.GetUserFullName2(username).ToString();
                        context.AdditionalResponseParameters.Add("fullName", fullName);
                    }
                    catch { }
                    context.AdditionalResponseParameters.Add("regId", backandUserId);
                    context.AdditionalResponseParameters.Add("userId", userId);
                }
                catch { }

                try
                {
                    if (System.Web.HttpContext.Current.Items.Contains(Durados.Database.CustomTokenAttrKey))
                    {
                        IDictionary <string, object> dic = (IDictionary <string, object>)System.Web.HttpContext.Current.Items[Durados.Database.CustomTokenAttrKey];
                        const string ForToken            = "forToken";
                        if (dic.ContainsKey(ForToken))
                        {
                            var additionalValuesForToken = (IDictionary <string, object>)dic[ForToken];
                            foreach (string key in additionalValuesForToken.Keys)
                            {
                                context.AdditionalResponseParameters.Add(key, additionalValuesForToken[key]);
                            }
                        }
                        //else
                        //{
                        //    foreach (string key in dic.Keys)
                        //    {
                        //        context.AdditionalResponseParameters.Add(key, dic[key]);
                        //    }
                        //}
                    }
                }
                catch { }
            }

            return(Task.FromResult <object>(null));
        }
        public async Task<IHttpActionResult> ExternalSignin(SigninExternalTokenBindingModel model)
        {

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

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

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

            bool hasRegistered = user != null;
            ClaimsIdentity identity = null;

            if (hasRegistered)
            {
                if (!user.IsActiveUser)
                {
                    var response = new HttpResponseMessage(HttpStatusCode.Forbidden);

                    response.ReasonPhrase = user.Id;
                    return ResponseMessage(response);
                }

                //var hub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
                //hub.Clients.All.logout(user.Email);

                //var loggedInUsers = NotificationHub._connections.GetConnections(user.Email);
                //if (loggedInUsers.Count() > 0)
                //{
                //    var hub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
                //    foreach (var connectionId in loggedInUsers)
                //    {
                //        hub.Clients.Client(connectionId).logout();
                //    }
                //}

                identity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                identity.AddClaims(claims);
                Authentication.SignIn(identity);
            }
            else
            {
                return NotFound();
            }

            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));
            var 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("isFreeUser", user.IsFreeUser),
                new JProperty("id", user.Id),
                new JProperty("fullName", user.FullName),
                new JProperty("access_token", accessToken),
                new JProperty("token_type", "bearer"),
                new JProperty("showDownloadOption", (user.SubscriptionId == 1)),
                new JProperty("expires_in", TimeSpan.FromDays(365).TotalSeconds.ToString()),
                new JProperty(".issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
                new JProperty(".expires", currentUtc.Add(TimeSpan.FromDays(365)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
            );

            //_Uow._LoggedInTracking.Add(new EF.LoggedInTracking
            //{
            //    DateTimeLoggedIn = DateTime.UtcNow,
            //    Token = accessToken,
            //    UserId = user.Id
            //});
            //await _Uow.CommitAsync();

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

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

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

            bool hasRegistered = user != null;
            ClaimsIdentity identity = null;
            IdentityResult result;

            if (hasRegistered)
            {
                identity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                identity.AddClaims(claims);
                Authentication.SignIn(identity);
                if (user.IsActiveUser)
                {
                    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc = currentUtc;
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));
                    var 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("isFreeUser", user.IsFreeUser),
                        new JProperty("id", user.Id),
                        new JProperty("fullName", user.FullName),
                        new JProperty("access_token", accessToken),
                        new JProperty("token_type", "bearer"),
                        new JProperty("showDownloadOption", (user.SubscriptionId == 1)),
                        new JProperty("expires_in", TimeSpan.FromDays(365).TotalSeconds.ToString()),
                        new JProperty(".issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
                        new JProperty(".expires", currentUtc.Add(TimeSpan.FromDays(365)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
                    );

                    //_Uow._LoggedInTracking.Add(new EF.LoggedInTracking
                    //{
                    //    DateTimeLoggedIn = DateTime.UtcNow,
                    //    Token = accessToken,
                    //    UserId = user.Id
                    //});
                    //await _Uow.CommitAsync();

                    return Ok(user.Id);
                }
            }
            else
            {
                var subscription = await _Uow._Subscription.GetByIdAsync(2);
                user = new ApplicationUser()
                {
                    Id = Guid.NewGuid().ToString(),
                    UserName = model.Email,
                    Email = model.Email,
                    FullName = model.FullName,
                    CountryId = model.CountryId,
                    CreatedOn = DateTime.UtcNow,
                    CurrentViews = 0,
                    IsActiveUser = true,
                    IsAllowMobileVideos = true,
                    IsFilterByIP = false,
                    IsParentalControl = false,
                    IsPasswordReset = false,
                    NoOfConcurentViews = 1,
                    SubscriptionDate = DateTime.UtcNow,
                    SubscriptionId = 2,
                    ExpirationDate = DateTime.UtcNow.AddDays(subscription.TimeDuration.GetValueOrDefault()),
                    Active = true,
                    IsFreeUser = true,
                    IsInstitutionalAccount = false,
                };

                result = await UserManager.CreateAsync(user);
                if (!result.Succeeded)
                {
                    return GetErrorResult(result);
                }

                var info = new ExternalLoginInfo()
                {
                    DefaultUserName = model.Email,
                    Login = new UserLoginInfo(model.Provider, externalLogin.ProviderKey)
                };

                result = await UserManager.AddLoginAsync(user.Id, info.Login);
                if (!result.Succeeded)
                {
                    return GetErrorResult(result);
                }

                identity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                identity.AddClaims(claims);
                //Authentication.SignIn(identity);
            }

            //AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            //var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
            //ticket.Properties.IssuedUtc = currentUtc;
            //ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));
            //var 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("id", user.Id),
            //    new JProperty("fullName", user.FullName),
            //    new JProperty("access_token", accessToken),
            //    new JProperty("token_type", "bearer"),
            //    new JProperty("expires_in", TimeSpan.FromDays(365).TotalSeconds.ToString()),
            //    new JProperty(".issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
            //    new JProperty(".expires", currentUtc.Add(TimeSpan.FromDays(365)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
            //);
            return Ok(user.Id);
        }