1

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 :)

2
  • Does your code reach the` http.Redirect(w, r, "localhost:8080", http.StatusFound)` portion? the redirection should work, try checking if the ok value is not nil (you might have an error).
    – Dyn4sty
    May 11, 2022 at 15:31
  • yes, I have an ok because I have the content of fmt.Fprintf which is displayed well on the page
    – Abder-Edrs
    May 11, 2022 at 15:44

2 Answers 2

3

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)
}
2

Try to send your headers before writing content. And optionally use a relative Location

w.Header().Add("Location", "/")
w.WriteHeader(http.StatusFound)

fmt.Fprintf(w, "Token contents, %+v!", sa.GetAttributes())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.