Beispiel #1
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                PlayerDTO player = new PlayerDTO()
                {
                    Email    = model.Email,
                    Password = model.Password
                };
                var claim = await playerService.Authenticate(player);

                if (claim == null)
                {
                    ModelState.AddModelError("", "Неверный логин или пароль.");
                }
                else
                {
                    AuthenticationManager.SignOut();
                    AuthenticationManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = false
                    }, claim);
                    if (String.IsNullOrEmpty(returnUrl))
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        return(Redirect(returnUrl));
                    }
                }
            }
            return(View());
        }
        public async Task <PlayerAuthenticated> Authenticate([FromBody] PlayerAuth auth)
        {
            var player = await _service.Authenticate(auth.Username, auth.Password).ConfigureAwait(false);

            if (player == null)
            {
                return(null);
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_options.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, player.Username)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            //  return basic user info (without password) and token to store client side
            return(new PlayerAuthenticated {
                Player = _mapper.Map <PlayerDTO>(player),
                Token = $"Bearer {tokenString}"
            });
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            try
            {
                var player = _service.Authenticate(context.UserName, context.Password);

                if (player == null)
                {
                    context.SetError("invalid_grant", ErrorMessages.InvalidCredentials);
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim(ClaimTypes.GivenName, player.PlayerName));

                GenericPrincipal principal = new GenericPrincipal(identity, null);
                Thread.CurrentPrincipal = principal;

                context.Validated(identity);
            }
            catch (Exception ex)
            {
                context.SetError("invalid_grant", ErrorMessages.InvalidCredentials);
            }
        }
Beispiel #4
0
        public IActionResult Authenticate(UserRequest request)
        {
            var token = _playerService.Authenticate(request.Username, request.Password);

            if (string.IsNullOrEmpty(token))
            {
                return(Unauthorized());
            }

            return(Ok(new AuthenticationResponse {
                Token = token
            }));
        }
Beispiel #5
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                IPlayerService service = _container.Resolve <IPlayerService>();

                AuthenticateRequest request = new AuthenticateRequest();
                request.Email    = context.UserName;
                request.Password = context.Password;

                AuthenticateReponse response = service.Authenticate(request);

                if (service.IsInvalid())
                {
                    if (response == null)
                    {
                        context.SetError("invalid_grant", "Preencha um e-mail válido e uma senha com pelo menos 6 caracteres.");
                        return;
                    }
                }

                service.ClearNotifications();

                if (response == null)
                {
                    context.SetError("invalid_grant", "Player não encontrado!");
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                //Definindo as Claims
                identity.AddClaim(new Claim("Player", JsonConvert.SerializeObject(response)));

                var principal = new GenericPrincipal(identity, new string[] { });

                Thread.CurrentPrincipal = principal;

                context.Validated(identity);
            }
            catch (Exception ex)
            {
                context.SetError("invalid_grant", ex.Message);
                return;
            }
        }
Beispiel #6
0
        public IActionResult Authenticate(AuthenticateRequest model)
        {
            StringBuilder log = new StringBuilder();
            string        requestParameter = "Username = "******", " + "Password = "******"{MethodName}", UtilityResource.Authenticate).Replace("{RequestParameter}", requestParameter));

            var response = _playerservice.Authenticate(model);

            if (response == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }
            else
            {
                log.Append(UtilityResource.ExecutedSuccessfully.Replace("{MethodName}", UtilityResource.Authenticate));
                LogManagers.LogManagers.WriteTraceLog(log);
                return(Ok(response));
            }
        }