Redirect to home page after saml authentification (login)

Issue

I’m trying to integrate saml using crewjam library with an open-source app in go.

After authentication test using samltest.id, I want to be redirected to the home page.

I have tried several ways, but nothing works well, i’m using gorilla/mux router:

func login(w http.ResponseWriter, r *http.Request) {
    s := samlsp.SessionFromContext(r.Context())
    if s == nil {
        return
    }
    sa, ok := s.(samlsp.SessionWithAttributes)
    if !ok {
        return
    }
    fmt.Fprintf(w, "Token contents, %+v!", sa.GetAttributes())

    w.Header().Add("Location", "http://localhost:8080/")
    w.WriteHeader(http.StatusFound)
}

I have also tested :

http.Redirect(w, r, "http://localhost:8080/", http.StatusFound)

Can someone help me please?

Thanks 🙂

Solution

Calling w.Write or writing into it using Fmt.Fprintf requires HTTP status code to be set before, otherwise it sets default StatusOK

Server.go

// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).

Setting the status code multiple times throws superfluous log.

Therefore, Your code is setting the HTTP status code to 200 (http.StatusOk), so the redirect after that is simply impossible.

Solution:

func login(w http.ResponseWriter, r *http.Request) {
    s := samlsp.SessionFromContext(r.Context())
    if s == nil {
        return
    }
    sa, ok := s.(samlsp.SessionWithAttributes)
    if !ok {
        return
    }
    // this line is removed 
    // fmt.Fprintf(w, "Token contents, %+v!", sa.GetAttributes())

    w.Header().Add("Location", "http://localhost:8080/")
    w.WriteHeader(http.StatusFound)
    // Or Simply 
    // http.Redirect(w, r, "http://localhost:8080/", http.StatusFound)
}

Answered By – Dyn4sty

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.