Skip to content

Commit

Permalink
Enhancements for the JPA-related content
Browse files Browse the repository at this point in the history
Signed-off-by: Michal Maléř <[email protected]>

Adding additional content

Signed-off-by: Michal Maléř <[email protected]>
  • Loading branch information
MichalMaler committed Feb 20, 2023
1 parent 6a8ccf0 commit 33dc8b5
Show file tree
Hide file tree
Showing 4 changed files with 191 additions and 102 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ The following table maps specific authentication requirements to a supported mec

|Username and password |xref:security-basic-authentication-concept.adoc[Basic], xref:security-authentication-mechanisms-concept.adoc#form-auth[Form]

|Bearer access token a| xref:security-oidc-bearer-authentication-concept.adoc[OIDC Bearer], xref:security-jwt.adoc[JWT], xref:security-oauth2.adoc[OAuth2]
|Bearer access token | xref:security-oidc-bearer-authentication-concept.adoc[OIDC Bearer], xref:security-jwt.adoc[JWT], xref:security-oauth2.adoc[OAuth2]

|Single sign-on (SSO) |xref:security-oidc-code-flow-authentication-concept.adoc[OIDC Code Flow], xref:security-authentication-mechanisms-concept.adoc#form-auth[Form]

|Client certificate |xref:security-authentication-mechanisms-concept.adoc#mutual-tls[Mutual TLS (MTLS)]
|Client certificate |xref:security-authentication-mechanisms-concept.adoc#mutual-tls[Mutual TLS (MTLS)]

|WebAuthn |xref:security-webauthn-concept.adoc[WebAuthn]

|Kerberos ticket |link:https://quarkiverse.github.io/quarkiverse-docs/quarkus-kerberos/dev/index.html[Kerberos]
|Kerberos ticket |link:https://quarkiverse.github.io/quarkiverse-docs/quarkus-kerberos/dev/index.html[Kerberos]
|===

See also the <<table>> table featured later in this section.
Expand All @@ -53,10 +53,12 @@ Quarkus Security provides the following built-in authentication support:

You can secure your Quarkus application endpoints with the built-in HTTP Basic authentication mechanism.
For more information, see the following documentation:

* xref:security-basic-authentication-concept.adoc[Basic authentication]
** xref:security-basic-authentication-howto.adoc[Enable Basic authentication]
* xref:security-jpa-concept.adoc[Quarkus Security with JPA]
** xref:security-basic-authentication-tutorial.adoc[Secure a Quarkus application with Basic authentication and JPA]
* xref:security-identity-providers-concept.adoc[Identity providers]
* xref:security-basic-authentication-howto.adoc[Enable Basic authentication]
* xref:security-basic-authentication-tutorial.adoc[Secure a Quarkus application with Basic authentication and JPA]

[[form-auth]]
=== Form-based authentication
Expand Down
95 changes: 3 additions & 92 deletions docs/src/main/asciidoc/security-basic-authentication-tutorial.adoc
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
[id="security-basic-authentication-tutorial"]
= Secure a Quarkus application with Basic authentication and JPA
include::_attributes.adoc[]
:categories: security,getting-started
:categories: security,getting-started,jpa

Secure your Quarkus application endpoints by combining the built-in Quarkus xref:security-basic-authentication-concept.adoc[Basic authentication] with the JPA identity provider to enable role-based access control (RBAC).
The JPA `IdentityProvider` creates a `SecurityIdentity` instance, which is used during user authentication to verify and authorize access requests making your Quarkus application secure.

For more information about JPA, see the xref:security-jpa-concept.adoc[Quarkus Security with JPA].

This tutorial prepares you for implementing more advanced security mechanisms in Quarkus, for example, how to use the OpenID Connect (OIDC) authentication mechanism.

== Prerequisites
Expand Down Expand Up @@ -489,97 +491,6 @@ user

:sectnums!:

// The following section needs to be moved as SMEs confirmed that it does not really fit in the new content here. In the next phase of refactoring, consider moving this section into a dedicated concept/reference topic.

== Quarkus Security JPA information

Now that you have successfully run and tested the security quick start project, you are ready to explore more security features of Quarkus Security and the JPA identity store.

=== Supported model types

- The `@UserDefinition` class must be a JPA entity (with Panache or not).
- The `@Username` and `@Password` field types must be of type `String`.
- The `@Roles` field must either be of type `String` or `Collection<String>` or alternately a `Collection<X>` where `X` is an entity class with one `String` field annotated with the `@RolesValue` annotation.
- Each `String` role element type will be parsed as a comma-separated list of roles.

=== Storing roles in another entity

Use the following sample to store roles inside another entity:

