ASP Net Core Auth-RedirectToAction返回目标操作

时间:2019-03-18 18:04:50

标签: asp.net asp.net-mvc api

在ASP.NET Core Rest API项目中,我已经设置了自定义身份验证,并且可以使用[Authorize]属性注释Controller Action,该属性将未经授权的请求重定向回我的AuthController:

[Route("api/[controller]")]
[ApiController]
public class ResponseController : ControllerBase
{
    [Authorize]
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        return JsonConvert.SerializeObject(Repository.GetResponse(id), Formatting.Indented);
    }
}

[Route("api/[controller]")]
[ApiController]
public class MetaController : ControllerBase
{
    [Authorize]
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        return JsonConvert.SerializeObject(Repository.GetMeta(id), Formatting.Indented);
    }
}

[Route("api/[controller]")]
[ApiController]
public class AuthController : Controller
{
    UserManager _userManager;
    public AuthController(UserManager userManager)
    {
        _userManager = userManager;
    }
    [HttpGet]
    [HttpPost]
    public ActionResult<string> LogIn()
    {
        try
        {
            //authenticate
            var username = Request.Headers["username"];
            var password = Request.Headers["pass"];
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
                throw new Exception("Authentication Exception: Missing Username or Password");

            Task.Run(async () => {
                await _userManager.SignInAsync(this.HttpContext, username, password);
            }).GetAwaiter().GetResult();

            return RedirectToAction("Search", "Home", null);
            //^^^ How to send back to intended action?^^^
        }
        catch (Exception ex)
        {
            return AuthError();
        }
    }
}

这可行,除了我如何使用RedirectToAction方法返回到预期的控制器(在这种情况下为MetaControllerResponseController)之外? (带有标记为[Authorize]的方法的代码,它首先使我们进入了此身份验证控制器)

2 个答案:

答案 0 :(得分:1)

代替重定向,创建从AuthorizeAttribute继承的自己的属性,并覆盖OnAuthorization方法。这样,您就不必担心重定向。

答案 1 :(得分:1)

您需要使用returnUrl参数,如下所示:

[HttpGet]
[HttpPost]
public async Task<IActionResult> LogIn(string returnUrl = null)
{
    try
    {
        //authenticate
        var username = Request.Headers["username"];
        var password = Request.Headers["pass"];
        if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            throw new Exception("Authentication Exception: Missing Username or Password");

        await _userManager.SignInAsync(this.HttpContext, username, password);
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }

        return RedirectToAction("Search", "Home", null);
    }
    catch (Exception ex)
    {
        return BadRequest(new {error = "Authentication Failed"});
    }
}

我也修复了异步/等待控制器的动作。您需要使用async Task<ActionResult>插入的ActionResult<string>