예제 #1
0
        public static void UpdateClaim(this ClaimsPrincipal principal, String type, String value)
        {
            ClaimsIdentity?identity = (ClaimsIdentity?)principal.Identity;

            identity?.TryRemoveClaim(identity.FindFirst(type));
            identity?.AddClaim(new Claim(type, value));
        }
 private static void AddClaim(ClaimsIdentity claimsIdentity, string claimName, string claimValue)
 {
     if (claimValue != null)
     {
         claimsIdentity?.AddClaim(new Claim(claimName, claimValue));
     }
 }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                _panelRepository = Bootstrapper.WindsorContainer.Resolve <IPanelRepository>();
                string deviceId      = context.OwinContext.Get <string>("as:device_id");
                var    allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");
                if (allowedOrigin == null)
                {
                    allowedOrigin = "*";
                }
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

                var client = _repository.FindClient(context.ClientId);
                if (client == null)
                {
                    context.SetError("invalid_clientId", $"Client '{context.ClientId}' is not registered in the system.");
                    return;
                }
                if (client.ApplicationType == ApplicationType.JavaScript)
                {
                    var user = await _panelRepository.FindUser(context.UserName, context.Password);

                    if (user == null)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }
                    var roles = await _panelRepository.GetUserRoles(user);

                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identity.AddClaim(new Claim("FirstName", user.FirstName));
                    identity.AddClaim(new Claim("LastName", user.LastName));
                    identity.AddClaim(new Claim("UserId", user.Id));
                    foreach (var role in roles)
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, role));
                    }
                    var props = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "as:client_id", context.ClientId ?? string.Empty
                        },
                        {
                            "userId", user.Id
                        },
                        {
                            "firstName", user.FirstName
                        },
                        {
                            "lastName", user.LastName
                        }
                    });
                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);
                }
                else if (client.ApplicationType == ApplicationType.CustomerUserApp || client.ApplicationType == ApplicationType.ShopUserApp)
                {
                    var appUser  = _userManager.Users.SingleOrDefault(item => item.PhoneNumber == context.UserName);
                    var rolesApp = await _repository.GetUserRoles(appUser);

                    if (appUser == null)
                    {
                        context.SetError("invalid_grant", "کاربر یافت نشد");
                        return;
                    }

                    switch (client.ApplicationType)
                    {
                    case ApplicationType.CustomerUserApp:
                    {
                        if (!appUser.CustomerIsActive)
                        {
                            context.SetError("invalid_grant", "کاربر غیرفعال می باشد");
                        }
                        break;
                    }

                    case ApplicationType.ShopUserApp:
                    {
                        if (!appUser.ShopIsActive)
                        {
                            context.SetError("invalid_grant", "کاربر غیرفعال می باشد");
                        }
                        break;
                    }
                    }

                    await VerifyPhoneNumber(appUser, context.Password, context.UserName);

                    var identityApp = new ClaimsIdentity(context.Options.AuthenticationType);
                    identityApp.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identityApp.AddClaim(new Claim("UserId", appUser.Id));
                    identityApp.AddClaim(new Claim("MobileNumber", appUser.PhoneNumber));
                    identityApp.AddClaim(new Claim("DeviceId", deviceId));
                    identityApp.AddClaim(new Claim("ShopIsActive", appUser.ShopIsActive.ToString()));
                    identityApp.AddClaim(new Claim("CustomerIsActive", appUser.CustomerIsActive.ToString()));
                    identityApp.AddClaim(new Claim("RegisterDate", appUser.RegisterDate.ToString()));
                    foreach (var role in rolesApp)
                    {
                        identityApp.AddClaim(new Claim(ClaimTypes.Role, role));
                    }
                    var appProps = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            "as:client_id", context.ClientId ?? string.Empty
                        },
                        {
                            "userId", appUser.Id
                        },
                        {
                            "mobileNumber", appUser.PhoneNumber
                        }
                    });
                    var appTicket = new AuthenticationTicket(identityApp, appProps);
                    context.Validated(appTicket);
                }
            }
            catch (Exception e)
            {
                context.SetError("invalid_grant", e.Message);
            }
        }
 public static void SetUserLogin(this ClaimsIdentity identity, string login)
 {
     identity?.AddClaim(new Claim(UserLoginClaimType, login));
 }
        private string GetOpenId(ActionExecutingContext filterContext)
        {
            //var objLoginInfo = Session["UserInfo"] as WechatUser;

            //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo : " + (objLoginInfo == null?"NULL":objLoginInfo.wechatUserID));
            ////判断用户是否为空
            //if (objLoginInfo == null)
            {
                //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo is null");
                if (HttpContext.Request.IsAuthenticated)
                {
                    LogManager.GetLogger(this.GetType()).Debug("HttpContext.Request.IsAuthenticated");
                    if (Request.UserAgent.IndexOf("MicroMessenger") >= 0)
                    {
                        LogManager.GetLogger(this.GetType()).Debug("WeChat Browser");
                        var windowsIdentity = User.Identity;
                        if (windowsIdentity != null)
                        {
                            return(windowsIdentity.Name);
                        }
                        else
                        {
                            return(string.Empty);
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request["Ticket"]))
                    {
                        var ticket = Request["Ticket"];
                        Session["Ticket"] = ticket;



                        string enTicket = EncryptionHelper.DecodeFrom64(ticket);
                        enTicket = DesHelper.Decrypt(enTicket, WebConfigurationManager.AppSettings["EncryptKey"]);

                        var openid = enTicket.Split('|')[0];

                        //登录
                        ClaimsIdentity claimsIdentity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
                        claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, openid, "http://www.w3.org/2001/XMLSchema#string"));
                        claimsIdentity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, openid, "http://www.w3.org/2001/XMLSchema#string"));
                        claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"));

                        HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
                        {
                            IsPersistent = false
                        }, claimsIdentity);

                        //
                    }
                    else if (Session["Ticket"] == null)
                    {
                        var strUrl = WebConfigurationManager.AppSettings["OAuthUrl"];

                        filterContext.Result = new RedirectResult(strUrl + Server.UrlEncode(EncryptionHelper.ConvertBase64(Request.Url.ToString())));
                    }



                    //    LogManager.GetLogger(this.GetType()).Debug("SessionId:" + Session.SessionID);
                    //    Session["ReturnUrlMP"] = Request.Url.ToString();

                    //    string strRet = WebConfigurationManager.AppSettings["UserBackUrlMP"];
                    //    // string AppId = Request["AppId"];


                    //    string strwechatid = Request["wechatid"];

                    //    string strBackUrl = string.Format("{0}?wechatid={1}", strRet, strwechatid);

                    //    LogManager.GetLogger(this.GetType()).Debug("UrlStart:" + strBackUrl);

                    //   // var weChatConfig = WeChatCommonService.GetWeChatConfigByID(int.Parse(strwechatid));


                    //    LogManager.GetLogger(this.GetType()).Debug("UrlStart");
                    //    string strUrl = OAuthApi.GetAuthorizeUrl("wx2a3f5167603c5caf", strBackUrl, "About", Innocellence.Weixin.MP.OAuthScope.snsapi_base);
                    //    LogManager.GetLogger(this.GetType()).Debug(strUrl);

                    //    if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                    //    {
                    //        AjaxResult<int> result = new AjaxResult<int>();
                    //        result.Message = new JsonMessage((int)HttpStatusCode.Unauthorized, strUrl);
                    //        filterContext.Result = Json(result, JsonRequestBehavior.AllowGet);

                    //    }
                    //    else
                    //    {
                    //        LogManager.GetLogger(this.GetType()).Debug("filterContext.Result = new RedirectResult(strUrl)");
                    //        filterContext.Result = new RedirectResult(strUrl);
                    //    }
                    //    return string.Empty;
                }
            }
            return(string.Empty);
        }
