我很自豪地宣布发布基于 pac4j v1.8 ( https://github.com/pac4j/pac4j ) 的 play-pac4j v2.0 ( https://github.com/pac4j/play-pac4j )任何 Play 2 网络应用程序。它现在是一个 完整的安全库,简单而强大,支持身份验证和授权 ,还支持应用程序注销和 CSRF 保护等高级功能。
它支持大多数身份验证机制:OAuth(Facebook、Twitter、Google、Yahoo...)、CAS、HTTP(表单、基本身份验证...)、OpenID、SAML、Google App Engine、OpenID Connect、JWT、LDAP、RDBMS、 MongoDB 和 Stormpath 以及授权检查(角色/权限、CSRF 令牌...)
通过四个简单的步骤,保护您的网络应用程序:
1) 添加对库的依赖(Java Play 应用程序的 play-pac4j-java 或 Scala 应用程序的 play-pac4j-scala_2.11 )和所需的身份验证机制(例如 Facebook 的 pac4j-oauth 库)
2) 在模块中定义身份验证机制(客户端)和授权者(检查授权)。例如:Facebook 身份验证和 ROLE_ADMIN
public class SecurityModule extends AbstractModule {
@Override
protected void configure() {
FacebookClient facebookClient = new FacebookClient("xx", "yy");
Clients clients = new Clients("http://localhost:9000/callback", facebookClient);
Config config = new Config(clients);
config.addAuthorizer("admin", new RequireAnyRoleAuthorizer("ROLE_ADMIN"));
bind(Config.class).toInstance(config);
}
}
3) 定义用于 Facebook 身份验证的回调控制器( 路由 ):
public class SecurityModule extends AbstractModule {
@Override
protected void configure() {
FacebookClient facebookClient = new FacebookClient("xx", "yy");
Clients clients = new Clients("http://localhost:9000/callback", facebookClient);
Config config = new Config(clients);
config.addAuthorizer("admin", new RequireAnyRoleAuthorizer("ROLE_ADMIN"));
bind(Config.class).toInstance(config);
}
}
4) 保护 /facebook/index.html url 以要求用户进行身份验证,如果没有,则执行 Facebook 身份验证:
public class SecurityModule extends AbstractModule {
@Override
protected void configure() {
FacebookClient facebookClient = new FacebookClient("xx", "yy");
Clients clients = new Clients("http://localhost:9000/callback", facebookClient);
Config config = new Config(clients);
config.addAuthorizer("admin", new RequireAnyRoleAuthorizer("ROLE_ADMIN"));
bind(Config.class).toInstance(config);
}
}
public class SecurityModule extends AbstractModule {
@Override
protected void configure() {
FacebookClient facebookClient = new FacebookClient("xx", "yy");
Clients clients = new Clients("http://localhost:9000/callback", facebookClient);
Config config = new Config(clients);
config.addAuthorizer("admin", new RequireAnyRoleAuthorizer("ROLE_ADMIN"));
bind(Config.class).toInstance(config);
}
}
和/或要求用户拥有 ROLE_ADMIN:
public class SecurityModule extends AbstractModule {
@Override
protected void configure() {
FacebookClient facebookClient = new FacebookClient("xx", "yy");
Clients clients = new Clients("http://localhost:9000/callback", facebookClient);
Config config = new Config(clients);
config.addAuthorizer("admin", new RequireAnyRoleAuthorizer("ROLE_ADMIN"));
bind(Config.class).toInstance(config);
}
}
阅读文档:https: //github.com/pac4j/play-pac4j 并在 Java 中尝试演示:https: //github.com/pac4j/play-pac4j-java-demo 或在 Scala 中: https://github .com/pac4j/play-pac4j-scala-演示