[source,java]
----
@UserDefinition
@Table(name = "test_user")
@Entity
public class User extends PanacheEntity {
@Username
public String name;
@Password
public String pass;
@ManyToMany
@Roles
public List<Role> roles = new ArrayList<>();
}
@Entity
public class Role extends PanacheEntity {
@ManyToMany(mappedBy = "roles")
public List<ExternalRolesUserEntity> users;
@RolesValue
public String role;
}
----

=== Password storage and hashing

By default, passwords are stored and hashed by using https://en.wikipedia.org/wiki/Bcrypt[bcrypt] under the
https://en.wikipedia.org/wiki/Crypt_(C)[Modular Crypt Format] (MCF).

When creating a hashed password, you can use the convenient `String BcryptUtil.bcryptHash(String password)` function, which defaults to creating a random salt and hashing in 10 iterations.
You can also specify the number of iterations and the salt.

NOTE: When you use MCF, you don't need dedicated columns to store the hashing algorithm, the iterations count, or the salt because they are all stored in the hashed value.

You can also store passwords by using a different hashing algorithm, for example, `@Password(value = PasswordType.CUSTOM, provider = CustomPasswordProvider.class)`, as outlined in the following code snippet:

[source,java]
----
@UserDefinition
@Table(name = "test_user")
@Entity
public class CustomPasswordUserEntity {
@Id
@GeneratedValue
public Long id;
@Column(name = "username")
@Username
public String name;
@Column(name = "password")
@Password(value = PasswordType.CUSTOM, provider = CustomPasswordProvider.class)
public String pass;
@Roles
public String role;
}
public class CustomPasswordProvider implements PasswordProvider {
@Override
public Password getPassword(String pass) {
byte[] digest = DatatypeConverter.parseHexBinary(pass);
return SimpleDigestPassword.createRaw(SimpleDigestPassword.ALGORITHM_SIMPLE_DIGEST_SHA_256, digest);
}
}
----

WARNING: In a test environment, you can also store passwords in plain text by using `@Password(PasswordType.CLEAR)`.
For applications running in production, do not store passwords in plain text.

== What's next

Congratulations!
Expand Down
12 changes: 7 additions & 5 deletions docs/src/main/asciidoc/security-identity-providers-concept.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ include::_attributes.adoc[]

In the Quarkus Security framework, identity providers play a key role in authentication and authorization, providing services for storing and verifying user identities.
The JPA `IdentityProvider` creates a `SecurityIdentity` instance used during user authentication to verify and authorize access requests, making your Quarkus application secure.
[[identity-providers]]

[[identity-providers]]
`IdentityProvider` converts the authentication credentials provided by `HttpAuthenticationMechanism` to a `SecurityIdentity` instance.