예제 #6
0
        public async Task <IActionResult> SaveActiveProfile([FromBody] AccountProfileViewModel vm = null)
        {
            Account activeAccount = null;
            string  fullName      = null;

            AccountToken toSend = null;

            List <IdentityModel> toSave = null;

            Exception ex1 = null, ex2 = null;

            ClaimsIdentity claimsIdentity = null;

            try
            {
                if (vm == null)
                {
                    throw new NullReferenceException();
                }


                if (!string.IsNullOrEmpty(vm.Email) &&
                    !Helper.IsEmailValid(vm.Email))
                {
                    throw new ExceptionID(MessageIdentifier.INVALID_EMAIL);
                }


                activeAccount = _dbi.GetActiveAccount();

                if (activeAccount == null ||
                    activeAccount.UID != vm.UID)
                {
                    throw new NullReferenceException();
                }


                toSave = new List <IdentityModel>();

                if (!string.IsNullOrEmpty(vm.Email) &&
                    activeAccount.GetEmailValue()?.ToLower() != vm.Email.ToLower())
                {
                    string emailValue = activeAccount.GetEmailValue();

                    if (Helper.IsEmailValid(emailValue))
                    {
                        toSave.AddRange(from t in activeAccount.AccountTokens
                                        where t.Type == AccountTokenType.EmailChange
                                        select t.SetRecordState(RecordState.Deleted));
                    }

                    toSend = new AccountToken()
                    {
                        RecordState     = RecordState.Added,
                        Value           = _dbi.GenerateTokenValue(),
                        Type            = AccountTokenType.EmailChange,
                        EmailSentStatus = EmailSatus.NotSent,
                        AddData         = vm.Email,
                        Account_Id      = activeAccount.ID
                    };

                    activeAccount.RegisterForRecordStateChange();
                    activeAccount.Email          = activeAccount.UID;
                    activeAccount.EmailConfirmed = false;
                    activeAccount.UnregisterForRecordStateChange();
                }


                activeAccount.RegisterForRecordStateChange();

                activeAccount.AccountName = vm.AccountName;
                activeAccount.FName       = vm.FName;
                activeAccount.LName       = vm.LName;

                activeAccount.UnregisterForRecordStateChange();



                if (activeAccount.RecordState != RecordState.None)
                {
                    toSave.Add(activeAccount);
                }

                if (toSend == null)
                {
                    if (toSave.Count > 0)
                    {
                        _dbi.ManageIdentityModels(toSave.ToArray());
                    }
                }
                else
                {
                    await Task.WhenAll(
                        Helper.GetFunc(() =>
                    {
                        try
                        {
                            if (toSave.Count > 0)
                            {
                                _dbi.ManageIdentityModels(toSave.ToArray());
                            }
                        }
                        catch (Exception ex)
                        {
                            ex1 = ex;
                        }

                        return(Task.CompletedTask);
                    })(),
                        Helper.GetFunc(() =>
                    {
                        try
                        {
                            toSend = _dbi.ManageModel(toSend);
                        }
                        catch (Exception ex)
                        {
                            ex2 = ex;
                        }

                        return(Task.CompletedTask);
                    })());

                    if (ex1 != null)
                    {
                        throw ex1;
                    }
                    if (ex2 != null)
                    {
                        throw ex2;
                    }


                    string lang = this.GetSelectedLanguage();

                    using (var mailService = this.GetMailService())
                    {
                        await Task.WhenAll(
                            Helper.GetFunc(() =>
                        {
                            try
                            {
                                toSend.RegisterForRecordStateChange();
                                toSend.EmailSentStatus = EmailSatus.Sending;
                                toSend.UnregisterForRecordStateChange();

                                if (toSend.RecordState != RecordState.None)
                                {
                                    toSend = _dbi.ManageModel(toSend);
                                }
                            }
                            catch (Exception ex)
                            {
                                ex1 = ex;
                            }

                            return(Task.CompletedTask);
                        })(),
                            Helper.GetFunc(async() =>
                        {
                            string link = null;

                            try
                            {
                                link  = Url.Action("xxXxx", "confirmemail", null, this.Request.Scheme);
                                link += (link.EndsWith("/") ? "" : "/") + toSend.Value;

                                link = link.Replace("/xxXxx/", "/");

                                await mailService.SendEmailAsync(
                                    $"{LanguageManager.GetLabel("AppTitle", lang)} {LanguageManager.GetLabel("lbl_CnfrmEmailAddr", lang)}",
                                    LanguageManager.GetOther("email_ChngEmail", lang)
                                    .Replace("{1}", LanguageManager.GetLabel("AppTitle", lang))
                                    .Replace("{2}", link),
                                    toEmail: toSend.AddData,
                                    fromName: LanguageManager.GetLabel("AppTitle", lang),
                                    replyToEmail: "*****@*****.**",
                                    replyToName: "NO REPLY");
                            }
                            catch (Exception ex)
                            {
                                ex2 = new ExceptionID(MessageIdentifier.INVALID_EMAIL, ex, false);
                            }
                            finally
                            {
                                link = null;
                            }
                        })());

                        if (ex1 != null)
                        {
                            throw ex1;
                        }
                        if (ex2 != null)
                        {
                            _dbi.ManageModel(toSend.SetRecordState(RecordState.Deleted));

                            throw ex2;
                        }

                        toSend.RegisterForRecordStateChange();
                        toSend.EmailSentStatus = EmailSatus.Sent;
                        toSend.UnregisterForRecordStateChange();

                        if (toSend.RecordState != RecordState.None)
                        {
                            toSend = _dbi.ManageModel(toSend);
                        }
                    }
                }


                fullName = DbInteractor.GetAccountFullName(activeAccount);

                claimsIdentity = new ClaimsIdentity(BaseController.APP_ID);
                claimsIdentity.AddClaims(this.User.Claims.Where(l => l.Type != USER_FULL_NAME));

                claimsIdentity.AddClaim(new Claim(USER_FULL_NAME, fullName));

                if (GetRememberUser(this.User))
                {
                    await this.HttpContext.Authentication.SignInAsync(
                        BaseController.APP_ID,
                        new ClaimsPrincipal(claimsIdentity),
                        new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   = GetClaimExpDate(this.User)
                    });
                }
                else
                {
                    await this.HttpContext.Authentication.SignInAsync(BaseController.APP_ID, new ClaimsPrincipal(claimsIdentity));
                }

                return(Json(new { Ok = true, FullName = fullName, profile = this.GetActiveProfileViewModel() }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
            finally
            {
                activeAccount  = null;
                claimsIdentity = null;

                toSave?.Clear();
                toSave = null;
            }
        }
예제 #7
0
        public async Task <IActionResult> SignIn([FromBody] LoginViewModel vm)
        {
            object result = null;

            string refreshTokenValue = null;
            string accessTokenValue  = null;
            bool   invalidPassword   = false;
            string fullName          = null;

            ClaimsIdentity claimsIdentity        = null;
            int            refreshExpValueInSecs = 0;

            Exception ex1 = null, ex2 = null;

            try
            {
                if (vm == null)
                {
                    throw new NullReferenceException(nameof(vm));
                }


                await Task.WhenAll(
                    Helper.GetFunc(async() =>
                {
                    try
                    {
                        result = await _dbi.SignIn(vm.User, vm.Password, TokenClientType.WebApp);
                    }
                    catch (Exception ex)
                    {
                        ex1 = ex;
                    }
                })(),
                    Helper.GetFunc(() =>
                {
                    try
                    {
                        refreshExpValueInSecs = _dbi.GetSysParDetailValue("TokenParams", "RefreshTokenLifeSpan")?.IntVal ?? 0;

                        if (refreshExpValueInSecs <= 0)
                        {
                            throw new ExceptionID(MessageIdentifier.TOKEN_SYS_PARS_NOT_FOUND);
                        }
                    }
                    catch (Exception ex)
                    {
                        ex2 = ex;
                    }

                    return(Task.CompletedTask);
                })());

                if (ex1 != null)
                {
                    throw ex1;
                }
                if (ex2 != null)
                {
                    throw ex2;
                }


                refreshTokenValue = result.GetPropVal <string>("r");
                accessTokenValue  = result.GetPropVal <string>("a");
                invalidPassword   = result.GetPropVal <bool>("i");
                fullName          = result.GetPropVal <string>("fn");

                claimsIdentity = new ClaimsIdentity(BaseController.APP_ID);
                claimsIdentity.AddClaims(new Claim[]
                {
                    new Claim(REFRESH_TOKEN_KEY, refreshTokenValue),
                    new Claim(ACCESS_TOKEN_KEY, accessTokenValue),
                    new Claim(REMEMBER_USER, vm.Remember.ToString()),
                    new Claim(PASSWORD_FORMAT_INVALID, invalidPassword.ToString()),
                    new Claim(USER_FULL_NAME, fullName),
                });

                if (vm.Remember)
                {
                    claimsIdentity.AddClaim(
                        new Claim(REFRESH_TOKEN_EXP_DATE_KEY, Helper.JSonSerializeObject(DateTimeOffset.UtcNow.AddSeconds(refreshExpValueInSecs))));

                    await HttpContext.Authentication.SignInAsync(
                        BaseController.APP_ID,
                        new ClaimsPrincipal(claimsIdentity),
                        new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   = DateTimeOffset.UtcNow.AddSeconds(refreshExpValueInSecs)
                    });
                }
                else
                {
                    await HttpContext.Authentication.SignInAsync(BaseController.APP_ID, new ClaimsPrincipal(claimsIdentity));
                }

                return(Json(new
                {
                    Ok = true,
                    FullName = fullName,
                    Email = (_dbi?.LoginConnectionToken?.Email == _dbi?.LoginConnectionToken?.Uid ? "" : _dbi?.LoginConnectionToken?.Email),
                    Gender = _dbi?.LoginConnectionToken?.Gender
                }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
            finally
            {
                vm                = null;
                result            = null;
                refreshTokenValue = null;
                accessTokenValue  = null;
                invalidPassword   = false;
                fullName          = null;
            }
        }
예제 #8
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var authentication = HttpContext.Current.GetOwinContext().Authentication;

            if (IsAuthenticationNotPermitted())
            {
                Rock.Security.Authorization.SignOut();
                authentication.SignOut("OAuth");
                authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                NavigateToLinkedPage(AttributeKeys.RejectedAuthenticationPage);
                return;
            }

            var    ticket   = authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie).Result;
            var    identity = ticket != null ? ticket.Identity : null;
            string userName = null;

            string[] authorizedScopes = null;
            var      scopes           = (Request.QueryString.Get("scope") ?? "").Split(' ');
            bool     scopesApproved   = false;

            //The user is logged in but does not have OAuth identity
            if (CurrentUser != null && identity == null)
            {
                CreateOAuthIdentity(authentication);
                Response.Redirect(Request.RawUrl, true);
            }
            //The user is not logged in and does not have OAuth identity
            else if (identity == null)
            {
                authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);
                //Send them off to log in
                StoreQueryStringCookie();
                Response.Redirect(OAuthSettings["OAuthLoginPath"], true);
            }
            //The user has an OAuth identity
            else
            {
                OAuthContext  context       = new OAuthContext();
                ClientService clientService = new ClientService(context);
                Client        OAuthClient   = clientService.GetByApiKey(PageParameter(PageParameterKeys.ClientId).AsGuid());
                if (OAuthClient != null)
                {
                    ClientScopeService clientScopeService = new ClientScopeService(context);

                    userName = identity.Name;
                    AuthorizationService authorizationService = new AuthorizationService(context);

                    authorizedScopes = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLogin.UserName == identity.Name && a.Active == true).Select(a => a.Scope.Identifier).ToArray <string>();
                    if (!clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Any() ||
                        (authorizedScopes != null && scopes.Where(s => !authorizedScopes.Select(a => a.ToLower()).Contains(s.ToLower())).Count() == 0))
                    {
                        scopesApproved = true;
                    }

                    if (scopesApproved)
                    {
                        identity = new ClaimsIdentity(identity.Claims, "Bearer", identity.NameClaimType, identity.RoleClaimType);

                        //only allow claims that have been requested and the client has been authorized for
                        foreach (var scope in scopes.Where(s => clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope.Identifier.ToLower()).Contains(s.ToLower())))
                        {
                            identity.AddClaim(new Claim("urn:oauth:scope", scope));
                        }
                        authentication.SignIn(identity);
                    }
                    else
                    {
                        rptScopes.DataSource = clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(s => s.Scope).ToList();
                        rptScopes.DataBind();
                    }

                    lClientName.Text     = OAuthClient.ClientName;
                    lClientName2.Text    = OAuthClient.ClientName;
                    lUsername.Text       = CurrentUser.Person.FullName + " (" + userName + ")";
                    hlLogout.NavigateUrl = Request.RawUrl + "&OAuthLogout=true";
                }
                else
                {
                    throw new Exception("Invalid Client ID for OAuth authentication.");
                }
            }
        }
