public override void OnAuthorization(HttpActionContext actionContext)
        {
            actionContext.Request.Headers.TryGetValues("Authorization", out IEnumerable <string> authorisations); // recupere les valeurs d'Authorization -> bearer blablabla



            string token = authorisations.SingleOrDefault(t => t.StartsWith("Bearer ")); // n'en retourner qu'un seul qui commence par Bearer .



            if (token is null)                                                                 // si pas de valeur trouvée
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); //défini la réponse si le token est null
            }
            else
            {
                UserGlobal user = TokenService.Instance.DecodeToken(token); // ????



                if (user is null) // plus valide dans le temps par exemple
                {
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                }
                else
                {
                    // ????????????? quel action ?
                }
            }
        }
示例#2
0
    ///-----------------------------------------------------
    /// <summary>
    /// Name          : Page_Load()
    /// Description   : 페이지 로드
    /// </summary>
    ///-----------------------------------------------------
    protected void Page_Load(object sender, EventArgs e)
    {
        string strFamilyEventNo = string.Empty;

        strFamilyEventNo = UserGlobal.GetValue(Request.QueryString["familyeventno"]);
        Int64.TryParse(strFamilyEventNo, out intFamilyEventNo);
    }
        public UserGlobal DecodeToken(string token)
        {
            UserGlobal user = null;                                                                     // défini le user à null

            token = token.Replace("Bearer ", "");                                                       // supprimer le Bearer du token
            JwtSecurityToken jwtSecurityToken = Handler.ReadJwtToken(token);                            // permet de récuperer le payload

            if (jwtSecurityToken.ValidFrom <= DateTime.Now && jwtSecurityToken.ValidTo >= DateTime.Now) // vérification de la validité du token
            {
                JwtPayload payload = jwtSecurityToken.Payload;                                          //
                string     test    = Handler.WriteToken(new JwtSecurityToken(Header, payload));         // regénère le token sur base des information du payload

                if (token == test)                                                                      // si vrais = authentifié
                {
                    payload.TryGetValue("Id", out object id);                                           // défini les info reçue
                    payload.TryGetValue("LastName", out object lastName);
                    payload.TryGetValue("FirstName", out object firstName);
                    payload.TryGetValue("Login", out object login);
                    user = new UserGlobal()
                    {
                        Id        = int.Parse((string)id),
                        LastName  = (string)lastName,
                        FirstName = (string)firstName,
                        Login     = (string)login,
                    };
                }
            }



            return(user); // si le token est pas valid, le user retourné sera null.
        }
示例#4
0
        ///----------------------------------------------------------------------
        /// <summary>
        /// 로그아웃을 한다.
        /// </summary>
        /// Author         : [email protected], 2007-07-03
        ///
        /// Modify History : Just Created.
        ///
        ///----------------------------------------------------------------------
        public void LogOut()
        {
            //쿠키 제거
            UserGlobal.RemoveCookie(UserGlobal.BOQ_DEFAULT_COOKIE);

            //사용자 정보 초기화
            ClearUserInfo();
        }
示例#5
0
        private string GlobalNameOrDefault(GlobalDataItem_v2 sGlobal, Address address)
        {
            if (!string.IsNullOrWhiteSpace(sGlobal.Name))
            {
                return(sGlobal.Name);
            }

            return(UserGlobal.GenerateDefaultName(address));
        }
        [Route("api/Auth/Login")]                                     //défini la route liée a la méthode **** PS: si les méthodes sont du même type (post, put, delete, get), la route devra être différente.
        public UserGlobal Login([FromBody] LoginForm form)            // récupère un formulaire adéquat en paramètre dans lequel la sérialisation du JSON pourra être injecté
        {
            UserGlobal user = _repo.Login(form.Login, form.Password); // récupération de l'utilisateur

            if (user != null)
            {
                user.Token = TokenService.Instance.EncodeToken(user); //ajout du token dans l'utilisateur
            }
            return(user);
        }
 public static UserClient ToClient(this UserGlobal user) // retourne un UserClient à partir d'une méthode d'extension d'un UserGlobal -> (this UserGlobal user)
 {
     return(new UserClient()
     {
         Id = user.Id,
         LastName = user.LastName,
         FirstName = user.FirstName,
         Login = user.Login,
         Password = user.Password,
         Token = user.Token,
     });
 }
