Mohammad Sadegh Rafiei
Mohammad Sadegh Rafiei

Reputation: 516

response redirection(302) not work in angular

I Designed a login page for SSO(Single Sign-On) by angular and the services for login developed separately by spring boot framework.

In the angular app, when submitted login form, login service call with post-HttpMethod by HttpClient module. In login service if username and password be correct then in the result of login service, set response status to 302 and add a specific URL to the header of the response. in this scenario I expect to browser redirect to specific URL, but this is not happening.

I trace request and response in Firefox as the same as the attached picture Firefox network tab.

  1. Send a post-login request, and response of it is 302 and header location is a specific URL that set in the server response
  2. The browser sends an option request to location URL of response header and gets 200 result
  3. The browser sends a get request to target URL(header location is specific URL), at this point browser is not opening target URL, and the just response is 200.

I change the Location header of response, and saw that the redirection is not doing(just login request and option request done), below picture is request trace. Firefox network tab

Upvotes: 5

Views: 13136

Answers (2)

fascynacja
fascynacja

Reputation: 2826

Something which helped me in similiar scenario was:

this.httpClient
    .post("/mydomain/j_spring_security_logout",
          "{}",
          { observe: 'response' ,responseType: 'text'})
    .subscribe(resp =>  {
        console.log(resp);
        if(resp.url != null) {
            window.location.href = resp.url;
        }
      })

I have used the option observe: 'response' in order to get full information about the final redirection page and I have used its url to set as window.location.

Upvotes: 0

David Palita
David Palita

Reputation: 1293

I suspect your requests are XHR requests. If so, the browser follows them in the handler but won't navigate the full page to the redirect location.

If you want to emulate what happens when a redirect is sent for a full page request, you may want to change your backend so that it returns a 200 with the target location of the original redirect in the payload, and then reload the page to that location (something like window.location = payload.redirectLocation).

You can also get rid of the redirect, let the backend return 200 or 401 depending on the authentication success, then navigate with the angular router.

Upvotes: 6

Related Questions