'C# Web 접속 로그인함수'에 해당되는 글 1건

728x90

C# 에서 Web 접속방식으로 로그인 처리를 위한 방법을 소개한다.


http://link2me.tistory.com/970 에 기본적인 사항을 적어두었다.


HttpClient 방식으로 로그인하는 방법을 알아두면 여러모로 유용하다.

로그인 뿐만 아니라 Web 접속방식으로 데이터를 주고 받을 때 많이 활용된다.

json 형태로 데이터를 주고 받기 위한 함수만 추가로 만들어서 사용하면 된다.


string json 부분을 보면 PHP 로그인 함수 결과값을 받는다.

PHP 에서 도대체 어떤 걸 받는거지? 라고 하는 의문이 들 것이다.

PHP 결과를 받는 것은 echo 문의 결과값이다.

이 결과값이 배열일 수도 있고 단순한 텍스트일 수도 있다.

echo 문으로 출력되는 결과를 어떻게 만들 것인가 하는 것은 PHP 에서 고민하면 된다.

가령 성공하면 1, 실패하면 0, DB접속 실패하면 -1 이런식으로 PHP 로그인 함수를 만들어도 된다.

개발자의 취향에 따라 개발해서 연동하면 된다.


=== LoginForm.cs ====

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Http;
using System.Web.Script.Serialization;
using System.IO;
using System.Configuration;

namespace Dennis_Sentence
{
    public partial class frmLogin : Form
    {
        Boolean CK = false;
        private string strID;

        public frmLogin()
        {
            InitializeComponent();
        }

        public string getstrID   // ID를 알려주는 속성 설정
        {
            get { return strID; }
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            txtID.Text = Properties.Settings.Default.LoginIDSave;
            txtPwd.Text = Properties.Settings.Default.SitePasswd;
            if (Properties.Settings.Default.LoginIDSave.Length > 0 && Properties.Settings.Default.SitePasswd.Length > 0)
            {
                IDSave.Visible = false;
                IDdelete.Visible = true;
            }
            else
            {
                IDSave.Visible = true;
                IDdelete.Visible = false;
            }
        }

        /// <summary>
        /// SQL 인젝션 필터 - Select 에서 조건절 필터링
        /// </summary>
        private static string Filtering(string inputSQL)
        {
            return inputSQL.Replace(":", "").Replace("+", "").Replace(";", "").Replace("--", "").Replace("\"", "");
        }

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!CK)
            {
                Application.Exit();
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {

            if (this.txtID.Text == "")
            {
                MessageBox.Show("로그인 아이디를 입력하세요", "알림", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtID.Focus();
            }
            else if (this.txtPwd.Text == "")
            {
                MessageBox.Show("로그인 비밀번호를 입력하세요", "알림", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtPwd.Focus();
            }
            else
            {
                if (IDSave.Checked)
                {
                    Properties.Settings.Default.LoginIDSave = txtID.Text;
                    Properties.Settings.Default.SitePasswd = txtPwd.Text;
                    Properties.Settings.Default.Save();
                }

                if (IDdelete.Checked)
                {
                    Properties.Settings.Default.LoginIDSave = string.Empty;
                    Properties.Settings.Default.SitePasswd = string.Empty;
                    Properties.Settings.Default.Save();
                }

                mySqlLogin();
            }

        }

        private void mySqlLogin()
        {
            try
            {
                var client = new HttpClient();
                var postData = new List<KeyValuePair<string, string>>();
                string URL = "http://IP주소/Login.php";
                postData.Add(new KeyValuePair<string, string>("loginID", Filtering(txtID.Text.Trim())));
                postData.Add(new KeyValuePair<string, string>("loginPW", Filtering(txtPwd.Text.Trim())));
                var formContent = new FormUrlEncodedContent(postData);
                var result = client.PostAsync(URL, formContent).Result;
                string json = result.Content.ReadAsStringAsync().Result;
                //MessageBox.Show(json);
                if (json == "1") // PHP 로그인 함수에서 로그인 성공시의 echo 결과값
                {
                    CK = true;
                    strID = txtID.Text;
                    this.Close();  // 현재 폼 닫기
                }
                else
                {
                    MessageBox.Show("로그인 실패", "Login Fail", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    CK = false;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error :" + ex.Message);
            }
        }       

        private void btnCancel_Click(object sender, EventArgs e)
        {
            //CK = false;
            Application.Exit();  // 취소버튼을 누르면 프로그램 완전 종료 처리
        }

        private void txtPwd_KeyDown(object sender, KeyEventArgs e)  // 엔터키를 눌렀다면...
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnOK_Click(sender, e);
            }
        }

        private void IDSave_CheckedChanged(object sender, EventArgs e)
        {
            if (IDdelete.Checked == true)
            {
                IDdelete.Checked = false;
            }
        }

        private void IDdelete_CheckedChanged(object sender, EventArgs e)
        {
            if (IDSave.Checked == true)
            {
                IDSave.Checked = false;
            }
        }
    }
       
}


=== Login.php ===

<?php
session_start();
@extract($_POST);
if(isset($loginID) && !empty($loginID) && isset($loginPW) && !empty($loginPW)) {

    require_once 'phpclass/dbinfo.php';
    require_once 'phpclass/dbClass.php';
    $conn=new MySQLDbClass(); // DB 함수 객체 생성
    $DB_CONNECT = $conn->isConnectDb($DB); // 안드로이드폰에서는 반드시 객체로 생성해야 정상접속
    require_once 'phpclass/loginClass.php';
    $c=new LoginClass(); // 로그인 객체 생성

    $row = $c->WebUserAuthCheck($loginID,$loginPW);  // 로그인 체크 함수
    if(is_array($row)) {
        if(!empty($row['id'])) {
            $_SESSION['userID'] = $row['id'];
            echo 1; // 로그인 성공
        } else {
            echo 0; // 로그인 실패
        }
    } else if($row == '0'){
        echo 0; // 로그인 실패
    } else {
        echo 0; // 로그인 실패
    }

}
?>


도움이 되셨다면 00 00 해 주세요. 좋은 글 작성에 큰 도움이 됩니다.

'C# > 통신' 카테고리의 다른 글

C# Web 자동로그인 처리  (1) 2018.03.15
C# 과 Web  (0) 2018.03.10
C# webFile 다운로드 함수  (0) 2016.11.12
C# GetAsyncDataFromWeb  (0) 2016.08.21
C# GetDataFromWeb 사용자 함수  (0) 2016.08.20
블로그 이미지

Link2Me

,