Skip to content

Commit

Permalink
Merge pull request quarkusio#31297 from MichalMaler/QDOCS-99-Revampin…
Browse files Browse the repository at this point in the history
…g-the-JPA-section

Enhancements for the JPA-related content
  • Loading branch information
sberyozkin authored Feb 20, 2023
2 parents 176030c + bc7c502 commit b88d236
Show file tree
Hide file tree
Showing 8 changed files with 205 additions and 109 deletions.
2 changes: 1 addition & 1 deletion docs/src/main/asciidoc/amazon-lambda-http.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ quarkus.lambda-http.cognito-claim-matcher=[^\[\] \t]+

The default support for AWS security only maps the principal name to Quarkus security
APIs and does nothing to map claims or roles or permissions. You have full control on
how security metadata in the lambda HTTP event is mapped to Quarkus security APIs using
how security metadata in the lambda HTTP event is mapped to Quarkus Security APIs using
implementations of the `io.quarkus.amazon.lambda.http.LambdaIdentityProvider`
interface. By implementing this interface, you can do things like define role mappings for your principal
or publish additional attributes provided by IAM or Cognito or your Custom Lambda security integration.
Expand Down
4 changes: 2 additions & 2 deletions docs/src/main/asciidoc/rest-data-panache.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ public interface PeopleResource extends PanacheEntityResource<Person, Long> {

* `exposed` - whether resource could be exposed. A global resource property that can be overridden for each method. Default is `true`.
* `path` - resource base path. Default path is a hyphenated lowercase resource name without a suffix of `resource` or `controller`.
* `rolesAllowed` - List of the security roles permitted to access the resources. It needs a Quarkus security extension to be present, otherwise it will be ignored. Default is empty.
* `rolesAllowed` - List of the security roles permitted to access the resources. It needs a Quarkus Security extension to be present, otherwise it will be ignored. Default is empty.
* `paged` - whether collection responses should be paged or not.
First, last, previous and next page URIs are included in the response headers if they exist.
Request page index and size are taken from the `page` and `size` query parameters that default to `0` and `20` respectively.
Expand All @@ -322,7 +322,7 @@ Default is `false`.

* `exposed` - does not expose a particular HTTP verb when set to `false`. Default is `true`.
* `path` - operation path (this is appended to the resource base path). Default is an empty string.
* `rolesAllowed` - List of the security roles permitted to access this operation. It needs a Quarkus security extension to be present, otherwise it will be ignored. Default is empty.
* `rolesAllowed` - List of the security roles permitted to access this operation. It needs a Quarkus Security extension to be present, otherwise it will be ignored. Default is empty.

== Adding additional methods to the generated resource

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,19 @@ The following table maps specific authentication requirements to a supported mec
[width=80%]
[source, adoc]
|===
|Authentication requirement | Authentication mechanism
|Authentication requirement |Authentication mechanism

|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
Expand Up @@ -6,6 +6,8 @@ include::_attributes.adoc[]
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 @@ -41,7 +43,7 @@ You can find the solution in the `security-jpa-quickstart` {quickstarts-tree-url

== Create a Maven project

For Quarkus security to be able to map your security source to JPA entities, ensure that the Maven project that is used in this tutorial includes the `security-jpa` extension.
For Quarkus Security to be able to map your security source to JPA entities, ensure that the Maven project that is used in this tutorial includes the `security-jpa` extension.
You can either create a new Maven project with the `security-jpa` extension or you can add the extension to an existing Maven project.

* To create the Maven project, use the following command:
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
2 changes: 1 addition & 1 deletion docs/src/main/asciidoc/security-customization.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ include::_attributes.adoc[]

== Quarkus Security Dependency

`io.quarkus:quarkus-security` module contains the core Quarkus security classes.
`io.quarkus:quarkus-security` module contains the core Quarkus Security classes.

In most cases, it does not have to be added directly to your project's build file as it is already provided by all the security extensions.
However, if you need to write your own custom security code (for example, register a <<jaxrs-security-context, Custom JAX-RS SecurityContext>>) or use <<bouncy-castle, BouncyCastle>> libraries, then please make sure it is included:
Expand Down
13 changes: 8 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,11 @@ 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]
* xref:security-overview-concept.adoc[Quarkus Security overview]
180 changes: 180 additions & 0 deletions docs/src/main/asciidoc/security-jpa-concept.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
[id="security-jpa-concept"]
= Quarkus Security with JPA
include::_attributes.adoc[]
:categories: security

JPA is an identity provider, similar to xref:security-jdbc.adoc[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, regardless of whether 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, `security-jpa` uses bcrypt-hashed passwords, or you can configure plain text or custom passwords instead.
<4> This indicates the comma-separated list of roles added to the target principal representation attributes.
<5> This method allows you 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

When developing applications with Quarkus, you can decide how to manage password storage and hashing. You can choose to keep the default password and hashing settings of Quarkus, or you can 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.

The following snippet shows how to set a custom password provider that uses 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]
====
For applications running in a production environment, do not store passwords as plain text.
However, it is possible to store passwords as plain text with the `@Password(PasswordType.CLEAR)` annotation when operating in a test environment.
====

== References

* 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-overview-concept.adoc[Quarkus Security overview]
Loading

0 comments on commit b88d236

Please sign in to comment.