OpenLiberty / guide-security-intro

An introductory guide on how to secure a web application through authentication and authorization using Java EE 8 Security API: https://openliberty.io/guides/security-intro.html
Other
8 stars 11 forks source link

// Copyright (c) 2017, 2023 IBM Corporation and others. // Licensed under Creative Commons Attribution-NoDerivatives // 4.0 International (CC BY-ND 4.0) // https://creativecommons.org/licenses/by-nd/4.0/ // // Contributors: // IBM Corporation :guide-author: Open Liberty :page-layout: guide-multipane :projectid: security-intro :page-duration: 15 minutes :page-releasedate: 2018-10-19 :page-description: Learn how to secure a web application through authentication and authorization. :page-tags: ['Jakarta EE', 'Security'] :page-related-guides: ['microprofile-jwt', 'cdi-intro'] :page-guide-category: none :page-permalink: /guides/{projectid} :common-includes: https://raw.githubusercontent.com/OpenLiberty/guides-common/prod :source-highlighter: prettify :page-seo-title: Securing a Java web application using the Jakarta EE Security API :page-seo-description: A getting started tutorial with examples of how to secure a Java EE or Jakarta EE web application through authentication and authorization with a user registry by using the Jakarta EE Security API. :guide-author: Open Liberty = Securing a web application

[.hidden] NOTE: This repository contains the guide documentation source. To view the guide in published form, view it on the https://openliberty.io/guides/{projectid}.html[Open Liberty website^].

Learn how to secure a web application through authentication and authorization.

// ================================================================================================= // What you'll learn // =================================================================================================

== What you'll learn

You'll learn how to secure a web application by performing authentication and authorization using Jakarta EE Security. Authentication confirms the identity of the user by verifying a user's credentials while authorization determines whether a user has access to restricted resources.

Jakarta EE Security provides capability to configure the basic authentication, form authentication, or custom form authentication mechanism by using annotations in servlets. It also provides the SecurityContext API for programmatic security checks in application code.

You’ll implement form authentication for a simple web front end. You'll also learn to specify security constraints for a servlet and use the SecurityContext API to determine the role of a logged-in user.

// ================================================================================================= // Getting Started // ================================================================================================= [role="command"] include::{common-includes}/gitclone.adoc[]

[role='command'] include::{common-includes}/twyb-intro.adoc[]

The finished application is secured with form authentication.

ifndef::cloud-hosted[] Navigate your browser to this URL to access the application: http://localhost:9080[http://localhost:9080^] endif::[]

ifdef::cloud-hosted[] Click the following button to visit the application:

::startApplication{port="9080" display="external" name="Visit application" route="/"} endif::[]

The application automatically switches from an HTTP connection to a secure HTTPS connection and forwards you to a login page. If the browser gives you a certificate warning, it's because the Open Liberty instance created a self-signed SSL certificate by default. You can follow your browser's provided instructions to accept the certificate and continue.

Sign in to the application with one of the following user credentials from the user registry, which are provided to you:

[cols="<35, ^150, ^150, ^150"] |=== | Username | Password | Role | Group | alice | alicepwd | user | Employee | bob | bobpwd | admin, user | Manager, Employee | carl | carlpwd | admin, user | TeamLead, Employee | dave | davepwd | N/A | PartTime |===

Notice that when you sign in as Bob or Carl, the browser redirects to the admin page and you can view their names and roles. When you sign in as Alice, you can only view Alice's name. When you sign in as Dave, you are blocked and see an Error 403: Authorization failed message because Dave doesn't have a role that is supported by the application.

[role='command'] include::{common-includes}/twyb-end.adoc[]

// ================================================================================================= // Adding authentication and authorization // =================================================================================================

== Adding authentication and authorization

For this application, users are asked to log in with a form when they access the application. Users are authenticated and depending on their roles, they are redirected to the pages that they are authorized to access. If authentication or authorization fails, users are sent to an error page. The application supports two roles, admin and user.

Navigate to the start directory to begin. ifdef::cloud-hosted[]

cd /home/project/guide-security-intro/start

endif::[]

[role='command'] include::{common-includes}/devmode-lmp33-start.adoc[]

[role="code_command hotspot", subs="quotes"]

Create the HomeServlet class.

src/main/java/io/openliberty/guides/ui/HomeServlet.java