예제 #9
0
            public static async Task <ExternalLoginData> FromToken(string provider, string accessToken)
            {
                ExternalLoginData loginData = null;

                using (var client = new HttpClient())
                {
                    var verifyTokenEndPoint       = GetUserProfileEndPoint(provider, accessToken);
                    var verifyTokenPicturendPoint = GetUserProfilePictureEndPoint(provider, accessToken);
                    var verifyAppEndpoint         = GetAppProfileEndPoint(provider, accessToken);

                    if (verifyTokenEndPoint == null || verifyAppEndpoint == null)
                    {
                        return(null);
                    }

                    Uri uri = new Uri(verifyTokenEndPoint);
                    using (HttpResponseMessage response = await client.GetAsync(uri))
                    {
                        ClaimsIdentity identity = null;

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

                            dynamic iObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(content);
                            loginData = FromJObject(iObj);
                            if (loginData == null)
                            {
                                return(null);
                            }
                            using (var profilePictureResponse = await client.GetAsync(verifyTokenPicturendPoint))
                            {
                                if (profilePictureResponse.IsSuccessStatusCode)
                                {
                                    var appContent = await profilePictureResponse.Content.ReadAsStringAsync();

                                    dynamic profilePictureContent = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(appContent);
                                    loginData.ProfilePicture = profilePictureContent["data"]["url"] ?? "";
                                }
                            }

                            identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

                            if (provider == "Facebook")
                            {
                                uri = new Uri(verifyAppEndpoint);
                                using (var appResonse = await client.GetAsync(uri))
                                {
                                    var appContent = await appResonse.Content.ReadAsStringAsync();

                                    dynamic appObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(appContent);

                                    if (appObj["id"] != Startup.FacebookAuthOptions.AppId)
                                    {
                                        return(null);
                                    }
                                    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, iObj["id"].ToString(),
                                                                ClaimValueTypes.String, "Facebook", "Facebook"));
                                }
                            }
                        }
                        Claim providerKeyClaim = identity?.FindFirst(ClaimTypes.NameIdentifier);

                        if (string.IsNullOrEmpty(providerKeyClaim?.Issuer) ||
                            string.IsNullOrEmpty(providerKeyClaim.Value))
                        {
                            return(null);
                        }

                        if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
                        {
                            return(null);
                        }
                        loginData.LoginProvider = provider;
                        loginData.UserName      = loginData.Email;
                        return(loginData);
                    }
                }
            }
예제 #10
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));
        }
        public async Task <IActionResult> Accept(CancellationToken cancellationToken)
        {
            var response = HttpContext.GetOpenIdConnectResponse();

            if (response != null)
            {
                return(View("Error", response));
            }

            var request = HttpContext.GetOpenIdConnectRequest();

            if (request == null)
            {
                return(View("Error", new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.ServerError,
                    ErrorDescription = "An internal error has occurred."
                }));
            }

            // Create a new ClaimsIdentity containing the claims that
            // will be used to create an id_token, a token or a code.
            var identity = new ClaimsIdentity(
                OpenIdConnectServerDefaults.AuthenticationScheme,
                OpenIdConnectConstants.Claims.Name,
                OpenIdConnectConstants.Claims.Role);

            // Note: the "sub" claim is mandatory and an exception is thrown if this claim is missing.
            identity.AddClaim(
                new Claim(OpenIdConnectConstants.Claims.Subject, User.FindFirst(ClaimTypes.NameIdentifier).Value)
                .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                 OpenIdConnectConstants.Destinations.IdentityToken));

            identity.AddClaim(
                new Claim(OpenIdConnectConstants.Claims.Name, User.FindFirst(ClaimTypes.Name).Value)
                .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                 OpenIdConnectConstants.Destinations.IdentityToken));

            var application = await GetApplicationAsync(request.ClientId, cancellationToken);

            if (application == null)
            {
                return(View("Error", new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription = "The specified client identifier is invalid."
                }));
            }

            // Create a new authentication ticket holding the user identity.
            var ticket = new AuthenticationTicket(
                new ClaimsPrincipal(identity),
                new AuthenticationProperties(),
                OpenIdConnectServerDefaults.AuthenticationScheme);

            // Set the list of scopes granted to the client application.
            // Note: this sample always grants the "openid", "email" and "profile" scopes
            // when they are requested by the client application: a real world application
            // would probably display a form allowing to select the scopes to grant.
            ticket.SetScopes(new[]
            {
                /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
                /* email: */ OpenIdConnectConstants.Scopes.Email,
                /* profile: */ OpenIdConnectConstants.Scopes.Profile,
                /* offline_access: */ OpenIdConnectConstants.Scopes.OfflineAccess
            }.Intersect(request.GetScopes()));

            // Set the resources servers the access token should be issued for.
            ticket.SetResources("resource_server");

            // Returning a SignInResult will ask ASOS to serialize the specified identity to build appropriate tokens.
            return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
        }
예제 #12
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            if (ModelState.IsValid)
            {
                if (_marvinUserRepository.AreUserCredentialsValid(model.Username, model.Password))
                {
                    var user = _marvinUserRepository.GetUserByUsername(model.Username);

                    var id = new ClaimsIdentity();
                    id.AddClaim(new Claim(JwtClaimTypes.Subject, user.SubjectId));

                    await HttpContext.Authentication.SignInAsync("idsrv.2FA", new ClaimsPrincipal(id));

                    // send code...

                    var redirectToAdditionalFactorUrl =
                        Url.Action("AdditionalAuthenticationFactor",
                                   new
                    {
                        returnUrl     = model.ReturnUrl,
                        rememberLogin = model.RememberLogin
                    });

                    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(redirectToAdditionalFactorUrl));
                    }

                    return(Redirect("~/"));

                    //AuthenticationProperties props = null;
                    //// only set explicit expiration here if persistent.
                    //// otherwise we reply upon expiration configured in cookie middleware.
                    //if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    //{
                    //    props = new AuthenticationProperties
                    //    {
                    //        IsPersistent = true,
                    //        ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                    //    };
                    //};

                    //// issue authentication cookie with subject ID and username
                    //var user = _marvinUserRepository.GetUserByUsername(model.Username);
                    //await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));
                    //await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props);

                    //// make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint or a local page
                    //if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    //{
                    //    return Redirect(model.ReturnUrl);
                    //}

                    //return Redirect("~/");
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await _account.BuildLoginViewModelAsync(model);

            return(View(vm));
        }
예제 #13
0
        public IActionResult Login(string username, string password, Rol rol)
        {
            string returnUrl = TempData[_Return_Url] as string;

            if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
            {
                Usuario usuario = null;

                if (rol == Rol.Estudiante)
                {
                    usuario = _context.Alumnos.FirstOrDefault(usr => usr.Username == username);
                }
                else
                {
                    usuario = _context.Administradores.FirstOrDefault(usr => usr.Username == username);
                }

                if (usuario != null)
                {
                    var passwordEncriptada = password.Encriptar();

                    if (usuario.Password.SequenceEqual(passwordEncriptada))
                    {
                        // Se crean las credenciales del usuario que serán incorporadas al contexto
                        ClaimsIdentity identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);

                        // El lo que luego obtendré al acceder a User.Identity.Name
                        identity.AddClaim(new Claim(ClaimTypes.Name, username));

                        // Se utilizará para la autorización por roles
                        identity.AddClaim(new Claim(ClaimTypes.Role, rol.ToString()));

                        // Lo utilizaremos para acceder al Id del usuario que se encuentra en el sistema.
                        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, usuario.Id.ToString()));

                        // Lo utilizaremos cuando querramos mostrar el nombre del usuario logueado en el sistema.
                        identity.AddClaim(new Claim(ClaimTypes.GivenName, usuario.NombreYApellido));

                        ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                        // En este paso se hace el login del usuario al sistema
                        HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal).Wait();

                        _context.SaveChanges();

                        TempData["JustLoggedIn"] = true;

                        if (!string.IsNullOrWhiteSpace(returnUrl))
                        {
                            return(Redirect(returnUrl));
                        }

                        return(RedirectToAction(nameof(HomeController.Index), "Home"));
                    }
                }
            }

            // Completo estos dos campos para poder retornar a la vista en caso de errores.
            ViewBag.Error         = "Usuario o contraseña incorrectos";
            ViewBag.UserName      = username;
            TempData[_Return_Url] = returnUrl;

            return(View());
        }
