Example #1
0
        public async Task <IActionResult> OnGet()
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToPage("/Index"));
            }

            AuthSchemes = await _authSchemeProvider.GetRequestHandlerSchemesAsync();

            return(Page());
        }
        public async Task Invoke(HttpContext context, IAuthenticationSchemeProvider Schemes)
        {
            context.Features.Set <IAuthenticationFeature>(new AuthenticationFeature
            {
                OriginalPath     = context.Request.Path,
                OriginalPathBase = context.Request.PathBase
            });

            // Give any IAuthenticationRequestHandler schemes a chance to handle the request
            var handlers = context.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync().ConfigureAwait(false))
            {
                if (await handlers.GetHandlerAsync(context, scheme.Name).ConfigureAwait(false) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync().ConfigureAwait(false))
                {
                    return;
                }
            }

            var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await context.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    context.User = result.Principal;
                }
            }

            await _next(context);
        }
Example #3
0
        /// <summary>
        /// Configure authentication configuration for external login
        /// </summary>
        /// <param name="provider">name of social provider</param>
        /// <param name="redirectUrl">where should social provider redirect</param>
        /// <returns>Instance of ServiceResult</returns>
        public virtual async Task <ServiceResult <IAuthProperties> > GetAuthProperties(string provider, string redirectUrl)
        {
            if (string.IsNullOrEmpty(provider))
            {
                throw new ArgumentNullException(nameof(provider));
            }

            if (string.IsNullOrEmpty(redirectUrl))
            {
                throw new ArgumentNullException(nameof(redirectUrl));
            }

            var result = new RequestResult <IAuthProperties>();

            var allAuthScheme = (await schemeProvider.GetRequestHandlerSchemesAsync())
                                .Select(item => item.Name)
                                .ToList();

            if (!allAuthScheme.Contains(provider))
            {
                return(result.BadRequest("Requested provider is not supported"));
            }

            var items = new Dictionary <string, string>()
            {
                { "LoginProvider", provider }
            };

            return(result.GoodRequest(new ExternalAuthProperties(redirectUrl, items)));
        }
        public async Task <IActionResult> Index()
        {
            foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                var handler1 = await _handlers.GetHandlerAsync(HttpContext, scheme.Name) as IAuthenticationRequestHandler;

                if (handler1 != null && await handler1.HandleRequestAsync())
                {
                    return(View());
                }
            }
            var target = ResolveTarget(_options.CurrentValue.ForwardAuthenticate);

            var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await HttpContext.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    HttpContext.User = result.Principal;
                }
            }

            string cookieValue = HttpContext.Request.Cookies[".Aspnetcore.Identity.Application"];

            var provider = _options.CurrentValue.DataProtectionProvider;
            //Get a data protector to use with either approach
            IDataProtector dataProtector = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2");

            //Get the decrypted cookie as plain text
            UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

            byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookieValue);
            byte[] plainBytes     = dataProtector.Unprotect(protectedBytes);
            string plainText      = specialUtf8Encoding.GetString(plainBytes);


            //Get the decrypted cookie as a Authentication Ticket
            TicketDataFormat     ticketDataFormat = new TicketDataFormat(dataProtector);
            AuthenticationTicket ticket           = ticketDataFormat.Unprotect(cookieValue);
            //CookieAuthenticationHandler a;
            //a.AuthenticateAsync()
            //var result = (await handler.AuthenticateAsync()) ?? AuthenticateResult.NoResult();
            //if (!result.Succeeded)
            //{
            //    return View();
            //}
            //var options = _options.CurrentValue;
            //var cookie = options.CookieManager.GetRequestCookie(HttpContext, options.Cookie.Name!);
            var b = await ReadCookieTicket();

            //var a = options.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding());
            return(View());
        }
Example #5
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var res = await _schemeProvider.GetRequestHandlerSchemesAsync();

            return
                (View(new ExternalLoginViewModel()
            {
                ReturnUrl = Request.Query["returnUrl"],
                Providers = res.Select(p => p.Name).ToArray()
            }));
        }