示例#8
0
 void Awake()
 {
     if (Instance == null)
     {
         DontDestroyOnLoad(gameObject);
         Instance = this;
     }
     else if (Instance != this)
     {
         Destroy(gameObject);
     }
 }
示例#9
0
 //-------------------------------------------------------------
 /// <summary>
 /// Name          : Page_Load()
 /// Description   : 페이지 로드
 /// </summary>
 //-------------------------------------------------------------
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         //쿠키 삭제
         UserGlobal.RemoveCookie(UserGlobal.BOQ_DEFAULT_COOKIE);
     }
     catch (Exception pl_objEx)
     {
         UtilLog.WriteExceptionLog(pl_objEx.Message, pl_objEx.StackTrace, false);
     }
     finally
     {
         Response.Redirect(UserGlobal.BOQ_LOGIN_URL);
     }
 }
        } // génération du Header

        public string EncodeToken(UserGlobal user)
        {
            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                Header,                 //fourni le header du token
                new JwtPayload(         // fourni le payload du token -> les datas
                    issuer: null,       // de qui le token est généré
                    audience: null,     // a qui le token est destiné
                    claims: new Claim[] // liste des informations
            {
                new Claim("Id", user.Id.ToString()),
                new Claim("LastName", user.LastName),
                new Claim("FirstName", user.FirstName),
                new Claim("Login", user.Login),
            },
                    notBefore: DateTime.Now,         // date de génération du token
                    expires: DateTime.Now.AddDays(1) // date de validité du token
                    )
                );



            return(Handler.WriteToken(jwtSecurityToken)); // génère le token
        }
 public void Register([FromBody] UserGlobal entity)
 {
     _repo.Register(entity);
 }
示例#12
0
        public UserSession()
        {
            string pl_strErrMsg     = string.Empty;
            string pl_strCookieInfo = string.Empty;

            string[]   pl_arrCookieInfo = null;
            HttpCookie pl_objCookie     = null;

            _isLogin = false;

            try
            {
                pl_objCookie = HttpContext.Current.Request.Cookies[UserGlobal.BOQ_DEFAULT_COOKIE];
                if (pl_objCookie == null)
                {
                    pl_strErrMsg = "쿠키 " + UserGlobal.BOQ_DEFAULT_COOKIE + " 조회 실패";
                    _isLogin     = false;
                    return;
                }
                else if (string.IsNullOrEmpty(pl_objCookie.Value))
                {
                    pl_strErrMsg = "쿠키 " + UserGlobal.BOQ_DEFAULT_COOKIE + " 조회 - 빈값";
                    _isLogin     = false;
                    return;
                }

                pl_strCookieInfo = UserGlobal.GetDecryptStr(pl_objCookie.Value);
                if (string.IsNullOrEmpty(pl_strCookieInfo))
                {
                    pl_strErrMsg = "쿠키 " + UserGlobal.BOQ_DEFAULT_COOKIE + " 정보 조회 실패";
                    _isLogin     = false;
                    return;
                }

                pl_arrCookieInfo = pl_strCookieInfo.Split('/');
                if (!pl_arrCookieInfo.Length.Equals(7))
                {
                    pl_strErrMsg = "쿠키 " + UserGlobal.BOQ_DEFAULT_COOKIE + " 상세 정보 조회 실패";
                    _isLogin     = false;
                    return;
                }

                Int32.TryParse(pl_arrCookieInfo[0], out _intUserNo);
                _strUserID   = pl_arrCookieInfo[1];
                _strUserName = pl_arrCookieInfo[2];
                _strPhoneNo  = pl_arrCookieInfo[3];
                Int16.TryParse(pl_arrCookieInfo[4], out _intUserAuth);
                Int16.TryParse(pl_arrCookieInfo[5], out _intUserRole);
                Int16.TryParse(pl_arrCookieInfo[6], out _intStateCode);

                if (!_intUserNo.Equals(0) && !string.IsNullOrEmpty(_strUserID))
                {
                    _isLogin = true;

                    var encFamilyEventNo = HttpContext.Current.Request.QueryString["encfamilyeventno"];

                    if (!string.IsNullOrWhiteSpace(encFamilyEventNo))
                    {
                        Int64 intDecFamilyEventNo = Convert.ToInt64(UserGlobal.GetDecryptStr(encFamilyEventNo));

                        InsFamilyEventJoin(_intUserNo, intDecFamilyEventNo, out pl_strErrMsg);
                    }
                }
            }
            catch (Exception pl_objEx)
            {
                //사용자 정보 초기화
                LogOut();
                UtilLog.WriteExceptionLog(pl_objEx.Message, pl_objEx.StackTrace);
            }
            finally
            {
                pl_objCookie = null;
                if (!_isLogin)
                {
                    LogOut();
                    UtilLog.WriteCommonLog("UserSession", "UserSession", pl_strErrMsg);

                    Uri referrer = HttpContext.Current.Request.UrlReferrer;
                    if (referrer != null)
                    {
                        UtilLog.WriteCommonLog("UserSession", "UserSession", "요청위치: " + referrer.OriginalString.ToLower());
                    }
                }
            }

            return;
        }
