Home > Net >  Redirect to home page after saml authentification (login)
Redirect to home page after saml authentification (login)

Time:05-12

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

CodePudding user response:

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

CodePudding user response:

Try to send your headers before writing content. Fix the HTTP status code. And optionally use a relative Location

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

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