Example #6
0
        public async Task InvokeAsync(HttpContext context)
        {
            var handlers = context.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                var handler = await handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;

                if (handler != null && await handler.HandleRequestAsync())
                {
                    return;
                }
            }
            await _next(context);
        }
        /// <summary>
        /// Intercepts the websocket connection, extracts the JWT from the onOpenMessage and authenticate the user with it. The connection will be rejected if the no JWT is given.
        /// </summary>
        public async Task <ConnectionStatus> OnOpenAsync(
            HttpContext context,
            IReadOnlyDictionary <string, object> properties,
            CancellationToken cancellationToken
            )
        {
            if (properties.TryGetValue(WEBOCKET_PAYLOAD_AUTH_KEY, out object token) &&
                token is string stringToken)
            {
                // Das Token dem HTTP Context hinzufügen, sodass dies später für über den TokenRetriever verwendet werden aknn
                context.Items[HTTP_CONTEXT_WEBSOCKET_AUTH_KEY] = stringToken;

                context.Features.Set <IAuthenticationFeature>(new AuthenticationFeature
                {
                    OriginalPath     = context.Request.Path,
                    OriginalPathBase = context.Request.PathBase
                });

                // Give any IAuthenticationRequestHandler schemes a chance to handle the request
                var handlers = context.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
                {
                    var handler = handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;
                    if (handler != null && await handler.HandleRequestAsync())
                    {
                        return(ConnectionStatus.Reject());
                    }
                }

                var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    // Benutzer mithilfe des Tokens authentifizieren
                    var result = await context.AuthenticateAsync(defaultAuthenticate.Name);

                    // war die Authentifizierung erfolgreich wird die Anfrage angenommen und der Websockt kann Nachrichten erhalten
                    if (result?.Principal != null)
                    {
                        context.User = result.Principal;
                        return(ConnectionStatus.Accept());
                    }
                }
            }
            // Sollte kein Token vorhanden sein, wird die Anfrage abgelehnt
            return(ConnectionStatus.Reject());
        }
        /// <summary>
        /// handle requirement
        /// </summary>
        /// <param name="context">authorization handler context</param>
        /// <param name="jwtAuthorizationRequirement">jwt authorization requirement</param>
        /// <returns></returns>
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, JwtAuthorizationRequirement jwtAuthorizationRequirement)
        {
            //convert AuthorizationHandlerContext to HttpContext
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;

            var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                var handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;

                if (handler != null && await handler.HandleRequestAsync())
                {
                    context.Fail();
                    return;
                }
            }
            var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    httpContext.User = result.Principal;
                    var invockResult = jwtAuthorizationRequirement.ValidatePermission(httpContext);
                    if (invockResult)
                    {
                        context.Succeed(jwtAuthorizationRequirement);
                    }
                    else
                    {
                        context.Fail();
                    }
                }
                else
                {
                    context.Fail();
                }
            }
            else
            {
                context.Fail();
            }
        }
        /// <summary>
        /// Some authentication schemes need to be able to handle certian webrequests on their own.
        /// CookieAuthentication uses this to handle signout requests for example.
        /// </summary>
        private async Task <bool> TryHandleAuthenticationSchemeRequest(HttpContext context)
        {
            var handlers = context.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await schemes.GetRequestHandlerSchemesAsync())
            {
                if (await handlers.GetHandlerAsync(context, scheme.Name) is IAuthenticationRequestHandler handler)
                {
                    if (await handler.HandleRequestAsync())
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        public async Task <ConnectionStatus> OnOpenAsync(
            HttpContext context,
            IReadOnlyDictionary <string, object> properties,
            CancellationToken cancellationToken)
        {
            if (properties.TryGetValue(WEBOCKET_PAYLOAD_AUTH_KEY, out object token) &&
                token is string stringToken)
            {
                context.Items[HTTP_CONTEXT_WEBSOCKET_AUTH_KEY] = stringToken;
                context.Features.Set <IAuthenticationFeature>(new AuthenticationFeature
                {
                    OriginalPath     = context.Request.Path,
                    OriginalPathBase = context.Request.PathBase
                });
                // Give any IAuthenticationRequestHandler schemes a chance to handle the request
                var handlers = context.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
                {
                    var handler = handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;
                    if (handler != null && await handler.HandleRequestAsync())
                    {
                        return(ConnectionStatus.Reject());
                    }
                }
                var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await context.AuthenticateAsync(defaultAuthenticate.Name);

                    if (result?.Principal != null)
                    {
                        var webSocketContext = context.RequestServices.GetService <WebSocketContext>();
                        webSocketContext.User = result.Principal;
                        context.User          = result.Principal;
                        return(ConnectionStatus.Accept());
                    }
                }
            }
            return(ConnectionStatus.Reject());
        }
Example #11
0
        public async Task <IActionResult> Login(string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = "~/";
            }

            IEnumerable <AuthenticationScheme> registeredSchemes =
                await _authSchemeProvider.GetRequestHandlerSchemesAsync();

            IEnumerable <AuthenticationScheme> remoteSchemes =
                registeredSchemes
                .Where(scheme => typeof(IAuthenticationRequestHandler).IsAssignableFrom(scheme.HandlerType));

            LoginViewModel loginVm = new LoginViewModel();

            loginVm.AvailableExternalProviders = remoteSchemes;
            loginVm.ReturnUrl = returnUrl;

            return(View(loginVm));
        }
        public async Task Invoke(HttpContext context)
        {
            context.Features.Set <IAuthenticationFeature>(new AuthenticationFeature
            {
                OriginalPath     = context.Request.Path,
                OriginalPathBase = context.Request.PathBase
            });

            IAuthenticationHandlerProvider handlers = context.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (AuthenticationScheme scheme in await _authenticationSchemeProvider.GetRequestHandlerSchemesAsync())
            {
                if (await handlers.GetHandlerAsync(context, scheme.Name) is IAuthenticationRequestHandler handler &&
                    await handler.HandleRequestAsync())
                {
                    return;
                }
            }

            AuthenticationScheme defaultAuthenticate = await _authenticationSchemeProvider.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                AuthenticateResult result = await context.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    context.User = result.Principal;
                }
            }

            try
            {
                await _next(context);
            }
            finally
            {
                //
            }
        }
