首页 > 解决方案 > 如果用户未获得授权,则返回较少的数据

问题描述

我在控制器中有这个方法:

[Route("api/AppSearch/Search")]
[HttpPost]
[Authorize]
public async Task<ResponseEntity<AppSearchResponse>> Search([FromBody] AppSearchRequest request, string type = "")
{
    IEnumerable<AppSearchResponse> data = await SearchServiceV2.Search(request.SearchCriteria, request.AppKeyColumn, request.Filters, request.MaxResults, type);
    if (data == null)
    {
        var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent(string.Format("Unknown type ", type)),
            ReasonPhrase = "Unknown type"
        };
        throw new HttpResponseException(resp);
    }
    return this.AssembleSuccessResponse<AppSearchResponse>(data);
}

我想根据用户是否被授权返回不同的数据。如果用户被授权,我希望它返回 AppSearchResponse,如果没有,则返回一个包含 3 个 AppSearchResponse 成员的类。

我最初的想法是创建具有这 3 个字段的 AppSearchResponseBase,然后让 AppSearchResponse 扩展它。然后,检查用户是否在 Controller 方法中获得授权,并将data变量序列化为 AppSearchResponseBase 或 AppSearchResponse

例如

if(authorized){
return this.AssembleSuccessResponse<AppSearchResponse>(data)
} else {
return this.AssembleSuccessResponse<AppSearchResponseBase>(data)
}

我最好只创建一个新资源api/AppSearch/SearchUnauthorized/吗?

标签: c#.netserviceauthorization

解决方案


我会做一些事情,比如有一个单一的类,AppSearchResponse它的信息如下:

public AppSearchResponse{
    public string Username {get;set;}
    public DateTime Joined {get;set;}
    // etc
    public ExtendedData ExtendedData {get;set;}
}

ExtendedData如果用户具有适当的访问权限,则仅填充(其中将包含“安全”字段)。在客户端,ExtendedData如果null 客户端没有提供适当的凭据或其他什么。


推荐阅读