英文:
Better (general) auth implementation
问题
目前我在我的BaseController
中有一个方法,在每个需要用户进行身份验证的控制器方法中,我都需要调用以下代码:
user, err := c.getUser()
if err != nil {
return c.Redirect(UserController.Login)
}
这段代码只是检查在init.go
中是否添加了有效用户到.RenderArgs["user"]
中的
revel.InterceptMethod((*UserController).CheckUser, revel.BEFORE)
有没有办法将这个重定向到登录页面以及身份验证检查放入一个过滤器/拦截方法中,这样我就不必重复以上代码10次了?
(我在revel v0.9~0.10版本中开发了这段代码)
我想到的一个解决方案是编写一个类似于新的csrf模块的模块/应用程序。
编辑于2015年11月4日:此问题发布于一段时间之前,请查看官方的Revel文档,因为revel已经经历了相当多的开发
英文:
Currently I have a method in my BaseController
and in each controller method that I need the user to be authenticated I am left with always calling this piece of code:
user, err := c.getUser()
if err != nil {
return c.Redirect(UserController.Login)
}
Which just checks if
revel.InterceptMethod((*UserController).CheckUser, revel.BEFORE)
(in the init.go)
has added a valid user to .RenderArgs["user"]
.
Is there anyway I can put this redirect to the login page incl. the auth check into an filter / intercept method, so I don't have to repeat the above code 10 times?
(I developed this code around revel v0.9~0.10)
One solution I came up with would be writting a module/app similiar to the new csrf module.
EDIT 4.11.2015: This Question was posted sometime ago, please check back the official Revel documentation as revel has undergone quite some development
答案1
得分: 2
只要身份验证已经正确完成,就不要让请求到达你的控制器。你需要为此实现一个过滤器。具体做法如下:
init.go:
revel.Filters = []revel.Filter{
SessionFilter, // 最好使用安全的实现,不要使用明文的 cookie 等
mypackage.Authenticator
}
mypackage.go:
package mypackage
func Authenticator(c *revel.Controller, fc []revel.Filter) {
// 如果找到身份验证(从会话中),则传递给堆栈中的下一个过滤器
// 如果没有找到,则重定向到身份验证界面,并传递
// 或处理身份验证请求的其他部分...
// 如果身份验证成功,则将其保存到会话中
// 否则,只需丢弃该请求(可能记录日志?)
}
具体细节完全取决于你正在设置的身份验证类型。这里有一个单点登录(SSO)实现供你参考。
英文:
Just don't let the requests to your controllers unless if authentication has properly been done. You need to implement a Filter for that. It means something like
init.go:
revel.Filters = []revel.Filter{
SessionFilter, // Preferably a safe implementation that isn't plaintext cookies etc
mypackage.Authenticator
}
mypackage.go:
package mypackage
func Authenticator(c *revel.Controller, fc []revel.Filter) {
// If authentication found (from session), pass to next Filter in stack
// If not, redirect to your authentication UI, and pass
// Or handle other parts of authentication requests...
// If authentication succeeded, save it to session
// Otherwise just drop the request (probably log?)
}
The specifics depend entirely on what kind of authentication you are setting up. Here is one SSO implementation for your reference.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论