Example #1
0
        public object Authenticate(string user, string password)
        {
            if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(password))
            {
                return("failed");
            }
            var userIdentity = UserManager.FindAsync(user, password).Result;

            if (userIdentity == null)
            {
                return("failed");
            }

            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, user));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
            var ticket     = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

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

            return(accessToken);
        }
Example #2
0
        public IHttpActionResult Token(LoginViewModel login)
        {
            if (!ModelState.IsValid)
            {
                return(this.BadRequestError(ModelState));
            }
            ClaimsIdentity identity;

            if (!_loginProvider.ValidateCredentials(login.UserName, login.Password, out identity))
            {
                return(BadRequest("Incorrect user or password"));
            }
            DataSet data = DBConnection.GetQuery(@"SELECT [id],[surname],[name],[middle_name],[email]
                                                FROM[ReportServer].[dbo].[Users]
                                                where[login] = '" + login.UserName + "'");
            var     user = new AccountProfileViewModel {
                id = Convert.ToInt32(data.Tables[0].Rows[0][0]), surname = data.Tables[0].Rows[0][1].ToString(), name = data.Tables[0].Rows[0][2].ToString(), middlename = data.Tables[0].Rows[0][3].ToString(), email = data.Tables[0].Rows[0][4].ToString(), Login = login.UserName
            };
            var ticket     = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(7));
            return(Ok(new LoginAccessViewModel
            {
                User = user,
                AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket)
            }));
        }
Example #3
0
        public async Task <IHttpActionResult> Login(LoginBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            ApplicationUser user = await UserManager.FindAsync(model.Username, model.Password);

            if (user != null)
            {
                var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
                AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                var currentUtc = new SystemClock().UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));
                return
                    (Ok(new BearerTokenModel
                {
                    Token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket),
                    Username = model.Username
                }));
            }
            return(BadRequest("User with specified credentials doesn't exist."));
        }
        public IHttpActionResult Token(LoginViewModel login)
        {
            if (!ModelState.IsValid)
            {
                return(this.BadRequestError(ModelState));
            }

            ClaimsIdentity identity;

            if (!_loginProvider.ValidateCredentials(login.UserName, login.Password, out identity))
            {
                //Log.Debug("Leaving Token(): Incorrect user or password");
                return(BadRequest("Incorrect user or password"));
            }

            var ticket     = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            return(Ok(new LoginAccessViewModel
            {
                UserName = login.UserName,
                AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket)
            }));
        }
Example #5
0
        public async Task <AjaxResponse> Authenticate(LoginModel loginModel)
        {
            CheckModelState();

            var loginResult = await GetLoginResultAsync(
                loginModel.UsernameOrEmailAddress,
                loginModel.Password,
                loginModel.TenancyName
                );

            var ticket     = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(60));
            string token = OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

            LoginResponse response = new LoginResponse();

            response.Id           = loginResult.User.Id;
            response.FirstName    = loginResult.User.Name;
            response.SurName      = loginResult.User.Surname;
            response.EmailAddress = loginResult.User.EmailAddress;
            response.DriverId     = _driverService.GetDriverId(loginResult.User.Id);
            response.Token        = token;

            AjaxResponse ar = new AjaxResponse();

            ar.Result = response;
            return(ar);
        }
        public async Task <AjaxResponse> Authenticate(LoginModel loginModel)
        {
            var loginResult = await GetLoginResultAsync(
                loginModel.UsernameOrEmailAddress,
                loginModel.Password,
                loginModel.TenancyName
                );

            var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());

            var currentUtc = new SystemClock().UtcNow;
            var expiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));



            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = expiresUtc;

            var timeSpan        = expiresUtc - DateTime.UtcNow;
            var expireInSeconds = Convert.ToInt32(timeSpan.TotalSeconds);



            var result = new AuthenticateResultModel
            {
                AccessToken     = OAuthBearerOptions.AccessTokenFormat.Protect(ticket),
                ExpireInSeconds = expireInSeconds
            };


            return(new AjaxResponse(result));
        }
