Reputation: 3103
I'm trying to use identity server 4 as a SSO site with a front-end written as an SPA (framework not important)
The Example project uses MVC, which when the user logs in the page posts to a controller that redirects the browser to the return URL.
I'm having trouble modifying this flow to work in a more AJAX fashion. Firstly I want to be able to submit the username/password to an API controller so that I can get back validation errors etc without doing a page refresh. Given a successful login I then need to redirect the browser to the returnUrl, but I cannot get this to work and the callback url returns the user back to the login page again rather than redirecting to the client app logged in.
This is what my login endpoint looks like:
[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();
}
And simple form as a front-end, this is hosted on a static html page:
<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>
On a 200 response I use javascript to redirect the browser to the returnUrl.
I'm not sure what I'm missing to get this to work. Do I need to sign the user in and redirect all in one call?
I am modifying an existing example app here which does work with the direct post/redirect method as expected, so both host and client config is unchanged: https://github.com/BenjaminAbt/Samples.AspNetCore-IdentityServer4
Upvotes: 1
Views: 1410
Reputation: 3103
After investigating some logs and watching the requests a little more carefully I realised that the login response from the AJAX request was not setting the authentication cookie on the browser.
Setting the credentials
option in the fetch request to 'same-origin'
fixed the issue
thanks to this stackoverflow answer: https://stackoverflow.com/a/39233628
Upvotes: 1