HomeServlet.java [source, java, linenums, role='code_column hide_tags=copyright,javaDoc1,javaDoc2']

include::finish/src/main/java/io/openliberty/guides/ui/HomeServlet.java[]

The [hotspot=HomeServlet file=0]HomeServlet servlet is the entry point of the application. To enable form authentication for the [hotspot=HomeServlet file=0]HomeServlet class, define the [hotspot=AuthenticationMechanism file=0]@FormAuthenticationMechanismDefinition annotation and set its [hotspot=loginToContinue file=0]loginToContinue attribute with a [hotspot=loginToContinue file=0]@LoginToContinue annotation. This [hotspot=AuthenticationMechanism file=0]@FormAuthenticationMechanismDefinition annotation defines [hotspot=loginPage file=0]welcome.html as the login page and [hotspot=errorPage file=0]error.html as the error page.

The [hotspot=loginPage file=0]welcome.html page implements the login form, and the [hotspot=errorPage file=0]error.html page implements the error page. Both pages are provided for you under the src/main/webapp directory. The login form in the [hotspot=loginPage file=0]welcome.html page uses the j_security_check action, which is defined by Jakarta EE and available by default.

Authorization determines whether a user can access a resource. To restrict access to authenticated users with user and admin roles, define the [hotspot=ServletSecurity file=0]@ServletSecurity annotation with the [hotspot=HttpConstraint file=0]@HttpConstraint annotation and set the [hotspot=HttpConstraint file=0]rolesAllowed attribute to these two roles.

The [hotspot=TransportGuarantee file=0]transportGuarantee attribute defines the constraint on the traffic between the client and the application. Set it to [hotspot=TransportGuarantee file=0]CONFIDENTIAL to enforce that all user data must be encrypted, which is why an HTTP connection from a browser switches to HTTPS.

The SecurityContext interface provides programmatic access to the Jakarta EE Security API. Inject a SecurityContext instance into the [hotspot=HomeServlet file=0]HomeServlet class. The [hotspot=doGet file=0]doGet() method uses the [hotspot=CallerInRole file=0]isCallerInRole() method from the SecurityContext API to check a user's role and then forwards the response to the appropriate page.

The [hotspot=webxmlsecurity file=1]src/main/webapp/WEB-INF/web.xml file contains the rest of the security declaration for the application.

web.xml [source, xml, linenums, role='code_column hide_tags=copyright']

include::finish/src/main/webapp/WEB-INF/web.xml[]

ifdef::cloud-hosted[] ::openFile{path="/home/project/guide-security-intro/start/src/main/webapp/WEB-INF/web.xml"} endif::[]

The [hotspot=security-role file=1]security-role elements define the roles that are supported by the application, which are [hotspot=role-name-user file=1]user and [hotspot=role-name-admin file=1]admin. The [hotspot=security-constraint file=1]security-constraint elements specify that JSF resources like the [hotspot=url-pattern-user file=1]user.jsf and [hotspot=url-pattern-admin file=1]admin.jsf pages can be accessed only by users with [hotspot=role-name-user file=1]user and [hotspot=role-name-admin file=1]admin roles.

// ================================================================================================= // Configuring the user registry // =================================================================================================

== Configuring the user registry

User registries store user account information, such as username and password, for use by applications to perform security-related operations. Typically, Open Liberty would be configured to use an external registry like a Lightweight Directory Access Protocol (LDAP) registry. Applications would access information in the registry for authentication and authorization by using APIs like the Jakarta EE Security API.

Open Liberty provides an easy-to-use basic user registry for developers, which you will configure.

[role="code_command hotspot", subs="quotes"]

Create the userRegistry configuration file.

src/main/liberty/config/userRegistry.xml

userRegistry.xml [source, xml, linenums, role='code_column']

include::finish/src/main/liberty/config/userRegistry.xml[]

The registry has four users, [hotspot=user-bob file=0]bob, [hotspot=user-alice file=0]alice, [hotspot=user-carl file=0]carl, and [hotspot=user-dave file=0]dave. It also has four groups: [hotspot=group-name-Manager file=0]Manager, [hotspot=group-name-TeamLead file=0]TeamLead, [hotspot=group-name-Employee file=0]Employee, and [hotspot=group-name-PartTime file=0]PartTime. Each user belongs to one or more groups.

It is not recommended to store passwords in plain text. The passwords in the [hotspot file=0]userRegistry.xml file are encoded by using the Liberty securityUtility command with XOR encoding.