예제 #14
0
        public async Task <object> LogIn([FromBody] User user)
        {
            bool validCredentials = false;
            var  userIdentity     = new ApplicationUser();

            if (user != null && !string.IsNullOrWhiteSpace(user.UserID))
            {
                userIdentity = _userManager
                               .FindByNameAsync(user.UserID).Result;
                if (userIdentity != null)
                {
                    var loginResult = _signInManager
                                      .CheckPasswordSignInAsync(userIdentity, user.Password, false)
                                      .Result;
                    if (loginResult.Succeeded)
                    {
                        validCredentials = _userManager.IsInRoleAsync(
                            userIdentity, Roles.ROLE_USER).Result;
                    }
                }
            }

            if (validCredentials)
            {
                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(user.UserID, "Login"),
                    new[] {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.UserID)
                }
                    );
                var roles = await _userManager.GetRolesAsync(userIdentity);

                foreach (var role in roles)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, role));
                }

                DateTime createDate     = DateTime.Now;
                DateTime expirationDate = createDate +
                                          TimeSpan.FromSeconds(_tokenConfigurations.Seconds);

                var handler       = new JwtSecurityTokenHandler();
                var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                {
                    Issuer             = _tokenConfigurations.Issuer,
                    Audience           = _tokenConfigurations.Audience,
                    SigningCredentials = _signInConfigurations.SigningCredentials,
                    Subject            = identity,
                    NotBefore          = createDate,
                    Expires            = expirationDate
                });
                var token = handler.WriteToken(securityToken);

                return(new
                {
                    authenticated = true,
                    created = createDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    expiration = expirationDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    accessToken = token,
                    message = "OK"
                });
            }
            else
            {
                return(new
                {
                    authenticated = false,
                    message = "Not authenticating"
                });
            }
        }
        /// <summary>
        /// Owin middleware overrided method
        /// </summary>
        /// <param name="context">the owin context</param>
        /// <returns>next invoke task</returns>
        public override async Task Invoke(IOwinContext context)
        {
            var header = context.Request.Headers.FirstOrDefault(m => m.Key.ToLower() == "authorization");

            if (!string.IsNullOrWhiteSpace(header.Key))
            {
                string headerValue = header.Value.FirstOrDefault().Trim();
                if (!headerValue.StartsWith("Bearer"))
                {
                    string[] parts;
                    try
                    {
                        string parameter = Encoding.UTF8.GetString(
                            Convert.FromBase64String(
                                header.Value.FirstOrDefault()));
                        parts = parameter.Split(':');
                    }
                    catch (Exception e)
                    {
                        throw new Exception("invalid value");
                    }

                    if (parts.Count() == 2)
                    {
                        var allowedOrigin = context.Get <string>("as:clientAllowedOrigin") ?? "*";

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

                        var user = await this.authRepository.FindUser(parts[0], parts[1]);

                        if (user != null)
                        {
                            string userId   = user.Id.ToString();
                            string roleName = this.authRepository.GetRoleName(user.Roles.ToList()[0].RoleId);
                            var    claims   = new[]
                            {
                                new Claim(ClaimTypes.Name, user.UserName)
                            };
                            var identity = new ClaimsIdentity(claims, "Basic");
                            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId));
                            identity.AddClaim(new Claim(ClaimTypes.Role, roleName));
                            identity.AddClaim(new Claim("sub", user.UserName));
                            identity.AddClaim(new Claim("role", roleName));
                            context.Request.User = new ClaimsPrincipal(identity);

                            var props = new AuthenticationProperties(new Dictionary <string, string>
                            {
                                {
                                    "userName", user.UserName
                                },
                                {
                                    "userId", userId
                                },
                                {
                                    "type", roleName
                                }
                            });

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

            await Next.Invoke(context);
        }
        private async Task <string> SerializeAccessTokenAsync(
            ClaimsIdentity identity, AuthenticationProperties properties,
            OpenIdConnectMessage request, OpenIdConnectMessage response)
        {
            // properties.IssuedUtc and properties.ExpiresUtc
            // should always be preferred when explicitly set.
            if (properties.IssuedUtc == null)
            {
                properties.IssuedUtc = Options.SystemClock.UtcNow;
            }

            if (properties.ExpiresUtc == null)
            {
                properties.ExpiresUtc = properties.IssuedUtc + Options.AccessTokenLifetime;
            }

            // Create a new identity containing only the filtered claims.
            // Actors identities are also filtered (delegation scenarios).
            identity = identity.Clone(claim => {
                // Never exclude ClaimTypes.NameIdentifier.
                if (string.Equals(claim.Type, ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                // Claims whose destination is not explicitly referenced or doesn't
                // contain "access_token" are not included in the access token.
                return(claim.HasDestination(OpenIdConnectConstants.Destinations.AccessToken));
            });

            // Create a new ticket containing the updated properties and the filtered identity.
            var ticket = new AuthenticationTicket(identity, properties);

            ticket.SetUsage(OpenIdConnectConstants.Usages.AccessToken);
            ticket.SetAudiences(ticket.GetResources());

            // Associate a random identifier with the access token.
            ticket.SetTicketId(Guid.NewGuid().ToString());

            // By default, add the client_id to the list of the
            // presenters allowed to use the access token.
            if (!string.IsNullOrEmpty(request.ClientId))
            {
                ticket.SetPresenters(request.ClientId);
            }

            var notification = new SerializeAccessTokenContext(Context, Options, request, response, ticket)
            {
                DataFormat           = Options.AccessTokenFormat,
                Issuer               = Context.GetIssuer(Options),
                SecurityTokenHandler = Options.AccessTokenHandler,
                SigningCredentials   = Options.SigningCredentials.FirstOrDefault()
            };

            await Options.Provider.SerializeAccessToken(notification);

            if (notification.HandledResponse || !string.IsNullOrEmpty(notification.AccessToken))
            {
                return(notification.AccessToken);
            }

            else if (notification.Skipped)
            {
                return(null);
            }

            if (!notification.Audiences.Any())
            {
                Options.Logger.LogInformation("No explicit audience was associated with the access token.");
            }

            if (notification.SecurityTokenHandler == null)
            {
                return(notification.DataFormat?.Protect(ticket));
            }

            if (notification.SigningCredentials == null)
            {
                Options.Logger.LogWarning("No signing credentials are registered in the OpenID Connect server options. " +
                                          "Consider registering a X.509 certificate to ensure access tokens are signed.");
            }

            // Store the "unique_id" property as a claim.
            ticket.Identity.AddClaim(notification.SecurityTokenHandler is JwtSecurityTokenHandler ?
                                     OpenIdConnectConstants.Claims.JwtId :
                                     OpenIdConnectConstants.Claims.TokenId, ticket.GetTicketId());

            // Store the "usage" property as a claim.
            ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.Usage, ticket.GetUsage());

            // If the ticket is marked as confidential, add a new
            // "confidential" claim in the security token.
            if (ticket.IsConfidential())
            {
                ticket.Identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.Confidential, "true", ClaimValueTypes.Boolean));
            }

            // Create a new claim per scope item, that will result
            // in a "scope" array being added in the access token.
            foreach (var scope in notification.Scopes)
            {
                ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.Scope, scope);
            }

            var handler = notification.SecurityTokenHandler as JwtSecurityTokenHandler;

            if (handler != null)
            {
                // Note: when used as an access token, a JWT token doesn't have to expose a "sub" claim
                // but the name identifier claim is used as a substitute when it has been explicitly added.
                // See https://tools.ietf.org/html/rfc7519#section-4.1.2
                var subject = identity.FindFirst(OpenIdConnectConstants.Claims.Subject);
                if (subject == null)
                {
                    var identifier = identity.FindFirst(ClaimTypes.NameIdentifier);
                    if (identifier != null)
                    {
                        identity.AddClaim(OpenIdConnectConstants.Claims.Subject, identifier.Value);
                    }
                }

                // Remove the ClaimTypes.NameIdentifier claims to avoid getting duplicate claims.
                // Note: the "sub" claim is automatically mapped by JwtSecurityTokenHandler
                // to ClaimTypes.NameIdentifier when validating a JWT token.
                // Note: make sure to call ToArray() to avoid an InvalidOperationException
                // on old versions of Mono, where FindAll() is implemented using an iterator.
                foreach (var claim in ticket.Identity.FindAll(ClaimTypes.NameIdentifier).ToArray())
                {
                    ticket.Identity.RemoveClaim(claim);
                }

                // Store the audiences as claims.
                foreach (var audience in notification.Audiences)
                {
                    ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.Audience, audience);
                }

                // Extract the presenters from the authentication ticket.
                var presenters = notification.Presenters.ToArray();
                switch (presenters.Length)
                {
                case 0: break;

                case 1:
                    identity.AddClaim(OpenIdConnectConstants.Claims.AuthorizedParty, presenters[0]);
                    break;

                default:
                    Options.Logger.LogWarning("Multiple presenters have been associated with the access token " +
                                              "but the JWT format only accepts single values.");

                    // Only add the first authorized party.
                    identity.AddClaim(OpenIdConnectConstants.Claims.AuthorizedParty, presenters[0]);
                    break;
                }

                var token = handler.CreateToken(
                    subject: ticket.Identity,
                    issuer: notification.Issuer,
                    signingCredentials: notification.SigningCredentials,
                    notBefore: ticket.Properties.IssuedUtc.Value.UtcDateTime,
                    expires: ticket.Properties.ExpiresUtc.Value.UtcDateTime);

                token.Payload[OpenIdConnectConstants.Claims.IssuedAt] =
                    EpochTime.GetIntDate(ticket.Properties.IssuedUtc.Value.UtcDateTime);

                // Try to extract a key identifier from the signing credentials
                // and add the "kid" property to the JWT header if applicable.
                LocalIdKeyIdentifierClause clause = null;
                if (notification.SigningCredentials?.SigningKeyIdentifier != null &&
                    notification.SigningCredentials.SigningKeyIdentifier.TryFind(out clause))
                {
                    token.Header[JwtHeaderParameterNames.Kid] = clause.LocalId;
                }

                return(handler.WriteToken(token));
            }

            else
            {
                var descriptor = new SecurityTokenDescriptor {
                    Subject               = ticket.Identity,
                    AppliesToAddress      = notification.Audiences.ElementAtOrDefault(0),
                    TokenIssuerName       = notification.Issuer,
                    EncryptingCredentials = notification.EncryptingCredentials,
                    SigningCredentials    = notification.SigningCredentials,
                    Lifetime              = new Lifetime(
                        notification.Ticket.Properties.IssuedUtc.Value.UtcDateTime,
                        notification.Ticket.Properties.ExpiresUtc.Value.UtcDateTime)
                };

                // When the encrypting credentials use an asymmetric key, replace them by a
                // EncryptedKeyEncryptingCredentials instance to generate a symmetric key.
                if (descriptor.EncryptingCredentials != null &&
                    descriptor.EncryptingCredentials.SecurityKey is AsymmetricSecurityKey)
                {
                    // Note: EncryptedKeyEncryptingCredentials automatically generates an in-memory key
                    // that will be encrypted using the original credentials and added to the resulting token
                    // if the security token handler fully supports token encryption (e.g SAML or SAML2).
                    descriptor.EncryptingCredentials = new EncryptedKeyEncryptingCredentials(
                        wrappingCredentials: notification.EncryptingCredentials, keySizeInBits: 256,
                        encryptionAlgorithm: SecurityAlgorithms.Aes256Encryption);
                }

                var token = notification.SecurityTokenHandler.CreateToken(descriptor);

                // Note: the security token is manually serialized to prevent
                // an exception from being thrown if the handler doesn't implement
                // the SecurityTokenHandler.WriteToken overload returning a string.
                var builder = new StringBuilder();
                using (var writer = XmlWriter.Create(builder, new XmlWriterSettings {
                    Encoding = new UTF8Encoding(false), OmitXmlDeclaration = true
                })) {
                    notification.SecurityTokenHandler.WriteToken(writer, token);
                }

                return(builder.ToString());
            }
        }
        private async Task <string> SerializeIdentityTokenAsync(
            ClaimsIdentity identity, AuthenticationProperties properties,
            OpenIdConnectMessage request, OpenIdConnectMessage response)
        {
            // properties.IssuedUtc and properties.ExpiresUtc
            // should always be preferred when explicitly set.
            if (properties.IssuedUtc == null)
            {
                properties.IssuedUtc = Options.SystemClock.UtcNow;
            }

            if (properties.ExpiresUtc == null)
            {
                properties.ExpiresUtc = properties.IssuedUtc + Options.IdentityTokenLifetime;
            }

            // Replace the identity by a new one containing only the filtered claims.
            // Actors identities are also filtered (delegation scenarios).
            identity = identity.Clone(claim => {
                // Never exclude ClaimTypes.NameIdentifier.
                if (string.Equals(claim.Type, ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                // Claims whose destination is not explicitly referenced or doesn't
                // contain "id_token" are not included in the identity token.
                return(claim.HasDestination(OpenIdConnectConstants.Destinations.IdentityToken));
            });

            // Create a new ticket containing the updated properties and the filtered identity.
            var ticket = new AuthenticationTicket(identity, properties);

            ticket.SetUsage(OpenIdConnectConstants.Usages.IdentityToken);

            // Associate a random identifier with the identity token.
            ticket.SetTicketId(Guid.NewGuid().ToString());

            // By default, add the client_id to the list of the
            // presenters allowed to use the identity token.
            if (!string.IsNullOrEmpty(request.ClientId))
            {
                ticket.SetAudiences(request.ClientId);
                ticket.SetPresenters(request.ClientId);
            }

            var notification = new SerializeIdentityTokenContext(Context, Options, request, response, ticket)
            {
                Issuer = Context.GetIssuer(Options),
                SecurityTokenHandler = Options.IdentityTokenHandler,
                SigningCredentials   = Options.SigningCredentials.FirstOrDefault()
            };

            await Options.Provider.SerializeIdentityToken(notification);

            if (notification.HandledResponse || !string.IsNullOrEmpty(notification.IdentityToken))
            {
                return(notification.IdentityToken);
            }

            else if (notification.Skipped)
            {
                return(null);
            }

            if (notification.SecurityTokenHandler == null)
            {
                return(null);
            }

            if (!identity.HasClaim(claim => claim.Type == OpenIdConnectConstants.Claims.Subject) &&
                !identity.HasClaim(claim => claim.Type == ClaimTypes.NameIdentifier))
            {
                throw new InvalidOperationException("A unique identifier cannot be found to generate a 'sub' claim: " +
                                                    "make sure to add a 'ClaimTypes.NameIdentifier' claim.");
            }

            if (notification.SigningCredentials == null)
            {
                Options.Logger.LogWarning("No signing credentials are registered in the OpenID Connect server options. " +
                                          "Consider registering a X.509 certificate to ensure identity tokens are signed.");
            }

            // Store the unique subject identifier as a claim.
            if (!identity.HasClaim(claim => claim.Type == OpenIdConnectConstants.Claims.Subject))
            {
                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, identity.GetClaim(ClaimTypes.NameIdentifier));
            }

            // Remove the ClaimTypes.NameIdentifier claims to avoid getting duplicate claims.
            // Note: the "sub" claim is automatically mapped by JwtSecurityTokenHandler
            // to ClaimTypes.NameIdentifier when validating a JWT token.
            // Note: make sure to call ToArray() to avoid an InvalidOperationException
            // on old versions of Mono, where FindAll() is implemented using an iterator.
            foreach (var claim in identity.FindAll(ClaimTypes.NameIdentifier).ToArray())
            {
                identity.RemoveClaim(claim);
            }

            // Store the "unique_id" property as a claim.
            ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.JwtId, ticket.GetTicketId());

            // Store the "usage" property as a claim.
            ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.Usage, ticket.GetUsage());

            // If the ticket is marked as confidential, add a new
            // "confidential" claim in the security token.
            if (ticket.IsConfidential())
            {
                ticket.Identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.Confidential, "true", ClaimValueTypes.Boolean));
            }

            // Store the audiences as claims.
            foreach (var audience in notification.Audiences)
            {
                ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.Audience, audience);
            }

            // If a nonce was present in the authorization request, it MUST
            // be included in the id_token generated by the token endpoint.
            // See http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
            var nonce = request.Nonce;

            if (request.IsAuthorizationCodeGrantType())
            {
                // Restore the nonce stored in the authentication
                // ticket extracted from the authorization code.
                nonce = ticket.GetNonce();
            }

            if (!string.IsNullOrEmpty(nonce))
            {
                ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.Nonce, nonce);
            }

            if (!string.IsNullOrEmpty(response.Code))
            {
                using (var algorithm = HashAlgorithm.Create(notification.SigningCredentials.DigestAlgorithm)) {
                    // Create the c_hash using the authorization code returned by SerializeAuthorizationCodeAsync.
                    var hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(response.Code));

                    // Note: only the left-most half of the hash of the octets is used.
                    // See http://openid.net/specs/openid-connect-core-1_0.html#HybridIDToken
                    ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.CodeHash,
                                             Base64UrlEncoder.Encode(hash, 0, hash.Length / 2));
                }
            }

            if (!string.IsNullOrEmpty(response.AccessToken))
            {
                using (var algorithm = HashAlgorithm.Create(notification.SigningCredentials.DigestAlgorithm)) {
                    // Create the at_hash using the access token returned by SerializeAccessTokenAsync.
                    var hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(response.AccessToken));

                    // Note: only the left-most half of the hash of the octets is used.
                    // See http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
                    ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.AccessTokenHash,
                                             Base64UrlEncoder.Encode(hash, 0, hash.Length / 2));
                }
            }

            // Extract the presenters from the authentication ticket.
            var presenters = notification.Presenters.ToArray();

            switch (presenters.Length)
            {
            case 0: break;

            case 1:
                identity.AddClaim(OpenIdConnectConstants.Claims.AuthorizedParty, presenters[0]);
                break;

            default:
                Options.Logger.LogWarning("Multiple presenters have been associated with the identity token " +
                                          "but the JWT format only accepts single values.");

                // Only add the first authorized party.
                identity.AddClaim(OpenIdConnectConstants.Claims.AuthorizedParty, presenters[0]);
                break;
            }

            var token = notification.SecurityTokenHandler.CreateToken(
                subject: ticket.Identity,
                issuer: notification.Issuer,
                signingCredentials: notification.SigningCredentials,
                notBefore: ticket.Properties.IssuedUtc.Value.UtcDateTime,
                expires: ticket.Properties.ExpiresUtc.Value.UtcDateTime);

            token.Payload[OpenIdConnectConstants.Claims.IssuedAt] =
                EpochTime.GetIntDate(ticket.Properties.IssuedUtc.Value.UtcDateTime);

            // Try to extract a key identifier from the signing credentials
            // and add the "kid" property to the JWT header if applicable.
            LocalIdKeyIdentifierClause clause = null;

            if (notification.SigningCredentials?.SigningKeyIdentifier != null &&
                notification.SigningCredentials.SigningKeyIdentifier.TryFind(out clause))
            {
                token.Header[JwtHeaderParameterNames.Kid] = clause.LocalId;
            }

            return(notification.SecurityTokenHandler.WriteToken(token));
        }
