From fc5ad8e88e884bcdf377d75c4dc2d6851f95cfb7 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Mon, 28 May 2018 21:45:51 +0000 Subject: [PATCH] java ee 8 security api --- .../app-auth-basic-store-db/pom.xml | 72 +++++++++++++++++ .../javaee/security/AdminServlet.java | 22 +++++ .../baeldung/javaee/security/AppConfig.java | 16 ++++ .../javaee/security/DatabaseSetupServlet.java | 59 ++++++++++++++ .../baeldung/javaee/security/UserServlet.java | 25 ++++++ .../src/main/liberty/config/server.xml | 9 +++ .../app-auth-custom-form-store-custom/pom.xml | 42 ++++++++++ .../baeldung/javaee/security/AppConfig.java | 17 ++++ .../InMemoryIdentityStore4Authentication.java | 46 +++++++++++ .../InMemoryIdentityStore4Authorization.java | 46 +++++++++++ .../baeldung/javaee/security/LoginBean.java | 81 +++++++++++++++++++ .../javaee/security/WelcomeServlet.java | 31 +++++++ .../src/main/liberty/config/server.xml | 9 +++ .../src/main/webapp/WEB-INF/beans.xml | 7 ++ .../src/main/webapp/WEB-INF/web.xml | 27 +++++++ .../src/main/webapp/login-error.html | 10 +++ .../src/main/webapp/login.xhtml | 32 ++++++++ .../src/main/webapp/welcome.xhtml | 19 +++++ .../app-auth-custom-no-store/pom.xml | 72 +++++++++++++++++ .../javaee/security/AdminServlet.java | 28 +++++++ .../baeldung/javaee/security/AppConfig.java | 7 ++ .../javaee/security/CustomAuthentication.java | 36 +++++++++ .../javaee/security/CustomPrincipal.java | 22 +++++ .../baeldung/javaee/security/UserDetail.java | 38 +++++++++ .../src/main/liberty/config/server.xml | 9 +++ .../src/main/webapp/login-error.html | 10 +++ .../src/main/webapp/login.html | 25 ++++++ .../app-auth-form-store-ldap/pom.xml | 50 ++++++++++++ .../javaee/security/AdminServlet.java | 22 +++++ .../baeldung/javaee/security/AppConfig.java | 22 +++++ .../javaee/security/LdapSetupServlet.java | 45 +++++++++++ .../baeldung/javaee/security/UserServlet.java | 22 +++++ .../src/main/liberty/config/server.xml | 9 +++ .../src/main/resources/users.ldif | 47 +++++++++++ .../src/main/webapp/login-error.html | 10 +++ .../src/main/webapp/login.html | 25 ++++++ java-ee-8-security-api/pom.xml | 73 +++++++++++++++++ pom.xml | 1 + 38 files changed, 1143 insertions(+) create mode 100644 java-ee-8-security-api/app-auth-basic-store-db/pom.xml create mode 100644 java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java create mode 100644 java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java create mode 100644 java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java create mode 100644 java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java create mode 100644 java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml create mode 100644 java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml create mode 100644 java-ee-8-security-api/app-auth-custom-no-store/pom.xml create mode 100644 java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java create mode 100644 java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java create mode 100644 java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java create mode 100644 java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java create mode 100644 java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java create mode 100644 java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml create mode 100644 java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html create mode 100644 java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html create mode 100644 java-ee-8-security-api/app-auth-form-store-ldap/pom.xml create mode 100644 java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java create mode 100644 java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java create mode 100644 java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java create mode 100644 java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java create mode 100644 java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml create mode 100644 java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif create mode 100644 java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html create mode 100644 java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html create mode 100644 java-ee-8-security-api/pom.xml diff --git a/java-ee-8-security-api/app-auth-basic-store-db/pom.xml b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml new file mode 100644 index 0000000000..7782fd0479 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + app-auth-basic-store-db + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + 1.4.197 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy + + + + + + + com.h2database + h2 + ${h2-version} + jar + + ${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global + + + + + + + + diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..32adbf1abb --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..a16d944f5a --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition; +import javax.security.enterprise.identitystore.DatabaseIdentityStoreDefinition; + +@BasicAuthenticationMechanismDefinition(realmName = "defaultRealm") +@DatabaseIdentityStoreDefinition( + dataSourceLookup = "java:comp/env/jdbc/securityDS", + callerQuery = "select password from users where username = ?", + groupsQuery = "select GROUPNAME from groups where username = ?" +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java new file mode 100644 index 0000000000..3658826e4d --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java @@ -0,0 +1,59 @@ +package com.baeldung.javaee.security; + +import javax.annotation.Resource; +import javax.annotation.sql.DataSourceDefinition; +import javax.inject.Inject; +import javax.security.enterprise.identitystore.Pbkdf2PasswordHash; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +@DataSourceDefinition( + name = "java:comp/env/jdbc/securityDS", + className = "org.h2.jdbcx.JdbcDataSource", + url = "jdbc:h2:~/securityTest;MODE=Oracle" +) +@WebServlet(value = "/init", loadOnStartup = 0) +public class DatabaseSetupServlet extends HttpServlet { + + @Resource(lookup = "java:comp/env/jdbc/securityDS") + private DataSource dataSource; + + @Inject + private Pbkdf2PasswordHash passwordHash; + + @Override + public void init() throws ServletException { + super.init(); + initdb(); + } + + private void initdb() { + executeUpdate(dataSource, "DROP TABLE IF EXISTS USERS"); + executeUpdate(dataSource, "DROP TABLE IF EXISTS GROUPS"); + + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS USERS(username VARCHAR(64) PRIMARY KEY, password VARCHAR(255))"); + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS GROUPS(username VARCHAR(64), GROUPNAME VARCHAR(64))"); + + executeUpdate(dataSource, "INSERT INTO USERS VALUES('admin', '" + passwordHash.generate("passadmin".toCharArray()) + "')"); + executeUpdate(dataSource, "INSERT INTO USERS VALUES('user', '" + passwordHash.generate("passuser".toCharArray()) + "')"); + + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'admin_role')"); + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'user_role')"); + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('user', 'user_role')"); + } + + private void executeUpdate(DataSource dataSource, String query) { + try (Connection connection = dataSource.getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(query)) { + statement.executeUpdate(); + } + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java new file mode 100644 index 0000000000..548b5f6d85 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java @@ -0,0 +1,25 @@ +package com.baeldung.javaee.security; + +import javax.annotation.security.DeclareRoles; +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + + +@WebServlet("/user") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"})) +public class UserServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml new file mode 100644 index 0000000000..35a90621ae --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + app-auth-custom-form-store-custom + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..bba9fa36ce --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.faces.annotation.FacesConfig; +import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; + + +@CustomFormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue( + loginPage = "/login.xhtml", + errorPage = "/login-error.html" + ) +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java new file mode 100644 index 0000000000..54219f9750 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java @@ -0,0 +1,46 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import java.util.*; + +import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT; + +@ApplicationScoped +public class InMemoryIdentityStore4Authentication implements IdentityStore { + + private Map users = new HashMap<>(); + + public InMemoryIdentityStore4Authentication() { + //Init users + // from a file or hardcoded + init(); + } + + private void init() { + //user1 + users.put("user", "pass0"); + //user2 + users.put("admin", "pass1"); + } + + @Override + public int priority() { + return 70; + } + + @Override + public Set validationTypes() { + return EnumSet.of(ValidationType.VALIDATE); + } + + public CredentialValidationResult validate(UsernamePasswordCredential credential) { + String password = users.get(credential.getCaller()); + if (password != null && password.equals(credential.getPasswordAsString())) { + return new CredentialValidationResult(credential.getCaller()); + } + return INVALID_RESULT; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java new file mode 100644 index 0000000000..f088ab80b9 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java @@ -0,0 +1,46 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import java.util.*; + +@ApplicationScoped +class InMemoryIdentityStore4Authorization implements IdentityStore { + + private Map> userRoles = new HashMap<>(); + + public InMemoryIdentityStore4Authorization() { + //Init users + // from a file or hardcoded + init(); + } + + private void init() { + //user1 + List roles = new ArrayList<>(); + roles.add("USER_ROLE"); + userRoles.put("user", roles); + //user2 + roles = new ArrayList<>(); + roles.add("USER_ROLE"); + roles.add("ADMIN_ROLE"); + userRoles.put("admin", roles); + } + + @Override + public int priority() { + return 80; + } + + @Override + public Set validationTypes() { + return EnumSet.of(ValidationType.PROVIDE_GROUPS); + } + + @Override + public Set getCallerGroups(CredentialValidationResult validationResult) { + List roles = userRoles.get(validationResult.getCallerPrincipal().getName()); + return new HashSet<>(roles); + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java new file mode 100644 index 0000000000..f8ee83432a --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java @@ -0,0 +1,81 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.RequestScoped; +import javax.faces.annotation.FacesConfig; +import javax.faces.application.FacesMessage; +import javax.faces.context.FacesContext; +import javax.inject.Inject; +import javax.inject.Named; +import javax.security.enterprise.AuthenticationStatus; +import javax.security.enterprise.SecurityContext; +import javax.security.enterprise.credential.Credential; +import javax.security.enterprise.credential.Password; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.constraints.NotNull; + +import static javax.faces.application.FacesMessage.SEVERITY_ERROR; +import static javax.security.enterprise.AuthenticationStatus.SEND_CONTINUE; +import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE; +import static javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters.withParams; + +@FacesConfig +@Named +@RequestScoped +public class LoginBean { + + @Inject + private SecurityContext securityContext; + + @Inject + private FacesContext facesContext; + + @NotNull + private String username; + + @NotNull + private String password; + + public void login() { + Credential credential = new UsernamePasswordCredential(username, new Password(password)); + AuthenticationStatus status = securityContext.authenticate( + getHttpRequestFromFacesContext(), + getHttpResponseFromFacesContext(), + withParams().credential(credential)); + if (status.equals(SEND_CONTINUE)) { + facesContext.responseComplete(); + } else if (status.equals(SEND_FAILURE)) { + facesContext.addMessage(null, + new FacesMessage(SEVERITY_ERROR, "Authentication failed", null)); + } + } + + private HttpServletRequest getHttpRequestFromFacesContext() { + return (HttpServletRequest) facesContext + .getExternalContext() + .getRequest(); + } + + private HttpServletResponse getHttpResponseFromFacesContext() { + return (HttpServletResponse) facesContext + .getExternalContext() + .getResponse(); + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java new file mode 100644 index 0000000000..fb9c944140 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java @@ -0,0 +1,31 @@ +package com.baeldung.javaee.security; + +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet("/welcome") +@ServletSecurity(@HttpConstraint(rolesAllowed = "USER_ROLE")) +public class WelcomeServlet extends HttpServlet { + + @Inject + private SecurityContext securityContext; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + securityContext.hasAccessToWebResource("/protectedServlet", "GET"); + resp.getWriter().write("" + + "Authentication type :" + req.getAuthType() + "\n" + + "Caller Principal :" + securityContext.getCallerPrincipal() + "\n" + + "User in Role USER_ROLE :" + securityContext.isCallerInRole("USER_ROLE") + "\n" + + "User in Role ADMIN_ROLE :" + securityContext.isCallerInRole("ADMIN_ROLE") + "\n" + + ""); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..2f4726a77e --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,7 @@ + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..bd219bf983 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,27 @@ + + + + + javax.faces.validator.ENABLE_VALIDATE_WHOLE_BEAN + true + + + + javax.faces.ENABLE_CDI_RESOLVER_CHAIN + true + + + + Faces Servlet + javax.faces.webapp.FacesServlet + 1 + + + Faces Servlet + *.xhtml + + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html new file mode 100644 index 0000000000..c540797b54 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Custom Form Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml new file mode 100644 index 0000000000..48928b2513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml @@ -0,0 +1,32 @@ + + + + + + + +

+ Custom Form-based Authentication +

+ +
+

+ Username + +

+

+ Password + +

+

+ +

+
+ + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml new file mode 100644 index 0000000000..d1a18db626 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml @@ -0,0 +1,19 @@ + + + + + + + +

+ Welcome !! +

+ + + + diff --git a/java-ee-8-security-api/app-auth-custom-no-store/pom.xml b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml new file mode 100644 index 0000000000..32e20fb066 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + app-auth-custom-no-store + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + 1.4.197 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy + + + + + + + com.h2database + h2 + ${h2-version} + jar + + ${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global + + + + + + + + diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..bef9e20038 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,28 @@ +package com.baeldung.javaee.security; + +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.security.Principal; + +@WebServlet("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Inject + SecurityContext securityContext; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("getCallerPrincipal :" + securityContext.getCallerPrincipal() + "\n"); + response.getWriter().append("CustomPrincipal :" + securityContext.getPrincipalsByType(CustomPrincipal.class) + "\n"); + response.getWriter().append("Principal :" + securityContext.getPrincipalsByType(Principal.class) + "\n"); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..e93360db4d --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,7 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; + +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java new file mode 100644 index 0000000000..9accf3c752 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java @@ -0,0 +1,36 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.AuthenticationException; +import javax.security.enterprise.AuthenticationStatus; +import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism; +import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.HashSet; + +@ApplicationScoped +public class CustomAuthentication implements HttpAuthenticationMechanism { + + @Override + public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + HttpMessageContext httpMessageContext) throws AuthenticationException { + String username = httpServletRequest.getParameter("username"); + String password = httpServletRequest.getParameter("password"); + //Mocking UserDetail, but in real life, we can find it from a database. + UserDetail userDetail = findByUserNameAndPassword(username, password); + if (userDetail != null) { + return httpMessageContext.notifyContainerAboutLogin( + new CustomPrincipal(userDetail), + new HashSet<>(userDetail.getRoles())); + } + return httpMessageContext.responseUnauthorized(); + } + + private UserDetail findByUserNameAndPassword(String username, String password) { + UserDetail userDetail = new UserDetail("uid_10", username, password); + userDetail.addRole("admin_role"); + return userDetail; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java new file mode 100644 index 0000000000..5bd636ea62 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import java.security.Principal; + +public class CustomPrincipal implements Principal { + + private UserDetail userDetail; + + public CustomPrincipal(UserDetail userDetail) { + this.userDetail = userDetail; + } + + @Override + public String getName() { + return userDetail.getLogin(); + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + ":" + getName(); + } +} diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java new file mode 100644 index 0000000000..68e1df33c8 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java @@ -0,0 +1,38 @@ +package com.baeldung.javaee.security; + +import java.util.ArrayList; +import java.util.List; + +public class UserDetail { + private String uid; + private String login; + private String password; + private List roles = new ArrayList<>(); + //... + + UserDetail(String uid, String login, String password) { + this.uid = uid; + this.login = login; + this.password = password; + } + + public String getUid() { + return uid; + } + + public String getLogin() { + return login; + } + + public String getPassword() { + return password; + } + + public List getRoles() { + return roles; + } + + public void addRole(String role) { + roles.add(role); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html new file mode 100644 index 0000000000..bd7263e0fb --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html new file mode 100644 index 0000000000..3336eb5513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html @@ -0,0 +1,25 @@ + + + + + Title + + +

+ Form-based Authentication +

+
+

+ Username + +

+

+ Password + +

+

+ +

+
+ + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml new file mode 100644 index 0000000000..570b36add5 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + app-auth-form-store-ldap + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + + com.unboundid + unboundid-ldapsdk + 4.0.4 + + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..32adbf1abb --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..6fd9672e8a --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; +import javax.security.enterprise.identitystore.LdapIdentityStoreDefinition; + +@FormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue( + loginPage = "/login.html", + errorPage = "/login-error.html" + ) +) +@LdapIdentityStoreDefinition( + url = "ldap://localhost:10389", + callerBaseDn = "ou=caller,dc=baeldung,dc=com", + groupSearchBase = "ou=group,dc=baeldung,dc=com", + groupSearchFilter = "(&(member=%s)(objectClass=groupOfNames))" +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java new file mode 100644 index 0000000000..e55fe0d2a7 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java @@ -0,0 +1,45 @@ +package com.baeldung.javaee.security; + +import com.unboundid.ldap.listener.InMemoryDirectoryServer; +import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; +import com.unboundid.ldap.listener.InMemoryListenerConfig; +import com.unboundid.ldap.sdk.LDAPException; +import com.unboundid.ldif.LDIFReader; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; + +@WebServlet(value = "/init-ldap", loadOnStartup = 1) +public class LdapSetupServlet extends HttpServlet { + + private InMemoryDirectoryServer inMemoryDirectoryServer; + + @Override + public void init() throws ServletException { + super.init(); + initLdap(); + System.out.println("@@@START_"); + } + + private void initLdap() { + try { + InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=baeldung,dc=com"); + config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", 10389)); + config.setSchema(null); + inMemoryDirectoryServer = new InMemoryDirectoryServer(config); + inMemoryDirectoryServer.importFromLDIF(true, + new LDIFReader(this.getClass().getResourceAsStream("/users.ldif"))); + inMemoryDirectoryServer.startListening(); + } catch (LDAPException e) { + e.printStackTrace(); + } + } + + @Override + public void destroy() { + super.destroy(); + inMemoryDirectoryServer.shutDown(true); + System.out.println("@@@END"); + } +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java new file mode 100644 index 0000000000..9f14cd8817 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + + +@WebServlet("/user") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"})) +public class UserServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif new file mode 100644 index 0000000000..538249aab7 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif @@ -0,0 +1,47 @@ +dn: dc=baeldung,dc=com +objectclass: top +objectclass: dcObject +objectclass: organization +dc: baeldung +o: baeldung + +dn: ou=caller,dc=baeldung,dc=com +objectclass: top +objectclass: organizationalUnit +ou: caller + +dn: ou=group,dc=baeldung,dc=com +objectclass: top +objectclass: organizationalUnit +ou: group + +dn: uid=admin,ou=caller,dc=baeldung,dc=com +objectclass: top +objectclass: uidObject +objectclass: person +uid: admin +cn: Administrator +sn: Admin +userPassword: passadmin + +dn: uid=user,ou=caller,dc=baeldung,dc=com +objectclass: top +objectclass: uidObject +objectclass: person +uid: user +cn: User +sn: User +userPassword: passuser + +dn: cn=admin_role,ou=group,dc=baeldung,dc=com +objectclass: top +objectclass: groupOfNames +cn: admin_role +member: uid=admin,ou=caller,dc=baeldung,dc=com + +dn: cn=user_role,ou=group,dc=baeldung,dc=com +objectclass: top +objectclass: groupOfNames +cn: user_role +member: uid=admin,ou=caller,dc=baeldung,dc=com +member: uid=user,ou=caller,dc=baeldung,dc=com diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html new file mode 100644 index 0000000000..bd7263e0fb --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html new file mode 100644 index 0000000000..3336eb5513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html @@ -0,0 +1,25 @@ + + + + + Title + + +

+ Form-based Authentication +

+
+

+ Username + +

+

+ Password + +

+

+ +

+
+ + \ No newline at end of file diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml new file mode 100644 index 0000000000..cdc288f469 --- /dev/null +++ b/java-ee-8-security-api/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + UTF-8 + + 9080 + 9443 + + 8.0 + 2.3 + 18.0.0.1 + 1.4.197 + + + + app-auth-basic-store-db + app-auth-form-store-ldap + app-auth-custom-form-store-custom + app-auth-custom-no-store + + + + + javax + javaee-web-api + ${javaee-version} + provided + + + + + + + maven-war-plugin + + false + pom.xml + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + + https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/nightly/2018-05-25_1422/openliberty-all-20180525-1300.zip + + + true + project + src/main/liberty/config/server.xml + true + + ${defaultHttpPort} + ${defaultHttpsPort} + + + + + + diff --git a/pom.xml b/pom.xml index 71f2a846fb..f3ef55e8cf 100644 --- a/pom.xml +++ b/pom.xml @@ -260,6 +260,7 @@ java-spi performance-tests twilio + java-ee-8-security-api