Example #13
0
        public async Task <IActionResult> OnGet()
        {
            AuthSchemes = await _authSchemeProvider.GetRequestHandlerSchemesAsync();

            return(Page());
        }
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, JwtAuthorizationRequirement jwtAuthorizationRequirement)
        {
            //convert AuthorizationHandlerContext to HttpContext
            var httpContext = _httpContextAccessor.HttpContext;

            var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                var handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;

                if (handler != null && await handler.HandleRequestAsync())
                {
                    httpContext.Response.Headers.Add("error", "request cancel");
                    context.Fail();
                    return;
                }
            }
            var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    httpContext.User = result.Principal;
                    var ipClaim = httpContext.User.Claims.SingleOrDefault(c => c.Type == "ip");
                    if (ipClaim == null)
                    {
                        var invockResult = _permissionAuthoriser.Authorise(httpContext);
                        if (invockResult)
                        {
                            context.Succeed(jwtAuthorizationRequirement);
                        }
                        else
                        {
                            context.Fail();
                        }
                    }
                    else
                    {
                        // 由于Jwt无状态方式,所以无法控制token无效关闭锁定等情况
                        // 可以通过一些特殊情况来处理
                        // token 黑名单
                        // token ip 变更
                        // httpContext.Features.Get<Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature>()?.RemoteIpAddress?.ToString();
                        var ip = IPAddressHelper.GetRequestIP(httpContext);
                        if (ipClaim.Value == ip)
                        {
                            httpContext.User = result.Principal;
                            var invockResult = _permissionAuthoriser.Authorise(httpContext);
                            if (invockResult)
                            {
                                context.Succeed(jwtAuthorizationRequirement);
                            }
                            else
                            {
                                context.Fail();
                            }
                        }
                        else
                        {
                            httpContext.Response.Headers.Add("error", "token ip and request ip is unlikeness");
                            context.Fail();
                        }
                    }
                }
                else
                {
                    httpContext.Response.Headers.Add("error", "authenticate fail");
                    context.Fail();
                }
            }
            else
            {
                httpContext.Response.Headers.Add("error", "can't find authenticate");
                context.Fail();
            }
        }
 public async Task OnGet()
 {
     AuthSchemes = await _schemeProvider.GetRequestHandlerSchemesAsync();
 }
        public async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null)
            {
                // this allows an acr_values of "Windows" and then the first actual windows-based provider to be used
                if (AccountOptions.WindowsAuthenticationEnabled && context.IdP == AccountOptions.WindowsAuthenticationProviderName)
                {
                    context.IdP = AccountOptions.WindowsAuthenticationSchemes.First();
                }

                // this is meant to short circuit the UI and only trigger the one external IdP
                return(new LoginViewModel
                {
                    EnableLocalLogin = false,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    ExternalProviders = new ExternalProvider[] { new ExternalProvider {
                                                                     AuthenticationScheme = context.IdP
                                                                 } }
                });
            }

            //var schemes = _httpContextAccessor.HttpContext.Authentication.GetAuthenticationSchemes();
            var schemes = await _schemeProvider.GetRequestHandlerSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null && !AccountOptions.WindowsAuthenticationSchemes.Contains(x.Name))
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName,
                AuthenticationScheme = x.Name
            }).ToList();

            if (AccountOptions.WindowsAuthenticationEnabled)
            {
                // this is needed to handle windows auth schemes
                var windowsSchemes = schemes.Where(s => AccountOptions.WindowsAuthenticationSchemes.Contains(s.Name));
                if (windowsSchemes.Any())
                {
                    providers.Add(new ExternalProvider
                    {
                        AuthenticationScheme = AccountOptions.WindowsAuthenticationSchemes.First(),
                        DisplayName          = AccountOptions.WindowsAuthenticationDisplayName
                    });
                }
            }

            var allowLocal = true;

            if (context?.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            return(new LoginViewModel
            {
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            });
        }
