Beispiel #1
0
        public async Task <IActionResult> Auth([FromServices] IUserRepository repository,
                                               [FromServices] IConfiguration configuration,
                                               [FromBody] UserAuthModel model)
        {
            try
            {
                var user = await repository.GetAsync(model.Email, model.Password);

                if (user == null)
                {
                    return(BadRequest(new { Message = "Email e/ou senha está(ão) inválido(s)." }));
                }

                var token = JwtAuthHelper.GenerateToken(configuration["KeySecretAuth"], user.ToModel());

                return(Ok(new
                {
                    Token = token,
                    Usuario = user
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new { Message = ex.Message }));
            }
        }
Beispiel #2
0
        public override bool IsAuthorized(AuthFilterContext context)
        {
            Requires.NotNull("context", context);

            if (!JwtAuthHelper.IsAuthenticated())
            {
                return(false);
            }

            if (_denyRolesSplit.Any())
            {
                var currentUser = PortalController.Instance.GetCurrentPortalSettings().UserInfo;
                if (!currentUser.IsSuperUser && _denyRolesSplit.Any(currentUser.IsInRole))
                {
                    return(false);
                }
            }

            if (_staticRolesSplit.Any())
            {
                var currentUser = PortalController.Instance.GetCurrentPortalSettings().UserInfo;
                if (!_staticRolesSplit.Any(currentUser.IsInRole))
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #3
0
 protected override Tuple <bool, string> IsAuthorized(HttpActionContext actionContext)
 {
     try
     {
         return(JwtAuthHelper.IsAuthenticatedJwtRequest(actionContext)
             ? new Tuple <bool, string>(true, string.Empty)
             : base.IsAuthorized(actionContext));
     }
     catch (Exception e)
     {
         return(new Tuple <bool, string>(false, e.Message));
     }
 }
		public async Task<ActionResult<ExportParams>> GetExportedReport([FromBody] ExportParams exportParams)
		{
			if (string.IsNullOrWhiteSpace(exportParams.PageName))
			{
				return BadRequest(Constant.MissingPageName);
			}
			else if (string.IsNullOrWhiteSpace(exportParams.FileFormat))
			{
				return BadRequest(Constant.MissingFileFormat);
			}

			try
			{
				// Get username and role of user 
				var userInfo = JwtAuthHelper.GetUsernameAndRole(User.Identity as ClaimsIdentity);

				// Generated exported file
				var exportedFile = await exportService.GetExportedFile(exportParams.PageName, exportParams.FileFormat, exportParams.PageState, userInfo.username, userInfo.role);

				return Ok(File(exportedFile.MemoryStream.ToArray(), exportedFile.MimeType, exportedFile.FileName));
			}
			catch (MsalServiceException ex)
			{
				logger.LogError(ex, ex.Message);
				return StatusCode(ex.StatusCode, ex.Message);
			}
			catch (MsalClientException ex)
			{
				logger.LogError(ex, ex.Message);
				if (Int32.TryParse(ex.ErrorCode, out int errorCode))
				{
					return StatusCode(errorCode, ex.Message);
				}
				else
				{
					return StatusCode(403, ex.Message);
				}
			}
			catch (HttpOperationException ex)
			{
				logger.LogError(ex, ex.Message);
				JObject error = ErrorHelper.ExtractPowerBiErrorInfo(ex);
				return StatusCode((int)ex.Response.StatusCode, Convert.ToString(error, cultureInfo));
			}
			catch (Exception ex)
			{
				logger.LogError(ex, ex.Message);
				return StatusCode((int)HttpStatusCode.InternalServerError);
			}
		}
Beispiel #5
0
        public IActionResult Login([FromBody] Login model)
        {
            var jwtHelper = new JwtAuthHelper(_userService, _jwtOptions);
            var result    = jwtHelper.GetAuthTokenResult(model);

            var json = JsonConvert.SerializeObject(result, _serializerSettings);

            if (result.Success)
            {
                return(new OkObjectResult(json));
            }
            else
            {
                return(new OkObjectResult(JsonConvert.SerializeObject(result, _serializerSettings)));
            }
        }
		public IActionResult GetEmbedParams()
		{
			// Get username and role of user 
			var userInfo = JwtAuthHelper.GetUsernameAndRole(User.Identity as ClaimsIdentity);

			var embedParamsCacheKey = $"{userInfo.username}:{userInfo.role}";

			// Check cache for embed params
			if (cache.TryGetValue(embedParamsCacheKey, out EmbedParams cachedEmbedParams))
			{
				// Parse token
				var embedToken = cachedEmbedParams.EmbedToken.Token;

				// Parse token expiration string
				var tokenExpiry = cachedEmbedParams.EmbedToken.Expiration;

				// Return token from cache if it is still valid
				if (
					!string.IsNullOrWhiteSpace(embedToken) &&
					tokenExpiry.Subtract(DateTime.UtcNow) > TimeSpan.FromMinutes(Constant.RenewBeforeMinutes)
				)
				{
					return Ok(JsonSerializer.Serialize(cachedEmbedParams));
				}
			}

			// Not found in cache or token is close to expiry, generate new embed params
			try
			{
				// Generate Embed token
				var embedParams = embedService.GenerateEmbedParams(userInfo.username, userInfo.role);

				// Create cache options
				var cacheOptions = new MemoryCacheEntryOptions()
					// Keep in cache for this time, reset time if accessed
					.SetSlidingExpiration(TimeSpan.FromDays(Constant.ExpireInDays));

				// Cache the certificate
				cache.Set(embedParamsCacheKey, embedParams, cacheOptions);

				return Ok(JsonSerializer.Serialize(embedParams));
			}
			catch (MsalServiceException ex)
			{
				logger.LogError(ex, ex.Message);
				return StatusCode(ex.StatusCode, ex.Message);
			}
			catch (MsalClientException ex)
			{
				logger.LogError(ex, ex.Message);
				if (Int32.TryParse(ex.ErrorCode, out int errorCode))
				{
					return StatusCode(errorCode, ex.Message);
				}
				else
				{
					return StatusCode(403, ex.Message);
				}
			}
			catch (HttpOperationException ex)
			{
				logger.LogError(ex, ex.Message);
				JObject error = ErrorHelper.ExtractPowerBiErrorInfo(ex);
				return StatusCode((int)ex.Response.StatusCode, Convert.ToString(error, cultureInfo));
			}
			catch (Exception ex)
			{
				logger.LogError(ex, ex.Message);
				return StatusCode((int)HttpStatusCode.InternalServerError);
			}
		}
Beispiel #7
0
 protected override bool SkipAuthorization(HttpActionContext actionContext)
 {
     return(!JwtAuthHelper.RequestContainJwtHeader(actionContext) || base.SkipAuthorization(actionContext));
 }
 protected override bool SkipAuthorization(HttpActionContext actionContext)
 {
     return(JwtAuthHelper.IsAuthenticatedJwtRequest(actionContext) || base.SkipAuthorization(actionContext));
 }