我正在与外部提供商一起在我的应用程序中实现 OAuth2 授权。当用户从授权服务器重定向回我的应用程序时,尽管使用
Redirect()
方法指定 URL,我的应用程序仍会将用户重定向回来。
程序.cs
builder.Services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "ExternalProvider";
})
.AddCookie()
.AddOAuth("ExternalProvider", options =>
{
...
options.CallbackPath = new PathString("/auth/callback");
...
options.Events.OnCreatingTicket = async context =>
{
HttpRequestMessage req = new(HttpMethod.Get, context.Options.UserInformationEndpoint);
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
HttpResponseMessage res = await context.Backchannel.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
res.EnsureSuccessStatusCode();
var user = JsonDocument.Parse(await res.Content.ReadAsStringAsync()).RootElement;
context.RunClaimActions(user);
// Save user to database if it doesn't exist
ApplicationDbContext dbContext = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();
int userId = int.Parse(user.GetString("sub"));
// Check if user exists
bool userExists = (await dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId)) is not null;
if (!userExists)
{
// Save the user
string username = user.GetString("preferred_username");
string profilePicture = user.GetString("picture");
dbContext.Users.Add(new ApplicationUser()
{
Id = userId,
Username = username,
ProfilePicture = profilePicture
});
await dbContext.SaveChangesAsync();
}
context.Response.Redirect("/Home/Index"); // User is still redirected to /auth/login
};
});
AuthController.cs
using Microsoft.AspNetCore.Mvc;
namespace Frontend.Controllers
{
public class AuthController : Controller
{
public IActionResult Login()
{
return Challenge("ExternalProvider");
}
}
}
HomeController.cs
using Microsoft.AspNetCore.Mvc;
namespace Frontend.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
我想在授权过程完成后返回 MVC 视图,我尝试通过将用户重定向到家庭控制器来实现此目的,但没有成功,因为用户将被重定向回授权。
保持重定向的原因是你在 OnCreatingTicket 中设置
context.Response.Redirect("/Home/Index");
不起作用。
返回 url 在 AuthController 内部调用 Challenge 方法时设置。
如下修改即可正常运行。
var properties = new AuthenticationProperties
{
RedirectUri = "/home/index"
};
return Challenge(properties,"ExternalProvider");