server.xml [source, xml, linenums, role='code_column']

include::finish/src/main/liberty/config/server.xml[]

ifdef::cloud-hosted[] See the Liberty server.xml configuration file.

::openFile{path="/home/project/guide-security-intro/start/src/main/liberty/config/server.xml"} endif::[]

Use the [hotspot=location file=1]include element to add the basic user registry configuration to your Liberty configuration. Open Liberty includes configuration information from the specified XML file in its configuration.

The [hotspot file=1]server.xml configuration file contains the security configuration of the Liberty under the [hotspot=application-bnd file=1]application-bnd element. Use the [hotspot=Security file=1]security-role and [hotspot=Group hotspot=group-name-Employee file=1]group elements to map the groups in the [hotspot file=0]userRegistry.xml file to the appropriate user roles supported by the application for proper user authorization. The [hotspot=group-name-Manager file=1]Manager and [hotspot=group-name-TeamLead file=1]TeamLead groups are mapped to the [hotspot=security-role-admin file=1]admin role while the [hotspot=group-name-Employee file=1]Employee group is mapped to the [hotspot=security-role-user file=1]user role.

// ================================================================================================= // Running the application // ================================================================================================= [role="command"] include::{common-includes}/devmode-build.adoc[]

HomeServlet.java [source, java, linenums, role='code_column hide_tags=copyright,javaDoc1,javaDoc2']

include::finish/src/main/java/io/openliberty/guides/ui/HomeServlet.java[]

ifndef::cloud-hosted[] Point your browser to the http://localhost:9080[http://localhost:9080^] URL. endif::[]

ifdef::cloud-hosted[] Click the following button to visit the application:

::startApplication{port="9080" display="external" name="Visit application" route="/"} endif::[]

As you can see, the browser gets automatically redirected from an HTTP connection to an HTTPS connection because the transport guarantee is defined in the [hotspot file=0]HomeServlet class.

You will see a login form because form authentication is implemented and configured. Sign in to the application by using one of the credentials from the following table. The credentials are defined in the configured user registry.

[cols="<35, ^150, ^150, ^150"] |=== | Username | Password | Role | Group | alice | alicepwd | user | Employee | bob | bobpwd | admin, user | Manager, Employee | carl | carlpwd | admin, user | TeamLead, Employee | dave | davepwd | N/A | PartTime |===

Notice that when you sign in as Bob or Carl, the browser redirects to the admin page and you can view their names and roles. When you sign in as Alice, you can only view Alice's name. When you sign in as Dave, you are blocked and see an Error 403: Authorization failed message because Dave doesn't have a role that is supported by the application.

// ================================================================================================= // Testing the application // =================================================================================================

== Testing the application

Write the [hotspot file=0]SecurityIT class to test the authentication and authorization of the application.

[role="code_command hotspot", subs="quotes"]

Create the SecurityIT class.

src/test/java/it/io/openliberty/guides/security/SecurityIT.java

SecurityIT.java [source, java, linenums, role='code_column hide_tags=copyright']

include::finish/src/test/java/it/io/openliberty/guides/security/SecurityIT.java[]

The [hotspot=testAuthenticationFail]testAuthenticationFail() method tests an invalid user authentication while the [hotspot=testAuthorizationFail]testAuthorizationFail() method tests unauthorized access to the application.

The [hotspot=testAuthorizationForAdmin]testAuthorizationForAdmin() and [hotspot=testAuthorizationForUser]testAuthorizationForUser() methods verify that users with admin or user roles are properly authenticated and can access authorized resource.

[role='command'] include::{common-includes}/devmode-test.adoc[]

You see the following output:

[source, role="no_copy"]


T E S T S

Running it.io.openliberty.guides.security.SecurityIT Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.78 sec - in it.io.openliberty.guides.security.SecurityIT

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0


[role='command'] include::{common-includes}/devmode-quit-ctrlc.adoc[]

// ================================================================================================= // Great work! You're done! // =================================================================================================

== Great work! You're done!

You learned how to use Jakarta EE Security in Open Liberty to authenticate and authorize users to secure your web application.

Next, you can try the related https://openliberty.io/guides/microprofile-jwt.html[MicroProfile JWT^] guide. It demonstrates technologies to secure backend services.

include::{common-includes}/attribution.adoc[subs="attributes"]