Play framework is joining the Typesafe Stack — More information in the official announcement
Manual, tutorials & references
Get help with google
The simple Secure module help you to set up basic authentication and authorization management to your application. It provides a simple controllers.Secure controller that defines a set of interceptors that you can easily add to your own controllers using the @With annotation.
In the /conf/application.conf file, enable the Secure module by adding this line:
# The secure module
module.secure=${play.path}/modules/secure
In the conf/routes file, import the default module routes by adding this line:
# Import Secure routes
* / module:secure
Note that it’s not required to use the default routes file. You can also define your own routes, or mix the two.
To protect a controller you just have to annotate it using @With. For example:
@With(Secure.class)
public class Application extends Controller {
public static void index() {
render();
}
}
This controller will be automatically protected with the default authentication page.
By default, the login page will accept any login/password. To customize it your application has to provide a Security provider. Just create a class in the controllers package that extends the controllers.Secure.Security class. Then you can override the authentify(String username, String password) method.
package controllers;
public class Security extends Secure.Security {
static boolean authentify(String username, String password) {
User user = User.find("byEmail", username);
return user != null && user.password.equals(password);
}
}
Note that you can override other methods as well to customize how the application should react to authentication events (onAuthenticated, onDisconnected).
From your application code, your can reuse the Security helper that you’ve just created to retrieve the connected user.
@With(Secure.class)
public class Application extends Controller {
public static void index() {
String user = Security.connected();
render(user);
}
}
You can use the @Check annotation either on controller classes or action methods to tell the Secure module to check that the connected user has required authorization to call this action.
For example:
@With(Secure.class)
public class Application extends Controller {
...
@Check("isAdmin")
public static void delete(Long id) {
...
}
}
By default the secure module will always authorize all checks. You have to customize by overriding one more method in your Security class.
package controllers;
public class Security extends Secure.Security {
...
static boolean check(String profile) {
User user = User.find("byEmail", connected());
return user.admin;
}
}
Comments
Use this form to add corrections, additions and suggestions about the documentation on this page. Please ask questions on the play-framework group instead. Support requests, bug reports, and off-topic comments will be deleted without warning.