Example #17
0
        /// <summary>
        /// handle requirement
        /// </summary>
        /// <param name="context">authorization handler context</param>
        /// <param name="jwtAuthorizationRequirement">jwt authorization requirement</param>
        /// <returns></returns>
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, JwtAuthorizationRequirement jwtAuthorizationRequirement)
        {
            //convert AuthorizationHandlerContext to HttpContext
            var httpContext = context.Resource.GetType().GetProperty("HttpContext").GetValue(context.Resource) as HttpContext;

            var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                {
                    httpContext.Response.Headers.Add("error", "request cancel");
                    context.Fail();
                    return;
                }
            }
            var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    httpContext.User = result.Principal;
                    var ipClaim = httpContext.User.Claims.SingleOrDefault(c => c.Type == "ip");
                    if (ipClaim == null)
                    {
                        var invockResult = jwtAuthorizationRequirement.ValidatePermission(httpContext);
                        if (invockResult)
                        {
                            context.Succeed(jwtAuthorizationRequirement);
                        }
                        else
                        {
                            context.Fail();
                        }
                    }
                    else
                    {
                        var ip = httpContext.Features.Get <Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature>()?.RemoteIpAddress?.ToString();
                        if (ipClaim.Value == ip)
                        {
                            httpContext.User = result.Principal;
                            var invockResult = jwtAuthorizationRequirement.ValidatePermission(httpContext);
                            if (invockResult)
                            {
                                context.Succeed(jwtAuthorizationRequirement);
                            }
                            else
                            {
                                context.Fail();
                            }
                        }
                        else
                        {
                            httpContext.Response.Headers.Add("error", "token ip and request ip is unlikeness");
                            context.Fail();
                        }
                    }
                }
                else
                {
                    httpContext.Response.Headers.Add("error", "authenticate fail");
                    context.Fail();
                }
            }
            else
            {
                httpContext.Response.Headers.Add("error", "can't find authenticate");
                context.Fail();
            }
        }
        public async Task <List <string> > Providers()
        {
            var result = await _authenticationSchemeProvider.GetRequestHandlerSchemesAsync();

            return(result.Select(s => s.DisplayName).ToList());
        }