Example #7
0
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];

            string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["as:AudienceSecret"];

            var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);

            var signingKey = new HmacSigningCredentials(keyByteArray);

            var currentUtc = new SystemClock().UtcNow;

            data.Properties.IssuedUtc = currentUtc;

            double expirationTimeMin = double.Parse(ConfigurationManager.AppSettings["ExpirationTimeTokenInMin"]);

            data.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(expirationTimeMin));

            var expires = data.Properties.ExpiresUtc;

            var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, currentUtc.UtcDateTime, expires.Value.UtcDateTime, signingKey);

            var handler = new JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            return(jwt);
        }
Example #8
0
        public async Task <AjaxResponse> Authenticate(LoginModel loginModel)
        {
            var loginResult = await _userManager.LoginAsync(loginModel.UserName, loginModel.Password);

            if (loginResult.Result == AbpLoginResultType.Success)
            {
                var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());

                var currentUtc = new SystemClock().UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(30));
                return(new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)));
            }
            else
            {
                switch (loginResult.Result)
                {
                case AbpLoginResultType.InvalidUserName:
                case AbpLoginResultType.InvalidPassword:
                    throw new UserFriendlyException(L("LoginFailed"), L("InvalidUserNameOrPassword"));

                case AbpLoginResultType.UserIsNotActive:
                    throw new UserFriendlyException(L("LoginFailed"), L("UserIsNotActiveAndCanNotLogin", loginModel.UserName));

                case AbpLoginResultType.EmailIsNotConfirmed:
                    throw new UserFriendlyException(L("LoginFailed"), "Your email address is not confirmed. You can not login"); //TODO: localize message

                default:                                                                                                         //Can not fall to default actually. But other result types can be added in the future and we may forget to handle it
                    Logger.Warn("Unhandled login fail reason: " + loginResult.Result);
                    throw new UserFriendlyException(L("LoginFailed"));
                }
            }
        }
Example #9
0
        public virtual async Task <AjaxResponse> Register(RegisterViewModel model)
        {
            try
            {
                //  CheckSelfRegistrationIsEnabled();
                CurrentUnitOfWork.SetTenantId(null);
                var tenant = await GetActiveTenantAsync(Tenant.DefaultTenantName);

                CurrentUnitOfWork.SetTenantId(tenant.Id);
                //Getting tenant-specific settings
                // var isNewRegisteredUserActiveByDefault = await SettingManager.GetSettingValueForApplicationAsync<bool>(YtSettings.General.UserDefaultActive);
                var user = new User
                {
                    TenantId = tenant.Id,
                    Name     = model.Name,
                    IsActive = true
                };
                if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
                {
                    throw new AbpException("用户名或密码不可为空");
                }
                user.UserName = model.UserName;
                user.Password = new PasswordHasher().HashPassword(model.Password);
                user.Roles    = new List <UserRole>();
                var roles = _roleManager.Roles.Where(r => r.IsDefault).ToList();
                foreach (var defaultRole in roles)
                {
                    user.Roles.Add(new UserRole(tenant.Id, user.Id, defaultRole.Id));
                }

                //  CheckErrors(await _userManager.CreateAsync(user));
                await _userManager.CreateAsync(user);

                await _unitOfWorkManager.Current.SaveChangesAsync();

                if (!user.IsActive)
                {
                    return(new AjaxResponse("用户注册成功,处于禁用状态"));
                }
                AbpLoginResult <Tenant, User>
                loginResult = await GetLoginResultAsync(user.UserName, model.Password, tenant.TenancyName);

                if (loginResult.Result == AbpLoginResultType.Success)
                {
                    var ticket     = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());
                    var currentUtc = new SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc = currentUtc;
                    //有效期1天
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(1));
                    return(new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)));
                }
                Logger.Warn("登陆失败,原因: " + loginResult.Result);
                return(new AjaxResponse("用户注册成功,登陆失败,原因" + loginResult.Result));
            }
            catch (UserFriendlyException ex)
            {
                return(new AjaxResponse(ex.Message));
            }
        }
        public async Task <AjaxResponse> Authenticate(ThirdPartyLoginModel input)
        {
            IThirdPartyAuthService authService;

            switch (input.ThirdParty)
            {
            case ThirdParty.QQ:
                authService = _qqAuthService;
                break;

            case ThirdParty.Weixin:
                authService = _weixinAuthService;
                break;

            case ThirdParty.Weibo:
                authService = _weiboAuthService;
                break;

            case ThirdParty.Alipay:
                authService = _alipayAuthService;
                break;

            default:
                throw new UserFriendlyException("不支持您所选的登录平台");
            }
            //var codeCache = _cacheManager.GetCache("ThirdPartyAuthCodes");
            //var codeStatus = codeCache.GetOrDefault(input.Code);
            //if (codeStatus != null)
            //{
            //    throw new UserFriendlyException("认证信息已失效,请您重试第三方登录认证");
            //}

            //codeCache.Set(input.Code, input.Code, TimeSpan.FromMinutes(5));

            var authorizeResult = authService.Authorize(new AuthorizationInput {
                Code = input.Code
            });

            if (authorizeResult.Success)
            {
                var user = await _userManager.FindByIdAsync(authorizeResult.ThirdPartyUser.UserId);



                var identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalBearer);

                var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());

                var currentUtc = new SystemClock().UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(3));

                return(new AjaxResponse(AccountController.OAuthBearerOptions.AccessTokenFormat.Protect(ticket)));
            }
            return(new AjaxResponse(authorizeResult));
        }
        private AuthenticationTicket GetTicketByLoginResult(AbpLoginResult <Tenant, User> loginResult)
        {
            var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());

            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
            return(ticket);
        }
