如何使用播放框架安全模块在创建用户后登录用户 [英] How to use play frameworks Secure module to login a user after that user has been created
问题描述
我正在使用play框架中的Secure模块,它的工作效果非常好。我可以通过在我的应用程序中的/ login路由发布一个来登录用户。
I am using the "Secure" module from play framework and its mostly working great. I can login a user by posting a from the the /login route in my application.
然而,当我创建/注册一个新用户时,我想要用户创建后自动登录的用户。这样,我似乎无法以编程方式工作,即不必发布表单进行登录。
However, when I "create/signup" a new user, I would like for that user to be automatically logged in after user creation. This, I can't seem to get working programmatically, i.e., by not having to post a form to login.
我的用户创建操作的当前代码如下:
My current code for my user create action is like:
public static void create(@Required @Email String email, @Required String password, @Required @Equals("password") String passwordConfirmation) {
User user = new User(email);
user.password = new Crypto().encryptAES(password);
user.save();
try {
Secure.authenticate(email, password, false); // <== this is the action in secure module mapped to /login
} catch(Throwable t) {
t.printStackTrace();
}
}
所以我手动调用 Secure .authentication(用户名,密码,记住)
方法,但这只是将我重定向到登录页面而不是我的目标页面。
So I manually call Secure.authentication(username, password, remember)
method, but this just redirects me to the login page and not my target page.
我有因为我直接调用Secure.authenticate而不是通过请求/响应,所以感觉没有设置cookie或其他东西,但我只是不确定。
I have a feeling that a cookie or something is not being set because I am calling Secure.authenticate directly and not via a request/response, but I'm just not sure.
任何想法?
推荐答案
一个想法可能是在会话中设置用户名(用户成功注册后)
One idea could be to set the username in the session (after user signed up successfully)
session.put("username", username);
这将确保Secure.connected()按预期返回。
This will make sure Secure.connected() return as expected.
如果你需要'记住我',
if you need 'remember me',
if(remember){
response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
}
实际上,这是安全模块在成功验证后所做的事情。
查看安全模块
Actually this is what Secure module does after successful authentication. Check Secure module
这篇关于如何使用播放框架安全模块在创建用户后登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!