saml认证后重定向到主页(登录)

Redirect to home page after saml authentification (login)

我正在尝试使用 crewjam 库将 saml 与 go 中的开源应用程序集成。

使用 samltest.id 进行身份验证测试后,我希望被重定向到主页。

我尝试了几种方法,但都没有效果,我正在使用 gorilla/mux 路由器:

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

我也测试过:

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

有人可以帮我吗?

谢谢:)

调用w.Write或使用Fmt.Fprintf写入它需要在之前设置HTTP状态代码,否则它会设置默认StatusOK

Server.go

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

多次设置状态码抛出多余的日志。

因此,您的代码将 HTTP 状态代码设置为 200 (http.StatusOk),因此之后的重定向根本不可能。

解决方案:

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

尝试在写作内容之前发送您的headers。 并可选择使用相对位置

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

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