예제 #18
0
        public async Task <IActionResult> Login(LoginIM im)
        {
            if (im == null)
            {
                AR.Setfailure(Messages.InvalidUserNameOrPassword);
                return(Json(AR));
            }

            // var lookupUser = _userServices.SignIn(im.Username, im.Password);

            var user = await _context.Users.FirstOrDefaultAsync(predicate : u => u.UserName == im.Username);

            if (user == null)
            {
                AR.Setfailure(Messages.InvalidUserNameOrPassword);
                return(Json(AR));
            }

            var salt    = Convert.FromBase64String(user.SecurityStamp);
            var pwdHash = Hash.HashPasswordWithSalt(im.Password, salt);

            if (user.PasswordHash != pwdHash)
            {
                AR.Setfailure(Messages.InvalidUserNameOrPassword);
                return(Json(AR));
            }
            ;

            // create claims
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Sid, user.Id.ToString()),
                new Claim("RealName", user.RealName ?? "无"),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Email, user.Email)
            };

            // create identity
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var userRoles = await _context.Roles.Where(d => d.UserRoles.Any(r => r.UserId == user.Id)).ToArrayAsync();

            //add a list of roles

            if (userRoles.Any())
            {
                var roles = string.Join(",", userRoles.Select(d => d.RoleName));
                identity.AddClaim(new Claim(ClaimTypes.Role, roles));
            }

            // create principal
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties
            {
                IsPersistent = im.RememberMe,
                ExpiresUtc   = DateTimeOffset.Now.Add(TimeSpan.FromDays(180))
            });

            AR.SetSuccess(Messages.Wellcome);
            return(Json(AR));
        }