Example #19
0
        /// <summary>
        /// 重载异步处理程序
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AdmPolicyRequirement requirement)
        {
            var httpContext = _accessor.HttpContext;
            var routContext = (context.Resource as RouteEndpoint);
            var descriptor  = routContext.Metadata.OfType <ControllerActionDescriptor>().FirstOrDefault();
            var currentURI  = string.Empty;
            //如果有自定义资源标识,取自定义的标识。没有自定义的,取默认ControllerName:ActionName
            var admAuthorizeFilterAttr = GetAdmAuthorizeFilterAttributeOrNull(descriptor.MethodInfo);

            if (admAuthorizeFilterAttr == null || string.IsNullOrEmpty(admAuthorizeFilterAttr.FilterName))
            {
                if (descriptor != null)
                {
                    currentURI = $"{descriptor.ControllerName}:{descriptor.ActionName}";
                }
            }
            else
            {
                currentURI = admAuthorizeFilterAttr.FilterName;
            }
            //判断请求是否停止
            var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler &&
                    await handler.HandleRequestAsync())
                {
                    context.Fail();
                    return;
                }
            }

            var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                //result?.Principal不为空即登录成功
                if (result?.Principal != null)
                {
                    httpContext.User = result.Principal;
                    // 获取当前用户的角色信息
                    var currentUserRoles = (from item in httpContext.User.Claims
                                            where item.Type == requirement.ClaimType
                                            select Convert.ToInt32(item.Value)).ToList();
                    // 获取权限列表(role-uri)
                    var roleUris         = _roleService.GetRoleUriMaps();
                    var permisssionRoles = roleUris.Where(ru => currentUserRoles.Contains(ru.RoleId));
                    if (!permisssionRoles.Any(pr => currentURI.ToLower() == pr.Uri.ToLower()))
                    {
                        context.Fail();
                        return;
                    }

                    //判断过期时间
                    //这里仅仅是最坏验证原则,你可以不要这个if else的判断,因为我们使用的官方验证,Token过期后上边的result?.Principal 就为 null 了,进不到这里了,因此这里其实可以不用验证过期时间,只是做最后严谨判断
                    var expirationTime = httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value;
                    if (!string.IsNullOrEmpty(expirationTime) && DateTime.Parse(expirationTime) >= DateTime.Now)
                    {
                        context.Succeed(requirement);
                        return;
                    }
                    else
                    {
                        context.Fail();
                        return;
                    }
                }
                else
                {
                    context.Fail();
                    return;
                }
            }

            context.Succeed(requirement);
        }
