public void OnAuthorization(AuthorizationFilterContext context) { AllowAnonymousAttribute allowAnonymous = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo.GetCustomAttribute(typeof(AllowAnonymousAttribute), false) as AllowAnonymousAttribute; if (allowAnonymous == null) { const string prefix = "Bearer "; bool result = context.HttpContext.Request.Headers.TryGetValue("Authorization", out StringValues authorization); ResponseResult responseResult = CommonFactory.CreateResponseResult; //如果不包含授权信息 if (!result) { context.Result = new JsonResult(responseResult.Failed("未授权的访问")); return; } string info = authorization.ToString().Trim(); //空字符 不包含Bearer if (string.IsNullOrWhiteSpace(info) || !info.Contains(prefix)) { context.Result = new JsonResult(responseResult.Failed("未授权的访问")); return; } //token错误 if (!_authService.ValidateToken(info.Substring(prefix.Length))) { context.Result = new JsonResult(responseResult.Failed("未授权的访问")); return; } } }
private static IList <object> TranslateMetadata(ImmutableArray <object> metadata) { if (!metadata.IsDefaultOrEmpty) { var translatedMetadata = new List <object>(metadata.Length); foreach (var metadataEntry in metadata) { object translatedEntry = metadataEntry; if (metadataEntry is RpcAuthorizeAttribute rpcAuthorize) { translatedEntry = new AuthorizeAttribute { AuthenticationSchemes = rpcAuthorize.AuthenticationSchemes, Policy = rpcAuthorize.Policy, Roles = rpcAuthorize.Roles }; } else if (metadataEntry is RpcAllowAnonymousAttribute rpcAllowAnonymous) { translatedEntry = new AllowAnonymousAttribute(); } translatedMetadata.Add(translatedEntry); } return(translatedMetadata); } return(Array.Empty <object>()); }
public void AuthUserAsync_should_have_allow_anonymous_attribute() { // Assert Type controllerType = typeof(AuthController); MethodBase methodBase = controllerType.GetMethod(nameof(_authController.AuthUserAsync)); AllowAnonymousAttribute anonymousAttribute = methodBase.GetCustomAttribute <AllowAnonymousAttribute>(); Assert.IsTrue(anonymousAttribute != null); }
public When_Data_Import_Controller_Index_Action_Allow_Anonymous_Attribute() { const BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; var methodInfos = typeof(DataImportController) .GetMember(nameof(DataImportController.Index), MemberTypes.Method, flags) .Cast <MethodInfo>().ToList(); _allowAnonymousAttributeGet = methodInfos[0].GetCustomAttribute <AllowAnonymousAttribute>(); _allowAnonymousAttributePost = methodInfos[1].GetCustomAttribute <AllowAnonymousAttribute>(); }
public void Index_Allows_AnonymousAccess() { // Arrange MethodInfo methodInfo = typeof(HomeController).GetMethod("Index"); object[] actualAttrs = methodInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), inherit: true); // Act AllowAnonymousAttribute actualAttr = actualAttrs.Single() as AllowAnonymousAttribute; // Assert Assert.NotNull(actualAttr); }
/// <summary> /// Sets the value of <see cref="RequiresAuthorization"/> and <see cref="AuthorizeAttribute"/> /// </summary> protected void SetAuthorizationInfo() { AuthorizeAttribute authAttribute = Method.GetCustomAttribute <AuthorizeAttribute>() ?? Method.DeclaringType.GetCustomAttribute <AuthorizeAttribute>(); AllowAnonymousAttribute anonymousAttribute = Method.GetCustomAttribute <AllowAnonymousAttribute>(); bool requireAuth = authAttribute != null; if (anonymousAttribute != null) { requireAuth = false; } RequiresAuthorization = requireAuth; AuthorizeAttribute = requireAuth ? authAttribute : null; }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { //如果用户方法的Action带有AllowAnonymousAttribute,则不进行授权验证 ControllerActionDescriptor descriptor = context.ActionDescriptor as ControllerActionDescriptor; AllowAnonymousAttribute allowAnonymousAttribute = descriptor.MethodInfo.GetCustomAttribute <AllowAnonymousAttribute>(false); if (allowAnonymousAttribute != null) { await next(); return; } else { string token = context.HttpContext.Request.Headers["Authorization"]; if (string.IsNullOrWhiteSpace(token)) { //throw new ValidException("无效的Token!"); token = context.HttpContext.Request.Headers["Token"]; } //if (!string.IsNullOrWhiteSpace(token)) //{ // var tokenHash = this.encryptionService.CreateHash(token, "SHA1"); // var userToken = await RedisHelper.GetAsync($"token_{tokenHash}"); // if (token == userToken) // { // await RedisHelper.SetAsync($"token_{tokenHash}", token, 60 * 60 * 24); // } // else // { // throw new ValidException("Token验证失败!"); // } //} else { throw new ValidException("无效的Token!"); } await next(); } }
public static IEndpointConventionBuilder AddKubernetesProbes( this IEndpointRouteBuilder endpoints, int probePort) { if (endpoints is null) { throw new ArgumentNullException(nameof(endpoints)); } string host = $"*:{(probePort > 0 ? $"{probePort}" : "*")}"; var allowAnonymous = new AllowAnonymousAttribute(); endpoints .MapHealthChecks("healthz/ready") .RequireHost(host) .WithMetadata(allowAnonymous); return(endpoints .MapHealthChecks("healthz/live") .RequireHost(host) .WithMetadata(allowAnonymous)); }
public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { AllowAnonymousAttribute allowAnonymousAttribute = actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().FirstOrDefault(); if (allowAnonymousAttribute != null) { return(Task.FromResult <object>(null)); } if (actionContext.Request.Headers.Contains(AUTH_TOKEN)) { var authToken = actionContext.Request.Headers.GetValues(AUTH_TOKEN).First(); var user = DbUtility.GetUserByToken(authToken); if (user != null) { var userModel = new UserModel() { Id = user.Id, Username = user.Username, Token = authToken }; var principal = new UserPrincipal(userModel); SetPrincipal(principal); return(Task.FromResult <object>(null)); } else { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); return(Task.FromResult <object>(null)); } } else { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); return(Task.FromResult <object>(null)); } }