profile.User.Identity.IsAuthenticated 返回 false 没有人帮助我

Posted

技术标签:

【中文标题】profile.User.Identity.IsAuthenticated 返回 false 没有人帮助我【英文标题】:profile.User.Identity.IsAuthenticated return false nobody helped me 【发布时间】:2021-09-02 23:40:47 【问题描述】:

我正在尝试将带有另一个项目 (c#) 的 Web 服务构建连接到我的项目 (asp.net mvc)。目前我可以登录和注销,但我无法将查询带到我的项目中,因为 profile.User.Identity.IsAuthenticated 它返回 false。

这是我如何调用登录查询和另一个查询来带来一些信息。当我使用网络浏览器连接时,它们都可以工作。问题在于身份。

我的项目

//LOGIN USING WEBSERVICE
    [HttpPost]
    public IActionResult Login(LoginViewModel _login)
    

        using (var client = new WebClient())
        
            client.Headers.Add("Content-Type:application/json"); //Content-Type  
            client.Headers.Add("Accept:application/json");
            string result = 
 client.DownloadString("http://localhost/Services/BlueLifeDataService.svc/Login?login='" + 
 _login.db + "\\" + _login.Username + "'&password='" + _login.Password + "'");
            var _result = JsonConvert.DeserializeObject<dynamic>(result);
            if(_result["d"]["Login"].Value == true)
            
                Response.Cookies.Append("User", _login.Username);
                return RedirectToAction("Index");
            
            else
            
                return View();
            
        
    

    //BRING QUERY 
    public  IActionResult Get()
    
    
        using (var client = new WebClient())
        
            client.Headers.Add("Content-Type:application/json"); //Content-Type  
            client.Headers.Add("Accept:application/json");
            string result = 
 client.DownloadString("http://localhost/Services/BlueLifeDataService.svc/Aircraft?");
            var _result = JsonConvert.DeserializeObject<dynamic>(result);

            return View();
          
        

    

C# 中的网络服务

 public class BlueLifeDataService : DataService<BlueLifeEntities>
 
    private CommonProfile profile = new CommonProfile();

    /**
    // To call http://localhost:81/Services/BlueLifeDataService.svc/GetTechLog?id=3810L do 
  this
    [DataContract]
    class TechLogDTO 
    
        public TechLogDTO() 
        
        

        [DataMember]
        public long idTechlog  get; set; 
        [DataMember]
        public string sPilot  get; set; 
        [DataMember]
        public string sRemark  get; set; 
        [DataMember]
        public string sAircraftReg  get; set; 
        [DataMember]
        public string sTLNumber  get; set; 
        [DataMember]
        public EntityCollection<CRS> CRS  get; set; 
        public EntityCollection<Files> Files  get; set; 
        public EntityCollection<FlightsAirframe> FlightsAirframe  get; set; 
    

    //To call http://localhost:81/Services/BlueLifeDataService.svc/GetTechLog?id=3810L do this
    [WebGet]
    [WebInvoke(UriTemplate = "GetTechLog?id=id", Method = "GET", ResponseFormat = 
  WebMessageFormat.Json,
     BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json)]
    public string GetTechLog(long id)
    
        string json;
        using (MemoryStream ms = new MemoryStream())
        
            DataContractJsonSerializer ser = new 
  DataContractJsonSerializer(typeof(TechLogDTO));
            TechLog e = this.CurrentDataSource.TechLog.FirstOrDefault(t => t.idTechlog == id);
            ser.WriteObject(ms, new TechLogDTO 
             
                idTechlog = e.idTechlog, 
                sAircraftReg = e.sAircraftReg,
                sTLNumber = e.sTLNumber,
                sPilot = e.sPilot,
                sRemark = e.sRemark,
                CRS = e.CRS,
                Files = e.Files,
                FlightsAirframe = e.FlightsAirframe
            );
            json = System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, 
  Convert.ToInt16(ms.Length));
        

        return json;
    
    */


   #region Configuration

    // Cette méthode n'est appelée qu'une seule fois pour initialiser les stratégies au niveau 
   des services.
    public static void InitializeService(DataServiceConfiguration config)
    
        // TODO: définissez des règles pour indiquer les jeux d'entités et opérations de 
   service visibles, pouvant être mis à jour, etc.
        // Exemples :
        config.SetEntitySetAccessRule("*", EntitySetRights.All);
        config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

        config.UseVerboseErrors = 
   bool.Parse(RoleEnvironment.GetConfigurationSettingValue("UseVerbose"));
        config.SetEntitySetPageSize("TechLog", 
   int.Parse(RoleEnvironment.GetConfigurationSettingValue("TechLogEntitiesPerPage")));
    

    protected override BlueLifeEntities CreateDataSource()
    
        if (profile.User.Identity.IsAuthenticated)
        
            string connection =
                DBConnectionString.GetEntityConnectionString(profile.DataBase, 
   "Datasets.BlueLife.BlueLifeModel");

            var context = new BlueLifeEntities(connection)
            
                CommandTimeout = 
   int.Parse(RoleEnvironment.GetConfigurationSettingValue("SQLCommandTimeout"))
            ;

            return context;
        

        return base.CreateDataSource();
    

     [WebGet]
    public bool Login(string login, string password)
    
        if (Membership.ValidateUser(login, password) &&
            ServiceAuthHeaderValidation.HasAccessToApplication(login.Split('\\')[0], 
 "BlueLifeServiceSoapClient"))
        
            if (!Roles.IsUserInRole(login, "iPhone") & !Roles.IsUserInRole(login, "Client"))
                return false;

            FormsAuthentication.SetAuthCookie(login, false);
            return true;
        
        else
            return false;
    


    [WebGet]
    public bool Logout()
    
        if (!HttpContext.Current.Request.IsAuthenticated)
            return false;

        FormsAuthentication.SignOut();
        return true;
    

    #endregion

    #region Operations

    [WebGet]
    public void UpdateFollowingNewTechLog(string aircraftRegistration)
    
        if (!profile.User.Identity.IsAuthenticated)
            throw new ArgumentNullException("You're not authenticated. Please, Log in!");

        var lastTL = (from t in this.CurrentDataSource.TechLog
                      where t.sAircraftReg == aircraftRegistration
                      orderby t.idTechlog descending
                      select t).FirstOrDefault();

        var countersToUpdate = (from c in this.CurrentDataSource.Counter
                                where c.sAircraftReg == aircraftRegistration
                                select c.idCounter).ToList();

        var crewMembersToUpdate = this.CurrentDataSource.FlightCrew.Where(fc => fc.idPilot != 
 null &&
            fc.FlightsAirframe.TechLog.idTechlog == lastTL.idTechlog).OrderByDescending(fc => 
 fc.idFlightCrew)
            .Select(fc => fc.idPilot).Distinct().ToList();

        var plannedDutiesToUpdate = this.CurrentDataSource.CrewDuty.Where(cd => cd.idPilot != 
 null &&
            cd.idTechlog == lastTL.idTechlog).OrderByDescending(cd => cd.idCrewDuty)
            .Select(cd => cd.idPilot).Distinct().ToList();

    #region Interceptor

    [QueryInterceptor("Aircraft")]
    public Expression<Func<Aircraft, bool>> OnQueryAircraft()
    
        string login = HttpContext.Current.Request.QueryString["login"]; 
        string password = HttpContext.Current.Request.QueryString["password"];
        if(!String.IsNullOrEmpty(login) && !String.IsNullOrEmpty(password))
        
            bool result = Login(login, password);
            if(result)
            
                return (Aircraft a) => PersonalFleet.Contains(a.sAircraftReg);
            
            else
            
                return (Aircraft a) => false;
            
        

      
        // Loged in user in this project + Calling from other project
        if (!profile.User.Identity.IsAuthenticated)
        
            return (Aircraft a) => false;
        

        return (Aircraft a) => PersonalFleet.Contains(a.sAircraftReg);
    

【问题讨论】:

【参考方案1】:

从我在您的项目代码中看到的内容来看,您正在 Get 操作中创建一个新的 WebClient,但您没有传递您在调用 Web 服务时在 Login 操作中收到的 FormsAuthentication cookie -因此它无法验证该请求。你可能想看看:WebClient accessing page with credentials

【讨论】:

以上是关于profile.User.Identity.IsAuthenticated 返回 false 没有人帮助我的主要内容,如果未能解决你的问题,请参考以下文章