在ASP.NET标识中处理未经身份验证或未经授权的API请求

iqih9akk  于 2023-11-20  发布在  .NET
关注(0)|答案(2)|浏览(125)

我目前正在做一个ASP.NET项目,我使用ASP.NET Identity来管理用户帐户。我的Web应用程序中还包含一个API。我目前的问题是,当客户端发出未经身份验证或授权的API请求时,它们会被重定向到登录/禁止页面。然而,我希望这样的API请求返回一个JSON错误,而不是将用户重定向到登录页面。有人能帮助我如何在我的ASP.NET应用程序中自定义此行为吗?是否有任何特定的中间件或设置,我需要配置,以实现这一行为?任何帮助或建议将不胜感激。

1wnzp6jl

1wnzp6jl1#

在你随后的描述中,我理解你
希望发出API请求以返回JSON错误,而不是将用户重定向到登录页面
在我的选择中,我建议你可以创建一个中间件来处理API请求和网页请求:

public class ApiRequestMiddleware
{
    private readonly RequestDelegate _next;

    public ApiRequestMiddleware(RequestDelegate next)
    {
        _next = next;
    }
 
    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Path.StartsWithSegments("/api"))
        {
            
            try
            {
                
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                context.Response.ContentType = "application/json";

                var errorResponse = new
                {
                    message = "Unauthorized API requests",
                    error = "Authentication failed"
                };

                await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
            }
            catch (Exception ex)
            {
                
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                context.Response.ContentType = "application/json";

                var errorResponse = new
                {
                    message = "serve error",
                    error = ex.Message
                };

                await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
            }
        }
        else
        {
            
            await _next(context);
        }
    }
}

字符串

iovurdzv

iovurdzv2#

根据你对我的解决方案的建议,我对我的代码进行了改进:

public class ApiRequestMiddleware
    {
        private readonly RequestDelegate _next;
       
        public ApiRequestMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path.StartsWithSegments("/api"))
            {
                
                try
                {
                    if  (context.User.Identity.IsAuthenticated && context.User.IsInRole("Administrator"))
                        {
                        var user = context.User;
                        var userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                        var username = user.FindFirst(ClaimTypes.Name)?.Value;
                      
                        context.Response.ContentType = "application/json";
                        var successResponse = new
                        {
                            message = "Authorization passed",
                            UserId = userId,
                            Username = username
                        };
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(successResponse));

                    }
                    else
                    { 
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        context.Response.ContentType = "application/json";

                        var errorResponse = new
                        {
                            message = "Unauthorized API requests",
                            error = "Authentication failed"
                        };

                        await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
                    }
                }
                catch (Exception ex)
                { 
                    context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    context.Response.ContentType = "application/json";

                    var errorResponse = new
                    {
                        message = "serve error",
                        error = ex.Message
                    };

                    await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
                }
            }
            else
            {
                await _next(context);
            }
        }
    }

}

字符串
当我通过授权时,API将返回当前用户数据:

当I Unauthorized API请求时,它将返回一个json:



还有另一种方法:

public async Task Invoke(HttpContext context)
{
    if (context.Request.Path.StartsWithSegments("/api"))
    {
                
        try
        {
            if  (context.User.Identity.IsAuthenticated && context.User.IsInRole("Administrator"))
                {
                        
                if (context.Request.Path.StartsWithSegments("/api/Test"))
                {
                    await CallApiResource(context);
                }
            }
            else
            { 
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                context.Response.ContentType = "application/json";

                var errorResponse = new
                {
                    message = "Unauthorized API requests",
                    error = "Authentication failed"
                };

                await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
            }
        }
        catch (Exception ex)
        { 
            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            context.Response.ContentType = "application/json";

            var errorResponse = new
            {
                message = "serve error",
                error = ex.Message
            };

            await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
        }
    }
    else
    {
        await _next(context);
    }
}

private async Task CallApiResource(HttpContext context)
{
           
     var apiController = new TestApiController();
     var apiData = apiController.GetUsers() as ObjectResult;

     if (apiData != null)
     {
         var users = apiData.Value;

               
         var successResponse = new
         {
             message = "Authorization passed",
             data = users
         };

         var json = JsonConvert.SerializeObject(successResponse);

         context.Response.ContentType = "application/json";
         context.Response.StatusCode = StatusCodes.Status200OK;
         await context.Response.WriteAsync(json);
     }
}

[Route("api/test")]
[ApiController]
public class TestApiController : ControllerBase
{
    [HttpGet("users")]
    public IActionResult GetUsers()
    {
       
        var users = new List<string> { "User1", "User2", "User3" };

        return Ok(users);
    }
}


当我通过授权时,我可以通过CallApiResource获取用户:

当我未经授权:

相关问题