Example #12
0
        public static string Token(ClaimsIdentity identity)
        {
            var ticket     = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(120));
            var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

            return(token);
        }
Example #13
0
        public static string GenerateToken(AppUserManager userManager, AppUser user)
        {
            ClaimsIdentity identity = userManager.CreateIdentity(user, Startup.OAuthBearerOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(700));
            return(Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket));
        }
Example #14
0
        public JsonResult Login()
        {
            IList <Claim> claims = new List <Claim>();

            claims.Add(new Claim(ClaimTypes.Name, "llm"));
            claims.Add(new Claim(ClaimTypes.NameIdentifier, "123"));
            ClaimsIdentity indentity  = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
            var            ticket     = new AuthenticationTicket(indentity, new AuthenticationProperties());
            var            currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
            return(Json(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)));
        }
        public IHttpActionResult Token(LoginViewModel login)
        {
            Log.DebugFormat("Entering Token(): User={0}", login.UserName);

            if (!ModelState.IsValid)
            {
                Log.Debug("Leaving Token(): Bad request");
                return(this.BadRequestError(ModelState));
            }

            ClaimsIdentity identity;
            string         userNameClean = login.UserName.Contains("\\") ? login.UserName.Substring(login.UserName.IndexOf("\\") + 1).ToLower() : login.UserName.ToLower();
            bool           addUser       = !Repository.Query <User>().Any(u => u.Username == userNameClean);

            if (!_loginProvider.ValidateCredentials(userNameClean, login.Password, out identity))
            {
                Log.Debug("Leaving Token(): Incorrect user or password");
                return(BadRequest("Incorrect user or password"));
            }

            User user;

            if (addUser)
            {
                //add user to the database because it doesn't exist
                user = _loginProvider.CreateUser(userNameClean);
                Repository.Add <User>(user);
                Repository.SaveChangesAsync();
            }
            else
            {
                user = Repository.Query <User>().Single(u => u.Username == userNameClean);
            }

            var ticket     = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(60));

            Log.Debug("Leaving Token()");

            return(Ok(new LoginAccessViewModel
            {
                UserName = userNameClean,
                AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket),
                UserPicture = user.Picture
            }));
        }
        /// <summary>
        /// Get authentication ticket to generate access token.
        /// </summary>
        /// <param name="familyId">The family identifier.</param>
        /// <param name="familyMemberId">The family member identifier.</param>
        /// <param name="memberType">The member type.</param>
        /// <returns>The authentication ticket.</returns>
        private string GetAccessToken(int familyId, int familyMemberId, MemberType memberType)
        {
            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);

            identity.AddClaim(new Claim("FamilyID", (familyId == 0) ? string.Empty : familyId.ToString()));
            identity.AddClaim(new Claim("MemberID", (familyMemberId == 0) ? string.Empty : familyMemberId.ToString()));
            identity.AddClaim(new Claim("MemberType", ((int)memberType).ToString()));

            var authenticationTicket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc           = new SystemClock().UtcNow;

            authenticationTicket.Properties.IssuedUtc  = currentUtc;
            authenticationTicket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(2));
            return(Startup.OAuthBearerOptions.AccessTokenFormat.Protect(authenticationTicket));
        }