示例#13
0
        public static void SendMail(string strSubject, string strAddMailTo, string strMailInfo, int intRetVal, string strErrMsg)
        {
            StringBuilder pl_sbMailInfo = null;
            StringBuilder pl_sbMailBody = null;
            HttpContext   pl_objCtx     = null;
            MailMessage   pl_objMessage = null;
            SmtpClient    pl_objClient  = null;

            string pl_strMailSuject = string.Empty;
            string pl_strIPAddr     = string.Empty;

            try
            {
                pl_sbMailInfo = new StringBuilder();
                pl_sbMailBody = new StringBuilder();

                pl_objCtx    = HttpContext.Current;
                pl_strIPAddr = UserGlobal.GetClientIP();

                pl_strMailSuject = string.Format("[{0}][{1}][{2}]-{3}", Dns.GetHostName().ToUpper(), "FamilyEvent", strSubject, pl_objCtx.Request.ServerVariables.Get("HTTP_HOST") + pl_objCtx.Request.FilePath.ToString());

                pl_sbMailInfo.Append("<B>Server</B><BR/>");
                pl_sbMailInfo.AppendFormat("ServerName: {0}", pl_objCtx.Request.ServerVariables.Get("HTTP_HOST"));
                pl_sbMailInfo.AppendFormat("<br>ServerIP: {0}", pl_objCtx.Request.ServerVariables.Get("LOCAL_ADDR"));
                pl_sbMailInfo.AppendFormat("<br>RemoteIP: {0}", pl_strIPAddr);
                pl_sbMailInfo.Append("<BR/>");
                if (!string.IsNullOrEmpty(strMailInfo))
                {
                    pl_sbMailInfo.Append(strMailInfo);
                }
                pl_sbMailInfo.Append("<BR/>");
                pl_sbMailInfo.Append("<BR/><B>Error Code</B><BR/>");
                pl_sbMailInfo.Append(intRetVal);
                pl_sbMailInfo.Append("<BR/><B>Error Message</B><BR/>");
                pl_sbMailInfo.Append(strErrMsg);

                // --------------------------------------------------
                // To let the page finish running we clear the error
                // --------------------------------------------------
                pl_sbMailBody.Append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>");
                pl_sbMailBody.Append("<HTML>");
                pl_sbMailBody.Append("    <HEAD>");
                pl_sbMailBody.Append("        <META HTTP-EQUIV='Content-Type' Content='text/html; charset=ks_c_5601-1987'>");
                pl_sbMailBody.Append("        <STYLE type='text/css'>");
                pl_sbMailBody.Append("          BODY { font: 9pt/12pt Tahoma }");
                pl_sbMailBody.Append("          H1 { font: 13pt/15pt Tahoma }");
                pl_sbMailBody.Append("          H2 { font: 9pt/12pt Tahoma }");
                pl_sbMailBody.Append("          A:link { color: red }");
                pl_sbMailBody.Append("          A:visited { color: maroon }");
                pl_sbMailBody.Append("        </STYLE>");
                pl_sbMailBody.Append("    </HEAD>");
                pl_sbMailBody.Append("    <BODY>");
                pl_sbMailBody.Append("        <TABLE width=500 border=0 cellspacing=10>");
                pl_sbMailBody.Append("            <TR>");
                pl_sbMailBody.Append("                <TD>");
                pl_sbMailBody.Append(pl_sbMailInfo);
                pl_sbMailBody.Append("                </TD>");
                pl_sbMailBody.Append("            </TR>");
                pl_sbMailBody.Append("        </TABLE>");
                pl_sbMailBody.Append("    </BODY>");
                pl_sbMailBody.Append("</HTML>");

                pl_objMessage      = new MailMessage();
                pl_objMessage.From = new MailAddress(UserGlobal.BOQ_ADDRESS_FROM, UserGlobal.BOQ_ADDRESS_FROM);
                pl_objMessage.To.Add(UserGlobal.BOQ_ADDRESS_TO);
                //추가 주소가 있는 경우
                if (!string.IsNullOrEmpty(strAddMailTo))
                {
                    foreach (string pl_strMailTo in strAddMailTo.Split(';'))
                    {
                        pl_objMessage.To.Add(pl_strMailTo);
                    }
                }
                pl_objMessage.BodyEncoding    = Encoding.UTF8;
                pl_objMessage.SubjectEncoding = Encoding.UTF8;
                pl_objMessage.Subject         = pl_strMailSuject;
                pl_objMessage.Body            = pl_sbMailBody.ToString();
                pl_objMessage.IsBodyHtml      = true;

                if (string.IsNullOrEmpty(UserGlobal.BOQ_SMTP_ID))
                {
                    pl_objClient = new SmtpClient(UserGlobal.BOQ_SMTP_SERVER);
                }
                else
                {
                    pl_objClient = new SmtpClient(UserGlobal.BOQ_SMTP_SERVER);
                    pl_objClient.UseDefaultCredentials = false;
                    pl_objClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    pl_objClient.Credentials           = new NetworkCredential(UserGlobal.BOQ_SMTP_ID, UserGlobal.BOQ_SMTP_PWD);
                }

                pl_objClient.Send(pl_objMessage);
            }
            catch (SmtpException pl_objEx)
            {
                UtilLog.WriteExceptionLog(pl_objEx.Message, pl_objEx.StackTrace);
            }
            finally
            {
                pl_sbMailInfo = null;
                pl_sbMailBody = null;
                pl_objCtx     = null;

                if (pl_objMessage != null)
                {
                    pl_objMessage.Dispose();
                    pl_objMessage = null;
                }

                if (pl_objClient != null)
                {
                    pl_objClient.Dispose();
                    pl_objClient = null;
                }
            }
        }
