示例#1
0
        internal override AccessCredentials ParseResponse(HttpResponseMessage response)
        {
            this.Validate();
            AccessCredentials credentials = base.ParseResponse(response);

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(Convert.ToString(response.Content))))
            {
                return((AccessCredentials) new XmlSerializer(typeof(AccessCredentials)).Deserialize(stream));
            }
        }
示例#2
0
        public bool RequestAccessToken(Area area, string character, out AccessCredentials accessCredentials)
        {
            const string ROUTE = "/api/token/entity";

            return(GetToken(ROUTE, new[]
            {
                new KeyValuePair <string, string>("map", area.ToString()),
                new KeyValuePair <string, string>("char_name", character)
            },
                            out accessCredentials));
        }
示例#3
0
        /// <summary>
        /// Generate HTTP request object to obtain the access token.
        /// </summary>
        /// <param name="credentials">Auth credentials (id and secret)</param>
        /// <returns>UnityWebRequest object</returns>
        public virtual UnityWebRequest GenerateAuthRequest(AccessCredentials credentials)
        {
            var form = new Dictionary <string, string>()
            {
                { "grant_type", "client_credentials" },
                { "client_id", credentials.clientId },
                { "client_secret", credentials.clientSecret },
            };

            return(HttpPost(GetAuthUrl(), form));
        }
        public async Task <object> Login(
            [FromBody] AccessCredentials credenciais,
            [FromServices] UserManager <ApplicationUser> userManager,
            [FromServices] SignInManager <ApplicationUser> signInManager,
            [FromServices] SigningConfigurations signingConfigurations,
            [FromServices] TokenConfigurations tokenConfigurations)
        {
            bool credenciaisValidas = false;

            if (credenciais != null && !String.IsNullOrWhiteSpace(credenciais.Email))
            {
                try
                {
                    // Verifica a existência do usuário nas tabelas do ASP.NET Core Identity
                    var userIdentity = userManager.FindByNameAsync(credenciais.Email).Result;

                    if (userIdentity != null)
                    {
                        // Efetua o login com base no Id do usuário e sua senha
                        var resultadoLogin = signInManager
                                             .CheckPasswordSignInAsync(userIdentity, credenciais.Password, false)
                                             .Result;
                        if (resultadoLogin.Succeeded)
                        {
                            // Verifica se o usuário em questão possui a role App
                            credenciaisValidas = userManager.IsInRoleAsync(
                                userIdentity, Roles.ROLE_APP).Result;
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }

            if (credenciaisValidas)
            {
                Token resultado = await GenerateTokenAsync(
                    credenciais.Email, signingConfigurations,
                    tokenConfigurations, credenciais.RefreshToken, userManager);

                return(resultado);
            }
            else
            {
                return(new
                {
                    authenticated = false,
                    message = "Falha ao autenticar"
                });
            }
        }
        private void ValidateAppVersion(ResponseBase response, AccessCredentials credentials)
        {
            if (String.IsNullOrEmpty(credentials.Platform) || String.IsNullOrEmpty(credentials.AppVersion))
            {
                return;
            }

            if (!credentials.Platform.ToUpper().Equals(RESTAPIPlatform.web.ToString().ToUpper()))
            {
                // Application version validation is applied only
                // for Android and iOS platforms as of now
                return;
            }
        }
        private void ParseAuthorizationHeader(string credentialsValue, AccessCredentials credentials, ResponseBase response)
        {
            const string CredentialRegExPattern = "SessionToken *= *\"([^\\s]*)\" *, *CallerId *= *\"([^\\s]*)\" *";

            Match match = Regex.Match(credentialsValue, CredentialRegExPattern);

            if (!match.Success)
            {
                response.ErrorList.Add(new FormatValidationFault("Authorization header is not in correct format", CredentialRegExPattern));
                return;
            }

            credentials.SessionToken = match.Groups[1].ToString();
            credentials.CallerId     = match.Groups[2].ToString();
        }
        private void validateUserIdWithToken(ResponseBase r, AccessCredentials credentials)
        {
            DatabaseWrapper.databaseOperation(r, (context, query) => {
                UserAuthentication userAuthentication = query.GetAuthenticationByToken(context, credentials.SessionToken, credentials.CallerId);
                if (userAuthentication == null)
                {
                    r.ErrorList.Add(new FormatValidationFault("Authorization header is not valid", "Authorizationheader"));
                    return;
                }

                credentials.UserID    = userAuthentication.UserId;
                credentials.CallerId  = userAuthentication.CallerId;
                credentials.Token     = userAuthentication.Token;
                credentials.LoginDate = userAuthentication.CreatedDate;
            }, readOnly: true);
        }
示例#8
0
        private bool GetToken(string route, IEnumerable<KeyValuePair<string, string>> parameters, out AccessCredentials accessCredentials)
        {
            accessCredentials = null;

            JObject response;
            if (Http.Get(route, parameters, out response, _cookie))
            {
                if (response.GetValue("status").ToString().Equals("ok"))
                {
                    accessCredentials = new AccessCredentials
                    {
                        Area = (Area)Enum.Parse(typeof(Area), response.GetValue("map").ToString()),
                        ClientId = response.GetValue("client_id").ToString(),
                        EntityId = Guid.Parse(response.GetValue("entity_id").ToString()),
                        EntityToken = response.GetValue("entity_token").ToString(),
                        IsOutpost = response.GetValue("is_outpost").Value<bool>()
                    };

                    return true;
                }
            }

            return false;
        }
示例#9
0
        public bool RequestAccessToken(Area area, string character, out AccessCredentials accessCredentials)
        {
            const string ROUTE = "/api/token/entity";

            return GetToken(ROUTE, new[]
                    {
                                        new KeyValuePair<string, string>("map", area.ToString()),
                                        new KeyValuePair<string, string>("char_name", character)
                                },
                            out accessCredentials);
        }