为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
眼眸繁星 2022-12-13 15:58:00
我正在尝试使用crewjam库将 saml 与开源应用程序集成在一起。使用 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)有人能帮助我吗?
查看完整描述

2 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

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

服务器.go

// 如果未显式调用 WriteHeader,则第一次调用 Write
// 将触发隐式 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)

}


查看完整回答
反对 回复 2022-12-13
?
莫回无

TA贡献1865条经验 获得超7个赞

尝试在编写内容之前发送标题。并可选择使用相对位置


w.Header().Add("Location", "/")

w.WriteHeader(http.StatusFound)


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


查看完整回答
反对 回复 2022-12-13
  • 2 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号