这是一个asp.net core webapi项目,我只需要在那些接口上放置[Authorize]属性就可以保护它们。如果用户未被授权,则API将返回“401未经授权”的消息。
我的问题是,如果没有获得授权,如何本地化“401未经授权”消息。
对于其他数据注释,我可以设置DataAnnotaion属性的ErrorMessage属性,比如[Required(ErrorMessage = "xxx")]。但是,AuthorizeAttribute没有这样的属性。
感谢@Athanasios,我想出了我的解决方案,希望它能帮助某些人。(ErrorMessages仅是一个共享类)。
using System;
using System.Threading.Tasks;
using YourNamespace.Messages;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace YourNamespace.Attributes
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class LocalizedAuthorizeAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
{
public string UnauthorizedErrorMessage { get; set; }
public string ForbiddenErrorMessage { get; set; }
public LocalizedAuthorizeAttribute()
{
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
var localizer = context.HttpContext.RequestServices.GetService<IStringLocalizer<ErrorMessages>>();
var logger = context.HttpContext.RequestServices.GetService<ILogger<LocalizedAuthorizeAttribute>>();
string url = $"{context.HttpContext.Request.Scheme}://{context.HttpContext.Request.Host}{context.HttpContext.Request.Path}{context.HttpContext.Request.QueryString}";
if (!user.Identity.IsAuthenticated)
{
logger.LogInformation($"Unauthroized access to '{url}' from {context.HttpContext.Connection.RemoteIpAddress.ToString()}");
UnauthorizedErrorMessage = UnauthorizedErrorMessage ?? "Unauthorized";
ProblemDetails problemDetails = new ProblemDetails()
{
Title = localizer[UnauthorizedErrorMessage],
Detail = localizer[UnauthorizedErrorMessage + "_Detail"],
Status = StatusCodes.Status401Unauthorized
};
context.Result = new ObjectResult(problemDetails)
{
StatusCode = StatusCodes.Status401Unauthorized,
DeclaredType = problemDetails.GetType(),
};
}
else
{
ForbiddenErrorMessage = ForbiddenErrorMessage ?? "Forbidden";
var authorizeService = context.HttpContext.RequestServices.GetService<IAuthorizationService>();
if (!String.IsNullOrWhiteSpace(Policy))
{
AuthorizationResult result = await authorizeService.AuthorizeAsync(user, Policy);
if (!result.Succeeded)
{
logger.LogWarning($"Forbidden access to '{url}' from {context.HttpContext.Connection.RemoteIpAddress.ToString()}");
ProblemDetails problemDetails = new ProblemDetails()
{
Title = localizer[ForbiddenErrorMessage],
Detail = localizer[ForbiddenErrorMessage + "_Detail"],
Status = StatusCodes.Status403Forbidden
};
context.Result = new ObjectResult(problemDetails)
{
StatusCode = StatusCodes.Status403Forbidden,
DeclaredType = problemDetails.GetType(),
};
}
}
}
}
}
}
上述代码将向客户端返回问题详情。