public static string ActionAbsoluteUri(this UrlHelper Url, string actionName, string controllerName, string protocol, object routeValues = null) { if ((protocol == "https") && (!ConfiguracaoAppUtil.GetAsBool(enumConfiguracaoGeral.httpsHabilitado))) { protocol = "http"; } return(Url.Action(actionName, controllerName, routeValues, protocol)); }
public virtual void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } // Redireciona se urls que estiverem configurado var urlDominioReplace = ConfiguracaoAppUtil.GetAsDictionary(enumConfiguracaoGeral.urlDominioReplace); string scheme = "https"; string port = ""; if (!ConfiguracaoAppUtil.GetAsBool(enumConfiguracaoGeral.httpsHabilitado)) { scheme = "http"; if (filterContext.HttpContext.Request.Url.Port != 80) { port = ":" + filterContext.HttpContext.Request.Url.Port; } } foreach (var url in urlDominioReplace) { if ((filterContext.HttpContext.Request.Url.Host.Contains(url.Key)) && (!filterContext.HttpContext.Request.Url.Host.Contains(url.Value))) { string urlWWW = scheme + "://" + filterContext.HttpContext.Request.Url.Host.Replace(url.Key, url.Value) + port + filterContext.HttpContext.Request.RawUrl; filterContext.Result = new RedirectResult(urlWWW); return; } } // Only redirect GET requests e se o HTTPS esta habilitado if ((!filterContext.HttpContext.Request.IsSecureConnection) && (string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) && (ConfiguracaoAppUtil.GetAsBool(enumConfiguracaoGeral.httpsHabilitado))) { string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl; filterContext.Result = new RedirectResult(url); } }
protected override bool IsAuthorized(HttpActionContext actionContext) { try { if ((ConfiguracaoAppUtil.GetAsBool(enumConfiguracaoGeral.httpsHabilitado)) && (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { ReasonPhrase = "HTTPS Required" }; } if (base.IsAuthorized(actionContext)) { var controller = (MasterApiController)actionContext.ControllerContext.Controller; IPrincipal principal = actionContext.ControllerContext.RequestContext.Principal; if ((principal.Identity != null) && (principal.Identity.IsAuthenticated)) { using (var usuarioBO = new APIUsuarioBO()) { if (controller.APIUsuarioToken == null) { controller.APIUsuarioToken = usuarioBO.ConsultarToken(actionContext.ControllerContext.Request.Headers.Authorization.Parameter); if (controller.APIUsuarioToken == null) { controller.APIUsuarioToken = usuarioBO.ConsultarToken(actionContext.ControllerContext.Request.Headers.GetValues("ClientInfo").FirstOrDefault(), principal.Identity.Name); if ((controller.APIUsuarioToken == null) || (controller.APIUsuarioToken.Token != null)) { return(false); } controller.APIUsuarioToken.Token = actionContext.ControllerContext.Request.Headers.Authorization.Parameter; controller.AtualizarToken = true; } } if ((_apiRoles != null) && (_apiRoles.Length > 0) && (controller.APIUsuarioToken.Roles == null)) { controller.APIUsuarioToken.Roles = usuarioBO.ConsultarPermissoes(controller.APIUsuarioToken.APIUsuario.ID); } } controller.SessionModel = JsonConvert.DeserializeObject <SessionModel>(controller.APIUsuarioToken.DadosSession); if ((!controller.APIUsuarioToken.APIUsuario.Ativo) || (!controller.APIUsuarioToken.Ativo) || (controller.APIUsuarioToken.DadosIndentificacao != actionContext.ControllerContext.Request.Headers.GetValues("ClientInfo").FirstOrDefault())) { return(false); } // TODO: Tem algum problema, deve ser checado switch (controller.APIUsuarioToken.APIUsuario.TipoAcessoAsEnum) { case enumAPITipoAcesso.webClient: if (string.IsNullOrEmpty(controller.APIUsuarioToken.APIUsuario.DominiosOrigem)) { return(false); } if (controller.APIUsuarioToken.APIUsuario.DominiosOrigem != "*") { var dominiosWC = controller.APIUsuarioToken.APIUsuario.DominiosOrigem.Split(',').Select(t => t.Trim()); if (!dominiosWC.Contains(HttpContext.Current.Request.GetClientReferer())) { return(false); } } break; case enumAPITipoAcesso.webServer: if (string.IsNullOrEmpty(controller.APIUsuarioToken.APIUsuario.IPOrigem)) { return(false); } if (controller.APIUsuarioToken.APIUsuario.IPOrigem != "*") { var ips = controller.APIUsuarioToken.APIUsuario.IPOrigem.Split(',').Select(t => t.Trim()); if (!ips.Any(t => HttpContext.Current.Request.GetClientIPAddress().Contains(t))) { if (HttpContext.Current.Request.UrlReferrer == null) { LogUtil.Error("Os IPs " + string.Join(", ", HttpContext.Current.Request.GetClientIPAddress().ToArray()) + " não são permitidos para acesso a API com o usuário " + controller.APIUsuarioToken.APIUsuario.Login); return(false); } else { if (string.IsNullOrEmpty(controller.APIUsuarioToken.APIUsuario.DominiosOrigem)) { LogUtil.Error("Os IPs " + string.Join(", ", HttpContext.Current.Request.GetClientIPAddress().ToArray()) + " não são permitidos para acesso a API com o usuário " + controller.APIUsuarioToken.APIUsuario.Login); return(false); } if (controller.APIUsuarioToken.APIUsuario.DominiosOrigem != "*") { var dominiosWS = controller.APIUsuarioToken.APIUsuario.DominiosOrigem.Split(',').Select(t => t.Trim()); if (!dominiosWS.Contains(HttpContext.Current.Request.GetClientReferer())) { LogUtil.Error("O Domínio " + HttpContext.Current.Request.GetClientReferer() + " não permitido para o acesso a API com o usuário " + controller.APIUsuarioToken.APIUsuario.Login); return(false); } } } } } break; } if ((_apiRoles != null) && (_apiRoles.Length > 0)) { if ((!controller.APIUsuarioToken.Roles.Select(t => t.ToLower()).Contains(enumAPIRele.master.Description().ToLower())) && (!_apiRoles.Any(t => controller.APIUsuarioToken.Roles.Any(y => t.Description().ToLower().Split(',').Contains(y.ToLower()))))) { if (controller.ControllerContext.RouteData.Values.ContainsKey("action")) { LogUtil.Error("O Usuario da API " + controller.APIUsuarioToken.APIUsuario.Login + " não tem permissão para o acesso ao metodo " + controller.ControllerContext.RouteData.Values["action"] + " "); } else { LogUtil.Error("O Usuario da API " + controller.APIUsuarioToken.APIUsuario.Login + " não tem permissão para o acesso."); } return(false); } } } return(true); } return(false); } catch (Exception ex) { LogUtil.Error(ex); return(false); } }
/// <summary> /// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 /// </summary> /// <param name="app"></param> public void ConfigureAuth(IAppBuilder app) { // Habilita o cross domain app.Use(async(context, next) => { IOwinRequest req = context.Request; IOwinResponse res = context.Response; if (req.Path.StartsWithSegments(new PathString("/token"))) { res.Headers.Set("Access-Control-Allow-Origin", "*"); res.Headers.Set("Access-Control-Allow-Methods", "*"); if (req.Method == "OPTIONS") { res.Headers.Set("Access-Control-Allow-Headers", req.Headers["Access-Control-Request-Headers"]); res.StatusCode = 200; return; } } await next(); }); // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Configure the application for OAuth based flow PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/token"), Provider = new ApplicationOAuthProvider(PublicClientId), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = (!ConfiguracaoAppUtil.GetAsBool(enumConfiguracaoGeral.httpsHabilitado)), RefreshTokenProvider = new SimpleRefreshTokenProvider() }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); }