Example #20
0
        //protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IAuthorizationRequirement requirement)
        //{
        //    throw new NotImplementedException();
        //}

        // 重写异步处理程序
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            var httpContext = _accessor.HttpContext;

            // 获取系统中所有的角色和菜单的关系集合
            if (!requirement.Permissions.Any())
            {
                var data = await _roleModulePermissionServices.GetAllByUserIdAsync(1);

                var list = new List <PermissionItem>();
                // ids4和jwt切换
                // ids4
                if (true)
                {
                    list = (from item in data
                            where !string.IsNullOrEmpty(item.PermissionName)
                            orderby item.Id
                            select new PermissionItem
                    {
                        Url = item.PermissionPath,
                        Role = item.Id.ToString(),
                    }).ToList();
                }
                // jwt
                //else
                //{
                //    list = (from item in data
                //            where item.IsDeleted == false
                //            orderby item.Id
                //            select new PermissionItem
                //            {
                //                Url = item.Module?.LinkUrl,
                //                Role = item.Role?.Name.ObjToString(),
                //            }).ToList();
                //}
                requirement.Permissions = list;
            }

            if (httpContext != null)
            {
                var questUrl = httpContext.Request.Path.Value.ToLower();

                // 整体结构类似认证中间件UseAuthentication的逻辑,具体查看开源地址
                // https://github.com/dotnet/aspnetcore/blob/master/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs
                httpContext.Features.Set <IAuthenticationFeature>(new AuthenticationFeature
                {
                    OriginalPath     = httpContext.Request.Path,
                    OriginalPathBase = httpContext.Request.PathBase
                });

                // Give any IAuthenticationRequestHandler schemes a chance to handle the request
                // 主要作用是: 判断当前是否需要进行远程验证,如果是就进行远程验证
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        context.Fail();
                        return;
                    }
                }


                //判断请求是否拥有凭据,即有没有登录
                var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    //result?.Principal不为空即登录成功
                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;

                        // 获取当前用户的角色信息
                        var currentUserRoles = new List <string>();
                        // ids4和jwt切换
                        // ids4
                        if (true)
                        {
                            currentUserRoles = (from item in httpContext.User.Claims
                                                where item.Type == "role"
                                                select item.Value).ToList();
                        }
                        else
                        {
                            // jwt
                            //currentUserRoles = (from item in httpContext.User.Claims
                            //                    where item.Type == requirement.ClaimType
                            //                    select item.Value).ToList();
                        }

                        var isMatchRole      = false;
                        var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role));
                        foreach (var item in permisssionRoles)
                        {
                            try
                            {
                                if (Regex.Match(questUrl, item.Url.ToLower())?.Value == questUrl)
                                {
                                    isMatchRole = true;
                                    break;
                                }
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }

                        //验证权限
                        if (currentUserRoles.Count <= 0 || !isMatchRole)
                        {
                            context.Fail();
                            return;
                        }

                        var isExp = false;
                        // ids4和jwt切换
                        // ids4
                        if (true)
                        {
                            isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == "exp")?.Value) != null /* && DateHelper.StampToDateTime(httpContext.User.Claims.SingleOrDefault(s => s.Type == "exp")?.Value) >= DateTime.Now*/;
                        }
                        else
                        {
                            // jwt
                            //isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now;
                        }
                        if (isExp)
                        {
                            context.Succeed(requirement);
                        }
                        else
                        {
                            context.Fail();
                            return;
                        }
                        return;
                    }
                }
                //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
                if (!(questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType)))
                {
                    context.Fail();
                    return;
                }
            }

            //context.Succeed(requirement);
        }