Example #17
0
        /// <summary>
        /// User Signin
        /// </summary>
        /// <param name="user">User Email</param>
        /// <param name="options">Authentication Type</param>
        /// <param name="authManager">Authentication Manager</param>
        /// <returns></returns>
        public string SignIn(UserAuthenticateRequest user, OAuthAuthorizationServerOptions options, IAuthenticationManager authManager)
        {
            ClaimsIdentity identity = new ClaimsIdentity(options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Email, user.Username));
            identity.AddClaim(new Claim("UserID", user.UserID.ToString()));
            identity.AddClaim(new Claim("StudyID", user.StudyID));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(60));
            authManager.SignIn(identity);
            return(options.AccessTokenFormat.Protect(ticket));
        }
Example #18
0
        private string GetToken(AbpLoginResult <Tenant, User> loginResult)
        {
            if (loginResult.Result != AbpLoginResultType.Success)
            {
                throw new UserFriendlyException("登录或注册失败。结果:" + loginResult.Result);
            }

            var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());

            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            return(OAuthBearerOptions.AccessTokenFormat.Protect(ticket));
        }
Example #19
0
        public async Task <AjaxResponse> Authenticate(LoginModel loginModel)
        {
            var loginResult = await GetLoginResultAsync(
                loginModel.UsernameOrEmailAddress,
                loginModel.Password,
                string.Empty
                );

            var ticket     = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc = currentUtc;
            //有效期1天
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(1));
            return(new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)));
        }
Example #20
0
        public async Task <IHttpActionResult> Login(UTRGVCredentials login)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            ClaimsIdentity identity;
            string         cn;
            bool           authorized = false;

            if (!_loginProvider.ValidateCredentials(login.email, login.password, out cn, out authorized))
            {
                return(BadRequest("Incorrect user or password"));
            }
            if (!authorized)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You're not authorized")));
            }

            //set the identity values
            identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, cn));

            var dbUser = await db.Users.Where(u => u.Cn == cn).FirstOrDefaultAsync();

            if (dbUser != null)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, dbUser.Role.Name));
            }
            else
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "Faculty"));
            }



            var duration   = int.Parse(_sessionDuration);
            var ticket     = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(duration));



            return(Ok(Startup.OAuthOptions.AccessTokenFormat.Protect(ticket)));
        }
Example #21
0
        public ObjectContent <object> GetAccountTicket(User client)
        {
            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, client.UserName));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
            return(new ObjectContent <object>(new
            {
                UserName = client.UserName,
                AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket),
                Expires = ticket.Properties.ExpiresUtc
            }, Configuration.Formatters.JsonFormatter));
        }
        private static string GetAuthToken(User user)
        {
            var identity = new ClaimsIdentity(OwinConfig.OAuthBearerOptions.AuthenticationType);

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

            var currentUtc = new SystemClock().UtcNow;
            var ticket     = new AuthenticationTicket(identity, new AuthenticationProperties());

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            string token = OwinConfig.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

            return(token);
        }
        public static string GenerateAccessToken(this User user)
        {
            var identity = new ClaimsIdentity(AuthConfig.OAuthBearerOptions.AuthenticationType);

            identity.AddClaims(user);

            var currentUtc = new SystemClock().UtcNow;

            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(30));

            string token = AuthConfig.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

            return(token);
        }