예제 #19
0
        public async Task <IActionResult> Accept(CancellationToken cancellationToken)
        {
            var response = HttpContext.GetOpenIdConnectResponse();

            if (response != null)
            {
                return(View("Error", response));
            }

            var request = HttpContext.GetOpenIdConnectRequest();

            if (request == null)
            {
                return(View("Error", new OpenIdConnectMessage {
                    Error = OpenIdConnectConstants.Errors.ServerError,
                    ErrorDescription = "An internal error has occurred"
                }));
            }

            // Remove the authorization request from the user session.
            if (!string.IsNullOrEmpty(request.GetRequestId()))
            {
                HttpContext.Session.Remove("authorization-request:" + request.GetRequestId());
            }

            // Create a new ClaimsIdentity containing the claims that
            // will be used to create an id_token, a token or a code.
            var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);

            // Copy the claims retrieved from the external identity provider
            // (e.g Google, Facebook, a WS-Fed provider or another OIDC server).
            foreach (var claim in HttpContext.User.Claims)
            {
                // Allow ClaimTypes.Name to be added in the id_token.
                // ClaimTypes.NameIdentifier is automatically added, even if its
                // destination is not defined or doesn't include "id_token".
                // The other claims won't be visible for the client application.
                if (claim.Type == ClaimTypes.Name)
                {
                    claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                          OpenIdConnectConstants.Destinations.IdentityToken);
                }

                identity.AddClaim(claim);
            }

            var application = await GetApplicationAsync(request.ClientId, cancellationToken);

            if (application == null)
            {
                return(View("Error", new OpenIdConnectMessage {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription = "Details concerning the calling client application cannot be found in the database"
                }));
            }

            // Create a new ClaimsIdentity containing the claims associated with the application.
            // Note: setting identity.Actor is not mandatory but can be useful to access
            // the whole delegation chain from the resource server (see ResourceController.cs).
            identity.Actor = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);
            identity.Actor.AddClaim(ClaimTypes.NameIdentifier, application.ApplicationID);

            identity.Actor.AddClaim(ClaimTypes.Name, application.DisplayName,
                                    OpenIdConnectConstants.Destinations.AccessToken,
                                    OpenIdConnectConstants.Destinations.IdentityToken);

            // Create a new authentication ticket holding the user identity.
            var ticket = new AuthenticationTicket(
                new ClaimsPrincipal(identity),
                new AuthenticationProperties(),
                OpenIdConnectServerDefaults.AuthenticationScheme);

            // Set the list of scopes granted to the client application.
            // Note: this sample always grants the "openid", "email" and "profile" scopes
            // when they are requested by the client application: a real world application
            // would probably display a form allowing to select the scopes to grant.
            ticket.SetScopes(new[] {
                /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
                /* email: */ OpenIdConnectConstants.Scopes.Email,
                /* profile: */ OpenIdConnectConstants.Scopes.Profile,
                /* offline_access: */ OpenIdConnectConstants.Scopes.OfflineAccess
            }.Intersect(request.GetScopes()));

            // Set the resources servers the access token should be issued for.
            ticket.SetResources("resource_server");

            // Returning a SignInResult will ask ASOS to serialize the specified identity to build appropriate tokens.
            // Note: you should always make sure the identities you return contain ClaimTypes.NameIdentifier claim.
            // In this sample, the identity always contains the name identifier returned by the external provider.
            return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
        }
예제 #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));

            // this is for DI purposes
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services
            // .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddAuthentication(cfg =>
            {
                cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                cfg.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Authority = "https://securetoken.google.com/abtestinghost";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer   = true,
                    ValidIssuer      = "https://securetoken.google.com/abtestinghost",
                    ValidateAudience = true,
                    ValidAudience    = "abtestinghost",
                    ValidateLifetime = true
                };

                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = async ctx =>
                    {
                        // grabs the unique id from firebase
                        var name = ctx.Principal.Claims.First(c => c.Type == "user_id").Value;

                        //Get userManager out of DI
                        var _userManager = ctx.HttpContext.RequestServices.GetRequiredService <UserManager <ApplicationUser> >();

                        // retrieves the roles that the user has
                        ApplicationUser user = await _userManager.FindByNameAsync(name);

                        if (user == null)
                        {
                            user             = new ApplicationUser(name);
                            user.Email       = "*****@*****.**";
                            user.customField = "haha";

                            var newPineapple = new Pineapple()
                            {
                                name = "random name of things " + name
                            };
                            user.Pineapples = new List <Pineapple>();
                            user.Pineapples.Add(newPineapple);
                            var result     = await _userManager.CreateAsync(user);
                            var roleResult = await _userManager.AddToRoleAsync(user, "admin");
                        }

                        var userRoles = await _userManager.GetRolesAsync(user);

                        // adds the role as a new claim
                        ClaimsIdentity identity = ctx.Principal.Identity as ClaimsIdentity;
                        if (identity != null)
                        {
                            foreach (var role in userRoles)
                            {
                                identity.AddClaim(new System.Security.Claims.Claim(ClaimTypes.Role, role));
                            }
                        }
                    }
                };
            });
            services.AddIdentityCore <ApplicationUser>()
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.TryAddScoped <SignInManager <ApplicationUser> >();

            services.AddSingleton <IDocumentExecuter, DocumentExecuter>();
            services.AddSingleton <BaseGraphQLQuery>();
            services.AddSingleton <GraphQLQuery>();
            services.AddSingleton <GraphQLSchema>();
            services.AddSingleton <GraphQLMutation>();
            services.AddSingleton <PineappleType>();
            services.AddSingleton <PineappleInputType>();
            services.AddSingleton <ApplicationUserType>();

            var sp = services.BuildServiceProvider();

            services.AddSingleton <ISchema>(new GraphQLSchema(new FuncDependencyResolver(type => sp.GetService(type))));


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                          .AllowAnyMethod()
                                                          .AllowAnyHeader()));
        }
예제 #21
0
        private async Task <string[]> ChangeUserPassword(string resetToken, string oldPassword, string newPassword)
        {
            string[] result = null;

            PasswordPolicy passpol          = null;
            string         accessTokenValue = null;

            bool isPasswordValid = true;

            ClaimsIdentity claimsIdentity = null;

            try
            {
                resetToken  = resetToken ?? "";
                oldPassword = oldPassword ?? "";
                newPassword = newPassword ?? "";

                passpol = _dbi.GetPasswordPolicy();

                if (passpol != null)
                {
                    string lang = this.GetSelectedLanguage();

                    var verifResult = passpol.IsPasswordFormatValid(newPassword);

                    if (!verifResult.IsValid())
                    {
                        isPasswordValid = false;

                        result = passpol
                                 .SetAlphaErrorMsg(LanguageManager.GetMessage("errMsg_Pswrd_Alpha", lang))
                                 .SetMinLenErrorMsg(LanguageManager.GetMessage("errMsg_Pswrd_MinLen", lang))
                                 .SetNumericErrorMsg(LanguageManager.GetMessage("errMsg_Pswrd_Numeric", lang))
                                 .SetSpacesErrorMsg(LanguageManager.GetMessage("errMsg_Pswrd_Spaces", lang))
                                 .SetSpecialErrorMsg(LanguageManager.GetMessage("errMsg_Pswrd_Special", lang))
                                 .SetUppercaseErrorMsg(LanguageManager.GetMessage("errMsg_Pswrd_Uppercase", lang))
                                 .GetErrorMessages(verifResult);
                    }
                }

                if (isPasswordValid)
                {
                    accessTokenValue = _dbi.ChangeAccountPassword(oldPassword, newPassword, resetToken);

                    if (string.IsNullOrEmpty(resetToken))
                    {
                        claimsIdentity = new ClaimsIdentity(BaseController.APP_ID);
                        claimsIdentity.AddClaims(this.User.Claims.Where(l => l.Type != ACCESS_TOKEN_KEY && l.Type != PASSWORD_FORMAT_INVALID));

                        claimsIdentity.AddClaim(new Claim(ACCESS_TOKEN_KEY, accessTokenValue));
                        claimsIdentity.AddClaim(new Claim(PASSWORD_FORMAT_INVALID, false.ToString()));

                        if (GetRememberUser(this.User))
                        {
                            await this.HttpContext.Authentication.SignInAsync(
                                BaseController.APP_ID,
                                new ClaimsPrincipal(claimsIdentity),
                                new AuthenticationProperties
                            {
                                IsPersistent = true,
                                ExpiresUtc   = GetClaimExpDate(this.User)
                            });
                        }
                        else
                        {
                            await this.HttpContext.Authentication.SignInAsync(BaseController.APP_ID, new ClaimsPrincipal(claimsIdentity));
                        }
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                result           = null;
                passpol          = null;
                accessTokenValue = null;
                claimsIdentity   = null;
            }
        }
예제 #22
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityModel.JwtClaimTypes.Name;

            AntiForgeryConfig.SuppressXFrameOptionsHeader = true;

            app.Use <RequireSslMiddleware>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = Constants.AuthenticationTypeCookies,
                ExpireTimeSpan     = new TimeSpan(0, 30, 0),
                SlidingExpiration  = true
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId  = Constants.ClientCredentials.ClientId,
                Authority = Constants.Endpoints.IdentityServerEndpoint,
                SignInAsAuthenticationType = Constants.AuthenticationTypeCookies,
                ResponseType     = string.Join(" ", Constants.OpenIdConnectSettings.ResponseTypes),
                Scope            = string.Join(" ", Constants.OpenIdConnectSettings.ScopesRequesting),
                UseTokenLifetime = false,
                //PostLogoutRedirectUri = ""
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = async context =>
                    {
                        var appBaseUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.PathBase}";

                        if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        {
                            context.ProtocolMessage.RedirectUri = $"{appBaseUrl}/";
                        }

                        if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = context.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                                context.ProtocolMessage.IdTokenHint           = idTokenHint.Value;
                            }
                        }
                        await Task.FromResult(context);
                    },

                    SecurityTokenValidated = async context =>
                    {
                        var subClaim = context.AuthenticationTicket.Identity.FindFirst(IdentityModel.JwtClaimTypes.Subject);

                        var sidClaim = context.AuthenticationTicket.Identity.FindFirst(IdentityModel.JwtClaimTypes.SessionId);

                        var nameClaim = new Claim(IdentityModel.JwtClaimTypes.Name, $"{Constants.Endpoints.IdentityServerEndpoint}{subClaim.Value}");

                        var givenNameClaim = context.AuthenticationTicket.Identity.FindFirst(IdentityModel.JwtClaimTypes.GivenName);

                        var familyNameClaim = context.AuthenticationTicket.Identity.FindFirst(IdentityModel.JwtClaimTypes.FamilyName);

                        var preferredUserNameClaim = context.AuthenticationTicket.Identity.FindFirst(IdentityModel.JwtClaimTypes.PreferredUserName);

                        var imisbaseAddressClaim = context.AuthenticationTicket.Identity.FindFirst("imisbaseaddress");

                        var imisapiClaim = context.AuthenticationTicket.Identity.FindFirst("imisapi");

                        var newClaimsIdentity = new ClaimsIdentity(context.AuthenticationTicket.Identity.AuthenticationType, IdentityModel.JwtClaimTypes.Name, IdentityModel.JwtClaimTypes.Role);

                        if (subClaim != null)
                        {
                            newClaimsIdentity.AddClaim(subClaim);
                        }

                        if (sidClaim != null)
                        {
                            newClaimsIdentity.AddClaim(sidClaim);
                        }

                        if (nameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(nameClaim);
                        }

                        if (givenNameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(givenNameClaim);
                        }

                        if (familyNameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(familyNameClaim);
                        }

                        if (preferredUserNameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(preferredUserNameClaim);
                        }

                        if (imisbaseAddressClaim != null)
                        {
                            newClaimsIdentity.AddClaim(imisbaseAddressClaim);
                        }

                        if (imisapiClaim != null)
                        {
                            newClaimsIdentity.AddClaim(imisapiClaim);
                        }

                        var appBaseUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.PathBase}";

                        var client = new TokenClient(Constants.Endpoints.TokenEndpoint, Constants.ClientCredentials.ClientId, Constants.ClientCredentials.ClientSecret);

                        var response = await client.RequestAuthorizationCodeAsync(context.ProtocolMessage.Code, appBaseUrl + "/");

                        var expirationDateAsRoundtripString = DateTime.SpecifyKind(DateTime.UtcNow.AddSeconds(response.ExpiresIn), DateTimeKind.Utc).ToString("o");

                        newClaimsIdentity.AddClaim(new Claim("refresh_token", response.RefreshToken));
                        newClaimsIdentity.AddClaim(new Claim("access_token", context.ProtocolMessage.AccessToken));
                        newClaimsIdentity.AddClaim(new Claim("expires_at", expirationDateAsRoundtripString));
                        newClaimsIdentity.AddClaim(new Claim("id_token", response.IdentityToken));

                        context.AuthenticationTicket = new AuthenticationTicket(newClaimsIdentity, context.AuthenticationTicket.Properties);

                        await Task.FromResult(context);
                    }
                }
            });
        }
