![](/img/trans.png)
[英]How to redirect to a login page if Flutter API response is unauthorized?
[英]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
// 如果没有显式调用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)
}
尝试在编写内容之前发送您的标题。 并且可以选择使用相对位置
w.Header().Add("Location", "/")
w.WriteHeader(http.StatusFound)
fmt.Fprintf(w, "Token contents, %+v!", sa.GetAttributes())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.