示例#14
0
        //-------------------------------------------------------------
        /// <summary>
        /// 메인 프로세스
        /// </summary>
        //-------------------------------------------------------------
        public virtual void ProcessRequest(HttpContext objContext)
        {
            int    pl_intRetVal     = 0;
            string pl_strJsonResult = string.Empty;
            string pl_strReqParam   = string.Empty;
            string pl_strErrMsg     = string.Empty;

            HttpRequest     pl_objRequest  = null;
            HttpResponse    pl_objResponse = null;
            DefaultReqParam pl_objReqParam = new DefaultReqParam();
            DefaultResParam pl_objResParam = new DefaultResParam();
            MethodSet       objMethodAttr  = null;
            MethodInfo      objMethodInfo  = null;

            object[] parameters = null;     // 메소드의 in/out 파라미터

            try
            {
                strPageMethodName = MethodBase.GetCurrentMethod().Name;

                objContext.Response.ContentType     = "text/json";
                objContext.Response.ContentEncoding = Encoding.UTF8;
                pl_objRequest  = objContext.Request;
                pl_objResponse = objContext.Response;
                pl_objResParam = new DefaultResParam();

                // 보안체크 1. UrlReferrer 확인
                if (!UserGlobal.GetUrlReferrer(pl_objRequest, out strRefererUrl))
                {
                    pl_intRetVal = 4001;
                    pl_strErrMsg = "Failed to GetUrlReferrer";
                    return;
                }

                // 보안체크 2. 전송 파라미터(json) 확인
                using (StreamReader objSR = new StreamReader(pl_objRequest.InputStream))
                {
                    pl_strReqParam = objSR.ReadToEnd();
                    JsonSerializerSettings set = new JsonSerializerSettings();
                    set.NullValueHandling = NullValueHandling.Ignore;
                    pl_objReqParam        = JsonConvert.DeserializeObject <DefaultReqParam>(pl_strReqParam, set);

                    if (pl_objReqParam == null)
                    {
                        pl_intRetVal = 4002;
                        pl_strErrMsg = "RequestParam is Empty";
                        return;
                    }
                }

                // 보안체크 3.AjaxTicket 확인
                if (!UserGlobal.VerifyAjaxTicket(strRefererUrl, pl_objReqParam.strAjaxTicket))
                {
                    pl_intRetVal = 4003;
                    pl_strErrMsg = "Failed to VerifyAjaxTicket";
                    return;
                }

                // 보안체크 4. 메소드 이름 확인
                try
                {
                    // front 에서 호출한 메소드 이름이 같은 메소드가 있으면 할당
                    objMethodInfo = this.GetType().GetMethod(pl_objReqParam.strMethodName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                    // 해당 메소드의 MethodSet 어노테이션 할당.
                    objMethodAttr = objMethodInfo.GetCustomAttribute(typeof(MethodSet)) as MethodSet;
                }
                catch {
                    pl_intRetVal = 4004;
                    pl_strErrMsg = "Invalid strMethodName";
                    return;
                }

                // 보안체크 5. 메소드 접근권한 체크.
                if (objMethodAttr.pageType.Equals(PageAccessType.Login))
                {
                    objSes = new UserSession();
                    if (!objSes.isLogin)
                    {
                        pl_intRetVal = 4005;
                        pl_strErrMsg = "do not have permission.";
                        return;
                    }
                }

                // 생성된 파라미터를 핸들러 메소드에 넣어준다.
                // PLNOTICE 요청, 응답, 메시지 꼭 이 순서로 함수를 구성하여야한다.
                parameters = new object[] { GetParamter(strReq, objMethodInfo, pl_strReqParam), GetParamter(strRes, objMethodInfo), null };

                // 핸들러 메소드 실행
                pl_intRetVal = (int)objMethodInfo.Invoke(this, parameters);
                // 실행 후 반환 된 응답값을 pl_objResParam에 담아준다.
                pl_objResParam = Convert.ChangeType(parameters[1], Type.GetType(objMethodInfo.GetParameters()[1].ParameterType.AssemblyQualifiedName)) as DefaultResParam;
                // 실행 후 반환 된 메시지값을 pl_strErrMsg에 담아준다.
                if (!pl_intRetVal.Equals(0))
                {
                    pl_strErrMsg = (string)parameters[2];
                    return;
                }
            }
            catch (Exception pl_objEx)
            {
                pl_intRetVal = -24001;
                UtilLog.WriteExceptionLog(pl_objEx.Message, pl_objEx.StackTrace);
            }
            finally
            {
                pl_objResParam.intRetVal = pl_intRetVal;

                if (!pl_intRetVal.Equals(0))
                {
                    UtilLog.WriteLog(strPageMethodName, pl_intRetVal, "ReqParameter : " + JsonConvert.SerializeObject(pl_objReqParam) + "ErrMsg : " + pl_strErrMsg);

                    // 4000번대 에러인 경우 대표메시지 설정.
                    if ((pl_intRetVal / 1000).Equals(4))
                    {
                        pl_objResParam.strErrMsg = "잘못된 접근입니다.";
                    }
                    // 대표메시지가 설정되어 있는 경우 대표메시지 출력
                    else if (objMethodAttr != null && !string.IsNullOrEmpty(objMethodAttr.strRepresentMsg))
                    {
                        pl_objResParam.strErrMsg = objMethodAttr.strRepresentMsg;
                    }
                    else
                    {
                        pl_objResParam.strErrMsg = pl_strErrMsg;
                    }
                }

                // JSON 결과 리턴
                pl_strJsonResult = JsonConvert.SerializeObject(pl_objResParam);
                pl_objResponse.Write(pl_strJsonResult);

                // 로깅이 필요한 메소드의 경우 인/아웃풋 로깅
                if (objMethodAttr != null && objMethodAttr.loggingFlag)
                {
                    UtilLog.WriteLog(strPageMethodName, pl_intRetVal, string.Format("ReqParam = {0}", pl_strReqParam));
                    UtilLog.WriteLog(strPageMethodName, pl_intRetVal, string.Format("Method : {0}, JsonData: {1}", pl_objReqParam.strMethodName, pl_strJsonResult));
                }

                pl_objReqParam = null;
                pl_objRequest  = null;
                pl_objResponse = null;
                pl_objResParam = null;
            }

            return;
        }