Some extensions, for example, `OIDC`, `OAuth2`, and `SmallRye JWT` have inline `IdentityProvider` implementations specific to the supported authentication flow.
Expand All @@ -21,8 +21,10 @@ If you use Basic or form-based authentication, you must add an `IdentityProvider

To get started with security in Quarkus, we recommend you combine the Quarkus built-in Basic HTTP authentication with the JPA identity provider to enable role-based access control (RBAC).

* For more information about Basic authentication or form-based authentication, see the following resources:
For more information about Basic authentication, its mechanisms, and related identity providers, see the following resources:

* xref:security-jpa-concept.adoc[Quarkus Security with JPA]
** xref:security-basic-authentication-tutorial.adoc[Secure a Quarkus application with Basic authentication and JPA]
** xref:security-authentication-mechanisms-concept.adoc#form-auth[Form-based authentication]
** xref:security-jdbc.adoc[Using security with JDBC]
** xref:security-ldap.adoc[Using security with an LDAP realm]
* xref:security-authentication-mechanisms-concept.adoc#form-auth[Form-based authentication]
* xref:security-jdbc.adoc[Using security with JDBC]
* xref:security-ldap.adoc[Using security with an LDAP realm]
174 changes: 174 additions & 0 deletions docs/src/main/asciidoc/security-jpa-concept.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
[id="security-jpa-concept"]
= Quarkus Security with JPA
include::_attributes.adoc[]
:categories: security,jpa

JPA is an identity provider, similar to xref:[JDBC], suitable for use with the xref:security-basic-authentication-concept.adoc[Basic] and xref:security-authentication-mechanisms-concept.adoc#form-auth[Form-based] Quarkus security mechanisms, which require a combination of username and password credentials.

The JPA `IdentityProvider` creates a `SecurityIdentity` instance, which is used during user authentication to verify and authorize access requests making your Quarkus application secure.

For an example of practical use of Basic authentication and JPA, see the xref:security-basic-authentication-tutorial.adoc[Secure a Quarkus application with Basic authentication and JPA] tutorial.


== JPA entity specification

Quarkus security offers a JPA integration to collect usernames, passwords, and roles, and store them into JPA database entities.

The following JPA entity specification demonstrates how users' information needs to be stored in a JPA entity and properly mapped so that Quarkus can retrieve this information from a database.


* The `@UserDefinition` annotation must be present on a JPA entity, no matter if link:https://quarkus.io/guides/hibernate-orm-panache[simplified Hibernate ORM with Panache] is used or not.

* The `@Username` and `@Password` field types are always `String`.

* The `@Roles` field must either be `String`, `Collection<String>`, or a `Collection<X>`, where `X` is an entity class with a single `String` field annotated as `@RolesValue`.

* Each `String` role element type is parsed as a comma-separated list of roles.

The following example demonstrates storing security information by adding annotations to the `user` entity:

[source,java]
----
package org.acme.security.jpa;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import io.quarkus.elytron.security.common.BcryptUtil;
import io.quarkus.security.jpa.Password;
import io.quarkus.security.jpa.Roles;
import io.quarkus.security.jpa.UserDefinition;
import io.quarkus.security.jpa.Username;
@Entity
@Table(name = "test_user")
@UserDefinition <1>
public class User extends PanacheEntity {
@Username <2>
public String username;
@Password <3>
public String password;
@Roles <4>
public String role;
/**
* Adds a new user to the database
* @param username the username
* @param password the unencrypted password (it will be encrypted with bcrypt)
* @param role the comma-separated roles
*/
public static void add(String username, String password, String role) { <5>
User user = new User();
user.username = username;
user.password = BcryptUtil.bcryptHash(password);
user.role = role;
user.persist();
}
}
----

The `security-jpa` extension initializes only if a single entity is annotated with `@UserDefinition`.

<1> The `@UserDefinition` annotation must be present on a single entity, either a regular Hibernate ORM entity or a Hibernate ORM with a Panache entity.
<2> Indicates the field used for the username.
<3> Indicates the field used for the password.
By default, it uses bcrypt-hashed passwords, and you can configure it to use plain text or custom passwords.
<4> This indicates the comma-separated list of roles added to the target principal representation attributes.
<5> This method allows us to add users while hashing passwords with the proper `bcrypt` hash.


== JPA entity as storage of roles

Use the following example to store roles inside another JPA entity:

[source,java]
----
@UserDefinition
@Table(name = "test_user")
@Entity
public class User extends PanacheEntity {
@Username
public String name;
@Password
public String pass;
@ManyToMany
@Roles
public List<Role> roles = new ArrayList<>();
}
@Entity
public class Role extends PanacheEntity {
@ManyToMany(mappedBy = "roles")
public List<ExternalRolesUserEntity> users;
@RolesValue
public String role;
}
----

== Password storage and hashing

Regarding password storage and hashing management from a developer perspective, you can decide if you want to keep the settings as it is and use the Quarkus default or hash passwords manually.

With the default option, passwords are stored and hashed with https://en.wikipedia.org/wiki/Bcrypt[bcrypt] under the
https://en.wikipedia.org/wiki/Crypt_(C)[Modular Crypt Format] (MCF).
While using MCF, the hashing algorithm, iteration count, and salt are stored as a part of the hashed value.
As such, we do not need dedicated columns to keep them.

[NOTE]
====
In cryptography, a salt is a name for random data used as an additional input to a one-way function that hashes data, a password, or a passphrase.
====

For manual password hashing, create a class that implements the `CustomPasswordProvider`as shown in the example below.

This is an example of providing a custom password provider using the SHA256 hashing algorithm.

[source,java]
----
@UserDefinition
@Table(name = "test_user")
@Entity
public class CustomPasswordUserEntity {
@Id
@GeneratedValue
public Long id;
@Column(name = "username")
@Username
public String name;
@Column(name = "password")
@Password(value = PasswordType.CUSTOM, provider = CustomPasswordProvider.class)
public String pass;
@Roles
public String role;
}
public class CustomPasswordProvider implements PasswordProvider {
@Override
public Password getPassword(String pass) {
byte[] digest = DatatypeConverter.parseHexBinary(pass);
return SimpleDigestPassword.createRaw(SimpleDigestPassword.ALGORITHM_SIMPLE_DIGEST_SHA_256, digest);
}
}
----

[TIP]
====
For quick creation of a hashed password, use `String BcryptUtil.bcryptHash(String password)`, which defaults to creating a random salt and hashing in ten iterations.
This method also allows specifying the desired amount of iterations and the salt used.
====

[WARNING]
====
Never store passwords as a plain text for applications already running in production.
However, it is possible to store passwords as a plain text with the `@Password(PasswordType.CLEAR)` annotation when operating in a test environment.
====

0 comments on commit 33dc8b5

Please sign in to comment.