【发布时间】:2018-08-10 05:33:51
【问题描述】:
我正在尝试将身份服务器 4 用作 SSO 站点,前端编写为 SPA(框架不重要)
示例项目使用 MVC,当用户登录页面时,它会发布到控制器,该控制器将浏览器重定向到返回 URL。
我在修改此流程以使其以更 AJAX 方式工作时遇到问题。首先,我希望能够将用户名/密码提交给 API 控制器,这样我就可以在不刷新页面的情况下取回验证错误等。如果登录成功,我需要将浏览器重定向到 returnUrl,但我无法让它工作,并且回调 url 再次将用户返回到登录页面,而不是重定向到登录的客户端应用程序。
这是我的登录端点的样子:
[HttpPost]
[Route("api/identity/login")]
public async Task<IActionResult> Login(LoginInputModel model)
{
// check credentials in model etc
await _eventsService.RaiseAsync(new UserLoginSuccessEvent(model.Email, subjectId, model.Email));
await HttpContext.SignInAsync(subjectId, model.Email, new AuthenticationProperties());
return Ok();
}
作为前端的简单表单,它托管在静态 html 页面上:
<form>
<label for="email">Email</label>
<input id="email" type="email" />
<label for="password">Password</label>
<input id="password" type="password" />
<button onclick="login()" type="submit">Log me in</button>
</form>
<script>
var email = document.querySelector('#email').value;
var password = document.querySelector('#password').value;
var returnUrl = unescape(window.location.search.replace('?returnUrl=', ''));
fetch('/api/identity/login', {
body: JSON.stringify({ email, password }),
headers: new Headers({
'Content-Type': 'application/json'
}),
method: 'POST'
}).then(() => {
var returnUrl = unescape(window.location.search.replace('?returnUrl=', ''));
window.location = window.location.origin + returnUrl;
})
</script>
在 200 响应中,我使用 javascript 将浏览器重定向到 returnUrl。
我不确定我缺少什么才能让它工作。我需要让用户登录并在一次通话中重定向所有内容吗?
我在这里修改了一个现有的示例应用程序,它可以按预期使用直接发布/重定向方法,因此主机和客户端配置都没有改变:https://github.com/BenjaminAbt/Samples.AspNetCore-IdentityServer4
【问题讨论】:
-
您需要提供更多代码。请展示您已经完成的工作,而不是您正在努力实现的目标。
-
嗨@Brad,我已经包含了更多代码。我对问题的解释够清楚了吗?
-
您是否将您的路由设置为
path: ' ', component: LoginComponent? -
@k11k2 不确定您的意思,因为我在站点根目录为登录 ui 提供静态页面,所以我在 Startup.cs 中设置了这个:
services.AddIdentityServer(options => { options.UserInteraction.LoginUrl = "/"; }) -
@dpix,只是出于兴趣,您将如何在这里使用 ajax 方法处理部分登录的场景?比如 2FA、同意、强制密码重置或登录前可能需要的任何东西?
标签: asp.net-core single-page-application identityserver4