Example #21
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, DefaultRequirement requirement)
        {
            AuthorizationFilterContext authorizationFilterContext = context.Resource as AuthorizationFilterContext;
            HttpContext httpContext = authorizationFilterContext.HttpContext;
            IAuthenticationHandlerProvider handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (AuthenticationScheme scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                IAuthenticationRequestHandler handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;

                if (handler != null && await handler.HandleRequestAsync())
                {
                    context.Fail();
                    return;
                }
            }
            AuthenticationScheme defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                AuthenticateResult result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    if (long.Parse(result.Principal.Claims.SingleOrDefault(s => s.Type == "exp").Value) < DateTime.Now.ToIntS())
                    {
                        authorizationFilterContext.Result = new JsonResult(new MessageResult
                        {
                            Msg    = ConifgMessage.TIMEOUT,
                            Status = false
                        })
                        {
                            StatusCode = 401
                        };
                    }
                    else
                    {
                        httpContext.User = result.Principal;
                        if (requirement.Validation != null)
                        {
                            AuthResult validMsg = requirement.Validation(httpContext);
                            if (!validMsg.IsValid)
                            {
                                authorizationFilterContext.Result = new JsonResult(new MessageResult
                                {
                                    Msg    = validMsg.Msg,
                                    Status = false
                                })
                                {
                                    StatusCode = 401
                                };
                            }
                        }
                    }
                }
                else
                {
                    authorizationFilterContext.Result = new JsonResult(new MessageResult
                    {
                        Msg    = ConifgMessage.NOTRIGHT,
                        Status = false
                    })
                    {
                        StatusCode = 401
                    };
                }
            }
            else
            {
                context.Fail();
                return;
            }
            context.Succeed(requirement);
        }
Example #22
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRole requirement)
        {
            var data = _RoleManngeRepository.GetAll(u => u.Id != null && u.IsTrueRold == requirement.Istrue);
            var list = await(from item in data
                             orderby item.Id
                             select new UserPermission
            {
                Policy    = item.RoleName,
                Id        = item.Id,
                IsEnabled = item.IsTrueRold
            }).ToListAsync();

            requirement.UserPermissions = list;
            var filterContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext);
            var httpContext   = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)?.HttpContext;

            if (httpContext == null)
            {
                httpContext = _Accessor.HttpContext;
            }
            if (httpContext != null)
            {
                var questUrl = httpContext.Request.Path.Value.ToLower();
                //判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        context.Fail();
                        return;
                    }
                }
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;
                        var currentUserRoles = (from item in httpContext.User.Claims
                                                where item.Type == "jti" || item.Type == requirement.ClaimType
                                                select item.Value.ToString()).ToList();
                        if (currentUserRoles.Count < 2)
                        {
                            httpContext.Response.Redirect(requirement.DeniedAction);
                            return;
                        }
                        var userPermission = new UserPermission();
                        foreach (var role in currentUserRoles)
                        {
                            if (string.IsNullOrEmpty(userPermission.Policy))
                            {
                                var permission = list.Where(x => ((x.Id.ToString().Equals(role)))).FirstOrDefault();

                                if (permission != null)
                                {
                                    userPermission = permission;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (string.IsNullOrEmpty(userPermission.Policy))
                        {
                            context.Fail();
                            return;
                        }
                        context.Succeed(requirement);
                        return;
                    }
                    else
                    {
                        context.Fail();
                        return;
                    }
                }
                else
                {
                    //是登录的api请求
                    //if (!questUrl.Equals(requirement.LoginPath.ToLower()))
                    //{

                    //    context.Succeed(requirement);
                    //    return;
                    //}
                    context.Fail();
                }
            }
            return;
        }
Example #23
0
        public async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null)
            {
                return new LoginViewModel
                       {
                           EnableLocalLogin  = false,
                           ReturnUrl         = returnUrl,
                           LoginName         = context.LoginHint,
                           ExternalProviders = new[] { new ExternalProvider {
                                                           AuthenticationScheme = context.IdP
                                                       } }
                       }
            }
            ;


            //var schemes = _httpContextAccessor.HttpContext.Authentication.GetAuthenticationSchemes();
            var schemes = await _schemeProvider.GetRequestHandlerSchemesAsync();

            //非Windows登录的provider
            var providers = (from n in schemes
                             where !string.IsNullOrEmpty(n.DisplayName) &&
                             !_options.WindowsAuthenticationSchemes.Contains(n.Name)
                             select new ExternalProvider
            {
                DisplayName = n.DisplayName,
                AuthenticationScheme = n.Name
            }).ToList();


            //如果允许Windows登录。且用户已经用Windows登录过。直接放行,返回原windows provider
            if (_options.WindowsAuthenticationEnabled)
            {
                var windowsSchemes =
                    schemes.Where(s => _options.WindowsAuthenticationSchemes.Contains(s.Name));

                if (windowsSchemes.Any())
                {
                    providers.Add(new ExternalProvider
                    {
                        AuthenticationScheme = _options.WindowsAuthenticationSchemes.First(),
                        DisplayName          = _options.WindowsAuthenticationDisplayName
                    });
                }
            }

            var allowLocal = true;

            if (context?.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;
                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers
                                    .Where(provider => client.IdentityProviderRestrictions.Contains(provider
                                                                                                    .AuthenticationScheme)).ToList();
                    }
                }
            }

            return(new LoginViewModel
            {
                AllowRememberLogin = _options.AllowRememberLogin,
                EnableLocalLogin = allowLocal && _options.AllowLocalLogin,
                ReturnUrl = returnUrl,
                LoginName = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            });
        }
