blob: c077eb913edac3ed1213e9dbb2874133df8b61ac [file] [log] [blame]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Apache TomEE</title>
<meta name="description"
content="Apache TomEE is a lightweight, yet powerful, JavaEE Application server with feature rich tooling." />
<meta name="keywords" content="tomee,asf,apache,javaee,jee,shade,embedded,test,junit,applicationcomposer,maven,arquillian" />
<meta name="author" content="Luka Cvetinovic for Codrops" />
<link rel="icon" href="../../../favicon.ico">
<link rel="icon" type="image/png" href="../../../favicon.png">
<meta name="msapplication-TileColor" content="#80287a">
<meta name="theme-color" content="#80287a">
<link rel="stylesheet" type="text/css" href="../../../css/normalize.css">
<link rel="stylesheet" type="text/css" href="../../../css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="../../../css/owl.css">
<link rel="stylesheet" type="text/css" href="../../../css/animate.css">
<link rel="stylesheet" type="text/css" href="../../../fonts/font-awesome-4.1.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../../fonts/eleganticons/et-icons.css">
<link rel="stylesheet" type="text/css" href="../../../css/jqtree.css">
<link rel="stylesheet" type="text/css" href="../../../css/idea.css">
<link rel="stylesheet" type="text/css" href="../../../css/cardio.css">
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2717626-1']);
_gaq.push(['_setDomainName', 'apache.org']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div class="preloader">
<img src="../../../img/loader.gif" alt="Preloader image">
</div>
<nav class="navbar">
<div class="container">
<div class="row"> <div class="col-md-12">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">
<span>
<img src="../../../img/logo-active.png">
</span>
Apache TomEE
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right main-nav">
<li><a href="../../../docs.html">Documentation</a></li>
<li><a href="../../../community/index.html">Community</a></li>
<li><a href="../../../security/security.html">Security</a></li>
<li><a href="../../../download-ng.html">Downloads</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div></div>
</div>
<!-- /.container-fluid -->
</nav>
<div id="main-block" class="container main-block">
<div class="row title">
<div class="col-md-12">
<div class='page-header'>
<h1>MicroProfile JWT</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Este es un ejemplo básico sobre cómo configurar y usar MicroProfile JWT en TomEE.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_ejecute_las_pruebas_para_diferentes_escenarios_relacionados_con_la_validación_jwt">Ejecute las pruebas para diferentes escenarios relacionados con la validación JWT</h2>
<div class="sectionbody">
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">mvn clean test</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_configuración_en_tomee">Configuración en TomEE</h2>
<div class="sectionbody">
<div class="paragraph">
<p>La clase <code>MoviesMPJWTConfigurationProvider.java</code> proporciona a TomEE la configuración
necesaria para la validación JWT.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">package org.superbiz.moviefun.rest;
import org.apache.tomee.microprofile.jwt.config.JWTAuthContextInfo;
import jakarta.enterprise.context.Dependent;
import jakarta.enterprise.inject.Produces;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Optional;
@Dependent
public class MoviesMPJWTConfigurationProvider {
@Produces
Optional&lt;JWTAuthContextInfo&gt; getOptionalContextInfo() throws NoSuchAlgorithmException, InvalidKeySpecException {
JWTAuthContextInfo contextInfo = new JWTAuthContextInfo();
// todo use MP Config to load the configuration
contextInfo.setIssuedBy("https://server.example.com");
final String pemEncoded = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlivFI8qB4D0y2jy0CfEq" +
"Fyy46R0o7S8TKpsx5xbHKoU1VWg6QkQm+ntyIv1p4kE1sPEQO73+HY8+Bzs75XwR" +
"TYL1BmR1w8J5hmjVWjc6R2BTBGAYRPFRhor3kpM6ni2SPmNNhurEAHw7TaqszP5e" +
"UF/F9+KEBWkwVta+PZ37bwqSE4sCb1soZFrVz/UT/LF4tYpuVYt3YbqToZ3pZOZ9" +
"AX2o1GCG3xwOjkc4x0W7ezbQZdC9iftPxVHR8irOijJRRjcPDtA6vPKpzLl6CyYn" +
"sIYPd99ltwxTHjr3npfv/3Lw50bAkbT4HeLFxTx4flEoZLKO/g0bAoV2uqBhkA9x" +
"nQIDAQAB";
byte[] encodedBytes = Base64.getDecoder().decode(pemEncoded);
final X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedBytes);
final KeyFactory kf = KeyFactory.getInstance("RSA");
final RSAPublicKey pk = (RSAPublicKey) kf.generatePublic(spec);
contextInfo.setSignerKey(pk);
return Optional.of(contextInfo);
}
@Produces
JWTAuthContextInfo getContextInfo() throws InvalidKeySpecException, NoSuchAlgorithmException {
return getOptionalContextInfo().get();
}
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_utilizando_microprofile_jwt_en_tomee">Utilizando MicroProfile JWT en TomEE</h2>
<div class="sectionbody">
<div class="paragraph">
<p>El recurso JAX-RS <code>MoviesRest.java</code> contiene varios puntos finales seguros, que se consiguen
mediante el uso de anotación estándar <code>@RolesAllowed</code>. MicroProfile JWT se encarga de realizar
la validación de las solicitudes entrantes con el encabezado <code>Authorization</code>
que proveen un <code>Access Token</code> firmado</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java"> package org.superbiz.moviefun.rest;
import org.superbiz.moviefun.Movie;
import org.superbiz.moviefun.MoviesBean;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import java.util.List;
@Path("cinema")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MoviesRest {
@Inject
private MoviesBean moviesBean;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String status() {
return "ok";
}
@GET
@Path("/movies")
@RolesAllowed({"crud", "read-only"})
public List&lt;Movie&gt; getListOfMovies() {
return moviesBean.getMovies();
}
@GET
@Path("/movies/{id}")
@RolesAllowed({"crud", "read-only"})
public Movie getMovie(@PathParam("id") int id) {
return moviesBean.getMovie(id);
}
@POST
@Path("/movies")
@RolesAllowed("crud")
public void addMovie(Movie newMovie) {
moviesBean.addMovie(newMovie);
}
@DELETE
@Path("/movies/{id}")
@RolesAllowed("crud")
public void deleteMovie(@PathParam("id") int id) {
moviesBean.deleteMovie(id);
}
@PUT
@Path("/movies")
@RolesAllowed("crud")
public void updateMovie(Movie updatedMovie) {
moviesBean.updateMovie(updatedMovie);
}
}
@Inject
@ConfigProperty(name = "java.runtime.version")
private String javaVersion;</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_sobre_la_arquitectura_de_prueba">Sobre la arquitectura de prueba</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Los casos de prueba de este proyecto se construyen con Arquillian.
La configuración arquillian se puede encontrar en
<code>src/test/resources/arquillian.xml</code></p>
</div>
<div class="paragraph">
<p>La clase <code>TokenUtils.java</code> se utiliza durante la prueba para actuar como
un servidor de Autorización que genera <code>Access Tokens</code> basados en los archivos
de configuración <code>privateKey.pem</code>, ` publicKey.pem`, <code>Token1.json</code> y
` Token2 .json`.</p>
</div>
<div class="paragraph">
<p><code>nimbus-jose-jwt</code> es la libreria utilizada para la generación de JWT durante
las pruebas.</p>
</div>
<div class="paragraph">
<p><code>Token1.json</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">{
"iss": "https://server.example.com",
"jti": "a-123",
"sub": "24400320",
"upn": "jdoe@example.com",
"preferred_username": "jdoe",
"aud": "s6BhdRkqt3",
"exp": 1311281970,
"iat": 1311280970,
"auth_time": 1311280969,
"groups": [
"group1",
"group2",
"crud",
"read-only"
]
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>Token2.json</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">{
"iss": "https://server.example.com",
"jti": "a-123",
"sub": "24400320",
"upn": "alice@example.com",
"preferred_username": "alice",
"aud": "s6BhdRkqt3",
"exp": 1311281970,
"iat": 1311280970,
"auth_time": 1311280969,
"groups": [
"read-only"
]
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_escenarios_de_prueba">Escenarios de prueba</h2>
<div class="sectionbody">
<div class="paragraph">
<p><code>MovieTest.java</code> contiene 4 escenarios OAuth2 para diferentes combinaciones de JWT.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">package org.superbiz.moviefun;
import org.apache.cxf.feature.LoggingFeature;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.johnzon.jaxrs.JohnzonProvider;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.superbiz.moviefun.rest.ApplicationConfig;
import org.superbiz.moviefun.rest.MoviesMPJWTConfigurationProvider;
import org.superbiz.moviefun.rest.MoviesRest;
import jakarta.ws.rs.core.Response;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Logger;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertTrue;
@RunWith(Arquillian.class)
public class MoviesTest {
@Deployment(testable = false)
public static WebArchive createDeployment() {
final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(Movie.class, MoviesBean.class, MoviesTest.class)
.addClasses(MoviesRest.class, ApplicationConfig.class)
.addClass(MoviesMPJWTConfigurationProvider.class)
.addAsWebInfResource(new StringAsset("&lt;beans/&gt;"), "beans.xml");
System.out.println(webArchive.toString(true));
return webArchive;
}
@ArquillianResource
private URL base;
private final static Logger LOGGER = Logger.getLogger(MoviesTest.class.getName());
@Test
public void movieRestTest() throws Exception {
final WebClient webClient = WebClient
.create(base.toExternalForm(), singletonList(new JohnzonProvider&lt;&gt;()),
singletonList(new LoggingFeature()), null);
//Testing rest endpoint deployment (GET without security header)
String responsePayload = webClient.reset().path("/rest/cinema/").get(String.class);
LOGGER.info("responsePayload = " + responsePayload);
assertTrue(responsePayload.equalsIgnoreCase("ok"));
//POST (Using token1.json with group of claims: [CRUD])
Movie newMovie = new Movie(1, "David Dobkin", "Wedding Crashers");
Response response = webClient.reset()
.path("/rest/cinema/movies")
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token(1))
.post(newMovie);
LOGGER.info("responseCode = " + response.getStatus());
assertTrue(response.getStatus() == 204);
//GET movies (Using token1.json with group of claims: [read-only])
//This test should be updated to use token2.json once TOMEE- gets resolved.
Collection&lt;? extends Movie&gt; movies = webClient
.reset()
.path("/rest/cinema/movies")
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token(1))
.getCollection(Movie.class);
LOGGER.info(movies.toString());
assertTrue(movies.size() == 1);
//Should return a 403 since POST require group of claims: [crud] but Token 2 has only [read-only].
Movie secondNewMovie = new Movie(2, "Todd Phillips", "Starsky &amp; Hutch");
Response responseWithError = webClient.reset()
.path("/rest/cinema/movies")
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token(2))
.post(secondNewMovie);
LOGGER.info("responseCode = " + responseWithError.getStatus());
assertTrue(responseWithError.getStatus() == 403);
//Should return a 401 since the header Authorization is not part of the POST request.
Response responseWith401Error = webClient.reset()
.path("/rest/cinema/movies")
.header("Content-Type", "application/json")
.post(new Movie());
LOGGER.info("responseCode = " + responseWith401Error.getStatus());
assertTrue(responseWith401Error.getStatus() == 401);
}
private String token(int token_type) throws Exception {
HashMap&lt;String, Long&gt; timeClaims = new HashMap&lt;&gt;();
if (token_type == 1) {
return TokenUtils.generateTokenString("/Token1.json", null, timeClaims);
} else {
return TokenUtils.generateTokenString("/Token2.json", null, timeClaims);
}
}
}</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer>
<div class="container">
<div class="row">
<div class="col-sm-6 text-center-mobile">
<h3 class="white">Be simple. Be certified. Be Tomcat.</h3>
<h5 class="light regular light-white">"A good application in a good server"</h5>
<ul class="social-footer">
<li><a href="https://www.facebook.com/ApacheTomEE/"><i class="fa fa-facebook"></i></a></li>
<li><a href="https://twitter.com/apachetomee"><i class="fa fa-twitter"></i></a></li>
<li><a href="https://plus.google.com/communities/105208241852045684449"><i class="fa fa-google-plus"></i></a></li>
</ul>
</div>
<div class="col-sm-6 text-center-mobile">
<div class="row opening-hours">
<div class="col-sm-3 text-center-mobile">
<h5><a href="../../../latest/docs/" class="white">Documentation</a></h5>
<ul class="list-unstyled">
<li><a href="../../../latest/docs/admin/configuration/index.html" class="regular light-white">How to configure</a></li>
<li><a href="../../../latest/docs/admin/file-layout.html" class="regular light-white">Dir. Structure</a></li>
<li><a href="../../../latest/docs/developer/testing/index.html" class="regular light-white">Testing</a></li>
<li><a href="../../../latest/docs/admin/cluster/index.html" class="regular light-white">Clustering</a></li>
</ul>
</div>
<div class="col-sm-3 text-center-mobile">
<h5><a href="../../../latest/examples/" class="white">Examples</a></h5>
<ul class="list-unstyled">
<li><a href="../../../latest/examples/simple-cdi-interceptor.html" class="regular light-white">CDI Interceptor</a></li>
<li><a href="../../../latest/examples/rest-cdi.html" class="regular light-white">REST with CDI</a></li>
<li><a href="../../../latest/examples/ejb-examples.html" class="regular light-white">EJB</a></li>
<li><a href="../../../latest/examples/jsf-managedBean-and-ejb.html" class="regular light-white">JSF</a></li>
</ul>
</div>
<div class="col-sm-3 text-center-mobile">
<h5><a href="../../../community/index.html" class="white">Community</a></h5>
<ul class="list-unstyled">
<li><a href="../../../community/contributors.html" class="regular light-white">Contributors</a></li>
<li><a href="../../../community/social.html" class="regular light-white">Social</a></li>
<li><a href="../../../community/sources.html" class="regular light-white">Sources</a></li>
</ul>
</div>
<div class="col-sm-3 text-center-mobile">
<h5><a href="../../../security/index.html" class="white">Security</a></h5>
<ul class="list-unstyled">
<li><a href="http://apache.org/security" target="_blank" class="regular light-white">Apache Security</a></li>
<li><a href="http://apache.org/security/projects.html" target="_blank" class="regular light-white">Security Projects</a></li>
<li><a href="http://cve.mitre.org" target="_blank" class="regular light-white">CVE</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="row bottom-footer text-center-mobile">
<div class="col-sm-12 light-white">
<p>Copyright &copy; 1999-2016 The Apache Software Foundation, Licensed under the Apache License, Version 2.0. Apache TomEE, TomEE, Apache, the Apache feather logo, and the Apache TomEE project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners.</p>
</div>
</div>
</div>
</footer>
<!-- Holder for mobile navigation -->
<div class="mobile-nav">
<ul>
<li><a hef="../../../latest/docs/admin/index.html">Administrators</a>
<li><a hef="../../../latest/docs/developer/index.html">Developers</a>
<li><a hef="../../../latest/docs/advanced/index.html">Advanced</a>
<li><a hef="../../../community/index.html">Community</a>
</ul>
<a href="#" class="close-link"><i class="arrow_up"></i></a>
</div>
<!-- Scripts -->
<script src="../../../js/jquery-1.11.1.min.js"></script>
<script src="../../../js/owl.carousel.min.js"></script>
<script src="../../../js/bootstrap.min.js"></script>
<script src="../../../js/wow.min.js"></script>
<script src="../../../js/typewriter.js"></script>
<script src="../../../js/jquery.onepagenav.js"></script>
<script src="../../../js/tree.jquery.js"></script>
<script src="../../../js/highlight.pack.js"></script>
<script src="../../../js/main.js"></script>
</body>
</html>