Example #24
0
        public async Task <AjaxResponse> Authenticate(LoginForSmsCode input)
        {
            _smsManager.ValidateVerificationCode(input.PhoneNumber, input.Code);
            var user = _userManager.Users.Single(x => x.PhoneNumber == input.PhoneNumber);


            var identity = await _userManager.CreateIdentityAsync(user, "SmsLogin");

            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());

            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(3));

            return(new AjaxResponse(AccountController.OAuthBearerOptions.AccessTokenFormat.Protect(ticket)));
        }
Example #25
0
        public static string IssueToken(string userId)
        {
            var identity = new ClaimsIdentity(_bearerOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, userId));

            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());

            var now = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = now;
            ticket.Properties.ExpiresUtc = now.Add(_serverOptions.AccessTokenExpireTimeSpan);

            var token = _bearerOptions.AccessTokenFormat.Protect(ticket);

            return(token);
        }
Example #26
0
        public async Task<AjaxResponse> Authenticate(LoginModel loginModel)
        {
            CheckModelState();

            var loginResult = await GetLoginResultAsync(
                loginModel.UsernameOrEmailAddress,
                loginModel.Password,
                loginModel.TenancyName
                );

            var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());

            var currentUtc = new SystemClock().UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            return new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket));
        }
Example #27
0
        public async Task <AjaxResponse> Authenticate(LoginUser model)
        {
            SysLoginResult <UserInfo> result = await _userInfoAppService.LoginAuth(model);

            if (string.IsNullOrEmpty(model.UserNameCn))
            {
                _userInfoAppService.SetAuthenticationProperties(model, result);
            }

            var ticket = new AuthenticationTicket(result.Identity, new AuthenticationProperties());

            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(ConstantConfig.WebApiExpires));

            return(new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)));
        }
Example #28
0
        public async Task <AjaxResponse> Authenticate(LoginModel loginModel)
        {
            CheckModelState();
            //_captchaManager.CheckCaptcha(loginModel.Captcha);

            var loginResult = await GetLoginResultAsync(
                loginModel.UsernameOrEmailAddress,
                loginModel.Password,
                "Default"
                );

            var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());

            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(loginModel.RememberMe ? TimeSpan.FromDays(3) : TimeSpan.FromMinutes(30));

            return(new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)));
        }
Example #29
0
        public async Task <IHttpActionResult> PostAuth([FromBody] dynamic postBody)
        {
            string uname    = postBody.userName.Value;
            string password = postBody.userPassword.Value;

            if (string.IsNullOrEmpty(uname) || string.IsNullOrEmpty(password))
            {
                return(BadRequest("Invalid username/password"));
            }

            var accountAuthorized = new Tuple <Guid, bool>(Guid.NewGuid(), true); //await _accountRepo.IsAuthorized(uname, password);

            if (!accountAuthorized.Item2)
            {
                return(Unauthorized());
            }

            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, uname));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Common.ServiceApiKey));
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc     = new SystemClock().UtcNow;
            var expiresIn      = ApiCallContext == ApiCallerContext.MobileApp ? TimeSpan.FromDays(1) : TimeSpan.FromMinutes(30);
            var expiresSeconds = expiresIn.TotalSeconds;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(expiresIn);

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

            return(Ok(JObject.FromObject(new {
                access_token = accessToken,
                token_type = "bearer",
                expires_in = expiresSeconds,
                expires_utc = ticket.Properties.ExpiresUtc.ToString(),
                user_name = uname,
                id = accountAuthorized.Item1.ToString(),
                scope = ApiCallerContext.MobileApp.ToString()
            })));
        }
Example #30
0
        public IHttpActionResult Token(RbacRegisterUser login)
        {
            ClaimsIdentity identity;

            if (!new ActiveDirectoryUserLoginProvider("Microsoft").ValidateCredentials(login.UserName, login.Password, out identity))
            {
                return(BadRequest("Incorrect user or password"));
            }

            var ticket     = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            return(Ok(new LoginAccessViewModel
            {
                UserName = login.UserName,
                AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket)
            }));
        }