Example #24
0
 public Task <IEnumerable <AuthenticationScheme> > GetRequestHandlerSchemesAsync()
 {
     return(_inner.GetRequestHandlerSchemesAsync());
 }
Example #25
0
        // 重载异步处理程序--这个是自定义的权限拦截器,[Authorize("Permission")] 标记了这个特性的所有接口都走这个里面验证接口权限
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            // 将最新的角色和接口列表更新
            var data = await _IMainServices.GeRoleModule();

            var list = (from item in data
                        select new Permission
            {
                Url = item.SysModule?.LinkUrl,
                Role = item.SysRole?.RoleName,
            }).ToList();

            //var list=new List<Permission>();
            requirement.Permissions = list;

            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;
            //请求Url
            var questUrl = httpContext.Request.Path.Value.ToLower();
            //判断请求是否停止
            var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
            {
                var handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;

                if (handler != null && await handler.HandleRequestAsync())
                {
                    context.Fail();
                    throw new UnauthorizedAccessException("请求已停止!");
                }
            }
            //判断请求是否拥有凭据,即有没有登录
            var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                if (result.Failure != null && result.Failure.Message.Contains("The token is expired."))
                {
                    context.Fail();
                    throw new UnauthorizedAccessException("令牌已过期,请重新获取授权!");
                }
                //result?.Principal不为空即登录成功
                if (result?.Principal != null)
                {
                    httpContext.User = result.Principal;
                    //权限中是否存在请求的url
                    if (requirement.Permissions.GroupBy(g => g.Url).Where(w => w.Key?.ToLower() == questUrl).Count() > 0)
                    {
                        // 获取当前用户的角色信息
                        var currentUserRoles = (from item in httpContext.User.Claims
                                                where item.Type == requirement.ClaimType
                                                select item.Value).ToList();


                        //验证权限
                        if (currentUserRoles.Count <= 0 || requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role) && w.Url.ToLower() == questUrl).Count() <= 0)
                        {
                            context.Fail();
                            throw new UnauthorizedAccessException("没有使用这个接口的权限!");
                            // 可以在这里设置跳转页面,不过还是会访问当前接口地址的
                            //httpContext.Response.Redirect(requirement.DeniedAction);
                        }
                    }
                    else
                    {
                        context.Fail();
                        throw new UnauthorizedAccessException("这个接口不在权限系统中,请联系管理员添加接口权限!");
                    }
                    //判断过期时间
                    if ((httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now)
                    {
                        context.Succeed(requirement);
                        return;
                    }
                    else
                    {
                        context.Fail();
                        throw new UnauthorizedAccessException("令牌已过期,请重新获取授权!");
                    }
                }
                else
                {
                    context.Fail();
                    throw new UnauthorizedAccessException("请先登录!");
                }
            }
            //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
            if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") ||
                                                                                                !httpContext.Request.HasFormContentType))
            {
                context.Fail();
                throw new UnauthorizedAccessException("未经授权的访问!");
            }
            context.Succeed(requirement);
        }