예제 #23
0
        //ati login
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                UnitOfWork unitOfWork  = new UnitOfWork();
                var        userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

                ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);



                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                var roles = userManager.GetRoles(user.Id).First();


                var scope      = context.Scope.ToList();
                var customerId = Convert.ToInt32(context.Scope[0]);



                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                      CookieAuthenticationDefaults.AuthenticationType);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                if (roles == "Company")
                {
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "Company"));
                }
                else if (roles == "User")
                {
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "User"));
                }
                else
                {
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "xuser"));
                }


                oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "Vahid"));

                AuthenticationProperties properties = CreateProperties(user.UserName, (context.ClientId == null) ? string.Empty : context.ClientId);
                properties.Dictionary.Add("AuthId", user.Id);
                var company = await unitOfWork.CompanyRepository.GetViewCompanyByMobile(context.UserName);

                if (roles == "Company")
                {
                    if (company != null)
                    {
                        properties.Dictionary.Add("Name", company.Name);
                        properties.Dictionary.Add("UserId", company.Id.ToString());
                        properties.Dictionary.Add("Image", string.IsNullOrEmpty(company.ImageUrl) ? "" : company.ImageUrl.ToString());
                        properties.Dictionary.Add("Role", "Company");
                        //   properties.Dictionary.Add("EmployeeId", employee.Id.ToString());
                    }
                }
                else
                {
                    //ViewPerson person = await unitOfWork.PersonRepository.GetViewPersonByUserId(user.Id);
                    if (company != null)
                    {
                        properties.Dictionary.Add("Name", company.FullName);
                        properties.Dictionary.Add("UserId", company.Id.ToString());
                        properties.Dictionary.Add("Image", string.IsNullOrEmpty(company.ImageUrl) ? "" : company.ImageUrl.ToString());
                        properties.Dictionary.Add("Role", "User");
                        //   properties.Dictionary.Add("EmployeeId", employee.Id.ToString());
                    }
                }


                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
            catch (Exception ex)
            {
                int i = 0;
            }
        }
예제 #24
0
        /// <summary>
        /// Represents an event called for each validated token request
        /// to allow the user code to decide how the request should be handled.
        /// </summary>
        /// <param name="context">The context instance associated with this event.</param>
        public override Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            // Only handle grant_type=password requests and let ASOS
            // process grant_type=refresh_token requests automatically.
            if (context.Request.IsPasswordGrantType())
            {
                UserLogin            user                = null;
                ClaimsIdentity       identity            = null;
                IEnumerable <string> allowedClientScopes = null;
                var loginValid = false;

                // Do all the data access here so we can dispose of the rock context asap.
                using (var rockContext = new RockContext())
                {
                    var userLoginService = new UserLoginService(rockContext);
                    user = userLoginService.GetByUserName(context.Request.Username);
                    // Populate the entity type for use later.
                    _ = user.EntityType;

                    allowedClientScopes = RockIdentityHelper.NarrowRequestedScopesToApprovedScopes(rockContext, context.Request.ClientId, context.Request.GetScopes()).ToList();
                    var allowedClientClaims = RockIdentityHelper.GetAllowedClientClaims(rockContext, context.Request.ClientId, allowedClientScopes);
                    identity = RockIdentityHelper.GetRockClaimsIdentity(user, allowedClientClaims, context.Request.ClientId);

                    var component = AuthenticationContainer.GetComponent(user.EntityType.Name);
                    if (component != null && component.IsActive && !component.RequiresRemoteAuthentication)
                    {
                        loginValid = component.AuthenticateAndTrack(user, context.Request.Password);
                        rockContext.SaveChanges();
                    }
                }

                if (identity == null || allowedClientScopes == null)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidClient,
                        description: "Invalid client configuration.");
                    return(Task.FromResult(0));
                }

                if (user == null || !loginValid)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid credentials.");
                    return(Task.FromResult(0));
                }

                // Ensure the user is allowed to sign in.
                if (!user.IsConfirmed.HasValue || !user.IsConfirmed.Value || (user.IsPasswordChangeRequired != null && user.IsPasswordChangeRequired.Value))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "The specified user is not allowed to sign in.");
                    return(Task.FromResult(0));
                }

                // Create a new authentication ticket holding the user identity.
                var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());

                // Set the list of scopes granted to the client application.
                ticket.SetScopes(allowedClientScopes);

                // Set the resource servers the access token should be issued for.
                ticket.SetResources("resource_server");
                context.Validate(ticket);
            }

            if (context.Request.IsClientCredentialsGrantType())
            {
                // We don't need to validate the client id here because it was already validated in the ValidateTokenRequest method.
                var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationType);

                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, context.Request.ClientId,
                                  OpenIdConnectConstants.Destinations.AccessToken);

                // Create a new authentication ticket holding the user identity.
                var ticket = new AuthenticationTicket(
                    identity,
                    new AuthenticationProperties());

                context.Validate(ticket);
            }
            return(Task.FromResult(0));
        }
