Skip to content

Commit fc5ad8e

Browse files
committed
java ee 8 security api
1 parent ce645b6 commit fc5ad8e

File tree

38 files changed

+1143
-0
lines changed

38 files changed

+1143
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<artifactId>app-auth-basic-store-db</artifactId>
8+
<packaging>war</packaging>
9+
10+
<parent>
11+
<groupId>com.baeldung</groupId>
12+
<artifactId>java-ee-8-security-api</artifactId>
13+
<version>1.0-SNAPSHOT</version>
14+
</parent>
15+
16+
<properties>
17+
<h2-version>1.4.197</h2-version>
18+
</properties>
19+
20+
<build>
21+
<plugins>
22+
<plugin>
23+
<groupId>net.wasdev.wlp.maven.plugins</groupId>
24+
<artifactId>liberty-maven-plugin</artifactId>
25+
<executions>
26+
<execution>
27+
<id>install-server</id>
28+
<phase>prepare-package</phase>
29+
<goals>
30+
<goal>install-server</goal>
31+
<goal>create-server</goal>
32+
<goal>install-feature</goal>
33+
</goals>
34+
</execution>
35+
<execution>
36+
<id>install-apps</id>
37+
<phase>package</phase>
38+
<goals>
39+
<goal>install-apps</goal>
40+
</goals>
41+
</execution>
42+
</executions>
43+
</plugin>
44+
<plugin>
45+
<groupId>org.apache.maven.plugins</groupId>
46+
<artifactId>maven-dependency-plugin</artifactId>
47+
<executions>
48+
<execution>
49+
<id>copy</id>
50+
<phase>package</phase>
51+
<goals>
52+
<goal>copy</goal>
53+
</goals>
54+
</execution>
55+
</executions>
56+
<configuration>
57+
<artifactItems>
58+
<artifactItem>
59+
<groupId>com.h2database</groupId>
60+
<artifactId>h2</artifactId>
61+
<version>${h2-version}</version>
62+
<type>jar</type>
63+
<outputDirectory>
64+
${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global
65+
</outputDirectory>
66+
</artifactItem>
67+
</artifactItems>
68+
</configuration>
69+
</plugin>
70+
</plugins>
71+
</build>
72+
</project>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.javaee.security;
2+
3+
import javax.servlet.ServletException;
4+
import javax.servlet.annotation.HttpConstraint;
5+
import javax.servlet.annotation.ServletSecurity;
6+
import javax.servlet.annotation.WebServlet;
7+
import javax.servlet.http.HttpServlet;
8+
import javax.servlet.http.HttpServletRequest;
9+
import javax.servlet.http.HttpServletResponse;
10+
import java.io.IOException;
11+
12+
@WebServlet("/admin")
13+
@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"}))
14+
public class AdminServlet extends HttpServlet {
15+
16+
@Override
17+
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18+
response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
19+
response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
20+
response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
21+
}
22+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.javaee.security;
2+
3+
import javax.enterprise.context.ApplicationScoped;
4+
import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition;
5+
import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition;
6+
import javax.security.enterprise.identitystore.DatabaseIdentityStoreDefinition;
7+
8+
@BasicAuthenticationMechanismDefinition(realmName = "defaultRealm")
9+
@DatabaseIdentityStoreDefinition(
10+
dataSourceLookup = "java:comp/env/jdbc/securityDS",
11+
callerQuery = "select password from users where username = ?",
12+
groupsQuery = "select GROUPNAME from groups where username = ?"
13+
)
14+
@ApplicationScoped
15+
public class AppConfig {
16+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.baeldung.javaee.security;
2+
3+
import javax.annotation.Resource;
4+
import javax.annotation.sql.DataSourceDefinition;
5+
import javax.inject.Inject;
6+
import javax.security.enterprise.identitystore.Pbkdf2PasswordHash;
7+
import javax.servlet.ServletException;
8+
import javax.servlet.annotation.WebServlet;
9+
import javax.servlet.http.HttpServlet;
10+
import javax.sql.DataSource;
11+
import java.sql.Connection;
12+
import java.sql.PreparedStatement;
13+
import java.sql.SQLException;
14+
15+
@DataSourceDefinition(
16+
name = "java:comp/env/jdbc/securityDS",
17+
className = "org.h2.jdbcx.JdbcDataSource",
18+
url = "jdbc:h2:~/securityTest;MODE=Oracle"
19+
)
20+
@WebServlet(value = "/init", loadOnStartup = 0)
21+
public class DatabaseSetupServlet extends HttpServlet {
22+
23+
@Resource(lookup = "java:comp/env/jdbc/securityDS")
24+
private DataSource dataSource;
25+
26+
@Inject
27+
private Pbkdf2PasswordHash passwordHash;
28+
29+
@Override
30+
public void init() throws ServletException {
31+
super.init();
32+
initdb();
33+
}
34+
35+
private void initdb() {
36+
executeUpdate(dataSource, "DROP TABLE IF EXISTS USERS");
37+
executeUpdate(dataSource, "DROP TABLE IF EXISTS GROUPS");
38+
39+
executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS USERS(username VARCHAR(64) PRIMARY KEY, password VARCHAR(255))");
40+
executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS GROUPS(username VARCHAR(64), GROUPNAME VARCHAR(64))");
41+
42+
executeUpdate(dataSource, "INSERT INTO USERS VALUES('admin', '" + passwordHash.generate("passadmin".toCharArray()) + "')");
43+
executeUpdate(dataSource, "INSERT INTO USERS VALUES('user', '" + passwordHash.generate("passuser".toCharArray()) + "')");
44+
45+
executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'admin_role')");
46+
executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'user_role')");
47+
executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('user', 'user_role')");
48+
}
49+
50+
private void executeUpdate(DataSource dataSource, String query) {
51+
try (Connection connection = dataSource.getConnection()) {
52+
try (PreparedStatement statement = connection.prepareStatement(query)) {
53+
statement.executeUpdate();
54+
}
55+
} catch (SQLException e) {
56+
throw new IllegalStateException(e);
57+
}
58+
}
59+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.javaee.security;
2+
3+
import javax.annotation.security.DeclareRoles;
4+
import javax.inject.Inject;
5+
import javax.security.enterprise.SecurityContext;
6+
import javax.servlet.ServletException;
7+
import javax.servlet.annotation.HttpConstraint;
8+
import javax.servlet.annotation.ServletSecurity;
9+
import javax.servlet.annotation.WebServlet;
10+
import javax.servlet.http.HttpServlet;
11+
import javax.servlet.http.HttpServletRequest;
12+
import javax.servlet.http.HttpServletResponse;
13+
import java.io.IOException;
14+
15+
16+
@WebServlet("/user")
17+
@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"}))
18+
public class UserServlet extends HttpServlet {
19+
@Override
20+
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
21+
response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n");
22+
response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n");
23+
response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role"));
24+
}
25+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<server description="OpenLiberty MicroProfile server">
2+
3+
<featureManager>
4+
<feature>webProfile-8.0</feature>
5+
</featureManager>
6+
7+
<httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}"
8+
id="defaultHttpEndpoint" host="*"/>
9+
</server>
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<artifactId>app-auth-custom-form-store-custom</artifactId>
8+
<packaging>war</packaging>
9+
10+
<parent>
11+
<groupId>com.baeldung</groupId>
12+
<artifactId>java-ee-8-security-api</artifactId>
13+
<version>1.0-SNAPSHOT</version>
14+
</parent>
15+
16+
<build>
17+
<plugins>
18+
<plugin>
19+
<groupId>net.wasdev.wlp.maven.plugins</groupId>
20+
<artifactId>liberty-maven-plugin</artifactId>
21+
<executions>
22+
<execution>
23+
<id>install-server</id>
24+
<phase>prepare-package</phase>
25+
<goals>
26+
<goal>install-server</goal>
27+
<goal>create-server</goal>
28+
<goal>install-feature</goal>
29+
</goals>
30+
</execution>
31+
<execution>
32+
<id>install-apps</id>
33+
<phase>package</phase>
34+
<goals>
35+
<goal>install-apps</goal>
36+
</goals>
37+
</execution>
38+
</executions>
39+
</plugin>
40+
</plugins>
41+
</build>
42+
</project>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.javaee.security;
2+
3+
import javax.enterprise.context.ApplicationScoped;
4+
import javax.faces.annotation.FacesConfig;
5+
import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition;
6+
import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
7+
8+
9+
@CustomFormAuthenticationMechanismDefinition(
10+
loginToContinue = @LoginToContinue(
11+
loginPage = "/login.xhtml",
12+
errorPage = "/login-error.html"
13+
)
14+
)
15+
@ApplicationScoped
16+
public class AppConfig {
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.baeldung.javaee.security;
2+
3+
import javax.enterprise.context.ApplicationScoped;
4+
import javax.security.enterprise.credential.UsernamePasswordCredential;
5+
import javax.security.enterprise.identitystore.CredentialValidationResult;
6+
import javax.security.enterprise.identitystore.IdentityStore;
7+
import java.util.*;
8+
9+
import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT;
10+
11+
@ApplicationScoped
12+
public class InMemoryIdentityStore4Authentication implements IdentityStore {
13+
14+
private Map<String, String> users = new HashMap<>();
15+
16+
public InMemoryIdentityStore4Authentication() {
17+
//Init users
18+
// from a file or hardcoded
19+
init();
20+
}
21+
22+
private void init() {
23+
//user1
24+
users.put("user", "pass0");
25+
//user2
26+
users.put("admin", "pass1");
27+
}
28+
29+
@Override
30+
public int priority() {
31+
return 70;
32+
}
33+
34+
@Override
35+
public Set<ValidationType> validationTypes() {
36+
return EnumSet.of(ValidationType.VALIDATE);
37+
}
38+
39+
public CredentialValidationResult validate(UsernamePasswordCredential credential) {
40+
String password = users.get(credential.getCaller());
41+
if (password != null && password.equals(credential.getPasswordAsString())) {
42+
return new CredentialValidationResult(credential.getCaller());
43+
}
44+
return INVALID_RESULT;
45+
}
46+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.baeldung.javaee.security;
2+
3+
import javax.enterprise.context.ApplicationScoped;
4+
import javax.security.enterprise.identitystore.CredentialValidationResult;
5+
import javax.security.enterprise.identitystore.IdentityStore;
6+
import java.util.*;
7+
8+
@ApplicationScoped
9+
class InMemoryIdentityStore4Authorization implements IdentityStore {
10+
11+
private Map<String, List<String>> userRoles = new HashMap<>();
12+
13+
public InMemoryIdentityStore4Authorization() {
14+
//Init users
15+
// from a file or hardcoded
16+
init();
17+
}
18+
19+
private void init() {
20+
//user1
21+
List<String> roles = new ArrayList<>();
22+
roles.add("USER_ROLE");
23+
userRoles.put("user", roles);
24+
//user2
25+
roles = new ArrayList<>();
26+
roles.add("USER_ROLE");
27+
roles.add("ADMIN_ROLE");
28+
userRoles.put("admin", roles);
29+
}
30+
31+
@Override
32+
public int priority() {
33+
return 80;
34+
}
35+
36+
@Override
37+
public Set<ValidationType> validationTypes() {
38+
return EnumSet.of(ValidationType.PROVIDE_GROUPS);
39+
}
40+
41+
@Override
42+
public Set<String> getCallerGroups(CredentialValidationResult validationResult) {
43+
List<String> roles = userRoles.get(validationResult.getCallerPrincipal().getName());
44+
return new HashSet<>(roles);
45+
}
46+
}

0 commit comments

Comments
 (0)