예제 #25
0
        protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens)
        {
            var endpoint = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, "access_token", tokens.AccessToken);

            if (Options.SendAppSecretProof)
            {
                endpoint = QueryHelpers.AddQueryString(endpoint, "appsecret_proof", GenerateAppSecretProof(tokens.AccessToken));
            }
            if (Options.Fields.Count > 0)
            {
                endpoint = QueryHelpers.AddQueryString(endpoint, "fields", string.Join(",", Options.Fields));
            }

            var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted);

            response.EnsureSuccessStatusCode();

            var payload = JObject.Parse(await response.Content.ReadAsStringAsync());

            var ticket  = new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.AuthenticationScheme);
            var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, payload);

            var identifier = FacebookHelper.GetId(payload);

            if (!string.IsNullOrEmpty(identifier))
            {
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identifier, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var ageRangeMin = FacebookHelper.GetAgeRangeMin(payload);

            if (!string.IsNullOrEmpty(ageRangeMin))
            {
                identity.AddClaim(new Claim("urn:facebook:age_range_min", ageRangeMin, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var ageRangeMax = FacebookHelper.GetAgeRangeMax(payload);

            if (!string.IsNullOrEmpty(ageRangeMax))
            {
                identity.AddClaim(new Claim("urn:facebook:age_range_max", ageRangeMax, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var birthday = FacebookHelper.GetBirthday(payload);

            if (!string.IsNullOrEmpty(birthday))
            {
                identity.AddClaim(new Claim(ClaimTypes.DateOfBirth, birthday, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var email = FacebookHelper.GetEmail(payload);

            if (!string.IsNullOrEmpty(email))
            {
                identity.AddClaim(new Claim(ClaimTypes.Email, email, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var firstName = FacebookHelper.GetFirstName(payload);

            if (!string.IsNullOrEmpty(firstName))
            {
                identity.AddClaim(new Claim(ClaimTypes.GivenName, firstName, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var gender = FacebookHelper.GetGender(payload);

            if (!string.IsNullOrEmpty(gender))
            {
                identity.AddClaim(new Claim(ClaimTypes.Gender, gender, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var lastName = FacebookHelper.GetLastName(payload);

            if (!string.IsNullOrEmpty(lastName))
            {
                identity.AddClaim(new Claim(ClaimTypes.Surname, lastName, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var link = FacebookHelper.GetLink(payload);

            if (!string.IsNullOrEmpty(link))
            {
                identity.AddClaim(new Claim("urn:facebook:link", link, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var location = FacebookHelper.GetLocation(payload);

            if (!string.IsNullOrEmpty(location))
            {
                identity.AddClaim(new Claim("urn:facebook:location", location, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var locale = FacebookHelper.GetLocale(payload);

            if (!string.IsNullOrEmpty(locale))
            {
                identity.AddClaim(new Claim(ClaimTypes.Locality, locale, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var middleName = FacebookHelper.GetMiddleName(payload);

            if (!string.IsNullOrEmpty(middleName))
            {
                identity.AddClaim(new Claim("urn:facebook:middle_name", middleName, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var name = FacebookHelper.GetName(payload);

            if (!string.IsNullOrEmpty(name))
            {
                identity.AddClaim(new Claim(ClaimTypes.Name, name, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var timeZone = FacebookHelper.GetTimeZone(payload);

            if (!string.IsNullOrEmpty(timeZone))
            {
                identity.AddClaim(new Claim("urn:facebook:timezone", timeZone, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            await Options.Events.CreatingTicket(context);

            return(context.Ticket);
        }
예제 #26
0
        public async Task HandleIntrospectionRequest_RequestIsRejectedWhenRefreshTokenIsInvalid()
        {
            // Arrange
            var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);

            identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "Bob le Bricoleur");

            var ticket = new AuthenticationTicket(
                new ClaimsPrincipal(identity),
                new AuthenticationProperties(),
                OpenIdConnectServerDefaults.AuthenticationScheme);

            ticket.SetTokenId("3E228451-1555-46F7-A471-951EFBA23A56");
            ticket.SetTokenUsage(OpenIdConnectConstants.TokenUsages.RefreshToken);

            var format = new Mock <ISecureDataFormat <AuthenticationTicket> >();

            format.Setup(mock => mock.Unprotect("2YotnFZFEjr1zCsicMWpAA"))
            .Returns(ticket);

            var token = new OpenIddictToken();

            var manager = CreateTokenManager(instance =>
            {
                instance.Setup(mock => mock.FindByIdAsync("3E228451-1555-46F7-A471-951EFBA23A56", It.IsAny <CancellationToken>()))
                .ReturnsAsync(token);

                instance.Setup(mock => mock.IsValidAsync(token, It.IsAny <CancellationToken>()))
                .ReturnsAsync(false);
            });

            var server = CreateAuthorizationServer(builder =>
            {
                builder.Services.AddSingleton(CreateApplicationManager(instance =>
                {
                    var application = new OpenIddictApplication();

                    instance.Setup(mock => mock.FindByClientIdAsync("Fabrikam", It.IsAny <CancellationToken>()))
                    .ReturnsAsync(application);

                    instance.Setup(mock => mock.GetClientTypeAsync(application, It.IsAny <CancellationToken>()))
                    .ReturnsAsync(OpenIddictConstants.ClientTypes.Confidential);

                    instance.Setup(mock => mock.ValidateClientSecretAsync(application, "7Fjfp0ZBr1KtDRbnfVdmIw", It.IsAny <CancellationToken>()))
                    .ReturnsAsync(true);
                }));

                builder.Services.AddSingleton(manager);

                builder.Configure(options => options.RefreshTokenFormat = format.Object);
            });

            var client = new OpenIdConnectClient(server.CreateClient());

            // Act
            var response = await client.PostAsync(IntrospectionEndpoint, new OpenIdConnectRequest
            {
                ClientId     = "Fabrikam",
                ClientSecret = "7Fjfp0ZBr1KtDRbnfVdmIw",
                Token        = "2YotnFZFEjr1zCsicMWpAA"
            });

            // Assert
            Assert.Single(response.GetParameters());
            Assert.False((bool)response[OpenIdConnectConstants.Claims.Active]);

            Mock.Get(manager).Verify(mock => mock.FindByIdAsync("3E228451-1555-46F7-A471-951EFBA23A56", It.IsAny <CancellationToken>()), Times.Once());
            Mock.Get(manager).Verify(mock => mock.IsValidAsync(token, It.IsAny <CancellationToken>()), Times.Once());
        }
 public static void SetUserId(this ClaimsIdentity identity, Guid id)
 {
     identity?.AddClaim(new Claim(UserIdClaimType, id.ToString(), typeof(Guid).ToString()));
 }
예제 #28
0
        private bool IsLogin(ClaimsIdentity identity)
        {
            var strCookieKey = _navigationService.GetLoginKey();

            // 如果Cookie存在,获取cookie值。
            //如果Session存在且与cookie信息一致,则返回true,否则并将用户信息保存到Session中,返回true。
            if (_context.Request.Cookies[_cookieName] != null &&
                !string.IsNullOrEmpty(_context.Request.Cookies[_cookieName]))
            {
                try
                {
                    string cookieValue = DESEncryptor.Decrypt(_context.Request.Cookies[_cookieName], strCookieKey);
                    if (string.IsNullOrEmpty(cookieValue))
                    {
                        Logger.LogError("IsLogin无法获取cookie");
                        return(false);
                    }
                    string[] strCookieArr = cookieValue.Split('|');
                    if (strCookieArr.Length == 0)
                    {
                        Logger.LogError("IsLogin--》cookie格式不对:" + cookieValue);
                        return(false);
                    }
                    string useridstr = DESEncryptor.Decrypt(strCookieArr[0], strCookieKey);

                    int userid;
                    if (int.TryParse(useridstr, out userid))
                    {
                        string token = _navigationService.GetUserLoginToken(userid);
                        if (string.Equals(token, DESEncryptor.Decrypt(strCookieArr[7], strCookieKey)))
                        {
                            userid = Convert.ToInt32(DESEncryptor.Decrypt(strCookieArr[0], strCookieKey));
                            var username = DESEncryptor.Decrypt(WebUtility.UrlDecode(strCookieArr[1]), strCookieKey);
                            var truename = DESEncryptor.Decrypt(WebUtility.UrlDecode(strCookieArr[2]), strCookieKey);
                            var sysID    = "";
                            var gid      = DESEncryptor.Decrypt(strCookieArr[4], strCookieKey);
                            var departID = DESEncryptor.Decrypt(strCookieArr[5], strCookieKey);
                            var pid      = DESEncryptor.Decrypt(strCookieArr[6], strCookieKey);
                            var token1   = DESEncryptor.Decrypt(strCookieArr[7], strCookieKey);
                            var adname   = DESEncryptor.Decrypt(strCookieArr[8], strCookieKey);
                            var usercode = DESEncryptor.Decrypt(strCookieArr[9], strCookieKey);

                            identity.AddClaim(new Claim("userId", userid.ToString()));
                            identity.AddClaim(new Claim(ClaimTypes.Name, truename));
                            identity.AddClaim(new Claim("truename", truename));
                            identity.AddClaim(new Claim("sysID", sysID));
                            identity.AddClaim(new Claim("gid", gid));
                            identity.AddClaim(new Claim("departID", departID));
                            identity.AddClaim(new Claim("pid", pid));
                            identity.AddClaim(new Claim("token", token1));
                            identity.AddClaim(new Claim("adname", adname));
                            identity.AddClaim(new Claim("usercode", usercode));

                            return(true);
                        }
                        return(false);
                    }
                    return(false);
                }
                catch (Exception e)
                {
                    Logger.LogError("IsLogin异常", e);
                    throw;
                }
            }

            return(false);
        }
예제 #29
0
        public ActionResult CheckListCompleted()
        {
            try
            {
                AuthenticatedUser    _authUser;
                AccountCheckListInfo _accountCheckList;
                var _employeeRegInfo = new EmployeeRegistrationInfo();

                using (AuthRepository Repo = new AuthRepository())
                {
                    _authUser = Repo.GetAuthenticatedUserById(CurrentUser.EmployeeInfoId);
                }

                if (_authUser.IsCheckListCompleted == true)
                {
                    return(RedirectToAction("Logout", "Auth", new { area = "" }));
                }

                using (AccountCheckListRepository Repo = new AccountCheckListRepository())
                {
                    _accountCheckList = Repo.GetAccountCheckListByUserId(CurrentUser.AccountId);
                }

                if (_accountCheckList.IsPictureUploaded == false)
                {
                    return(RedirectToAction("UploadPicture", "File"));
                }

                using (EmployeeRepository Repo = new EmployeeRepository())
                {
                    _employeeRegInfo = Repo.GetRegisterEmployeeInfoById(CurrentUser.EmployeeInfoId);

                    _employeeRegInfo.DateOfJoin = DateTime.Now;

                    Repo.RegisterEmployee(_employeeRegInfo);
                }

                using (AccountRepository Repo = new AccountRepository())
                {
                    Repo.CheckListCompleted(CurrentUser.AccountId);
                }

                using (AuthRepository Repo = new AuthRepository())
                {
                    _authUser = Repo.GetAuthenticatedUserById(CurrentUser.EmployeeInfoId);
                }

                var _authManager = HttpContext.GetOwinContext().Authentication;
                var _identity    = new ClaimsIdentity(User.Identity);

                _identity.RemoveClaim(_identity.FindFirst(ClaimTypes.Role));
                _identity.AddClaim(new Claim(ClaimTypes.Role, _authUser.Role));
                _identity.RemoveClaim(_identity.FindFirst(ClaimTypes.Name));
                _identity.AddClaim(new Claim(ClaimTypes.Name, _authUser.FirstName + " " + _authUser.LastName));
                //_identity.RemoveClaim(_identity.FindFirst("AccountNo"));
                //_identity.AddClaim(new Claim("AccountNo", "12345"));

                _authManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(
                    new ClaimsPrincipal(_identity),
                    new AuthenticationProperties
                {
                    ExpiresUtc   = DateTime.UtcNow.AddMinutes(30),
                    AllowRefresh = true,
                    IsPersistent = false
                }
                    );

                return(RedirectToAction("Dashboard", "Home", new { Area = "Employee" }));
            }

            catch (Exception ex)
            {
                TempData["Msg"] = AlertMessageProvider.FailureMessage(ex.ToString());

                return(View());
            }
        }
예제 #30
0
 private static void AddCourseRole(this ClaimsIdentity identity, string courseId, CourseRoleType roleType)
 {
     identity.AddClaim(new Claim(courseRoleClaimType, courseId + " " + roleType));
 }