Modified: websites/production/cxf/content/docs/jax-rs-multiparts.html ============================================================================== --- websites/production/cxf/content/docs/jax-rs-multiparts.html (original) +++ websites/production/cxf/content/docs/jax-rs-multiparts.html Wed Sep 13 15:05:52 2017 @@ -32,8 +32,8 @@ <link type="text/css" rel="stylesheet" href="/resources/highlighter/styles/shThemeCXF.css"> <script src='/resources/highlighter/scripts/shCore.js'></script> -<script src='/resources/highlighter/scripts/shBrushJava.js'></script> <script src='/resources/highlighter/scripts/shBrushXml.js'></script> +<script src='/resources/highlighter/scripts/shBrushJava.js'></script> <script> SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); @@ -121,18 +121,18 @@ Apache CXF -- JAX-RS Multiparts  </p><p> </p><p> </p><p> </p><p> </p><p><style type="text/css">/*<![CDATA[*/ -div.rbtoc1505311201473 {padding: 0px;} -div.rbtoc1505311201473 ul {list-style: disc;margin-left: 0px;} -div.rbtoc1505311201473 li {margin-left: 0px;padding-left: 0px;} +div.rbtoc1505314871519 {padding: 0px;} +div.rbtoc1505314871519 ul {list-style: disc;margin-left: 0px;} +div.rbtoc1505314871519 li {margin-left: 0px;padding-left: 0px;} -/*]]>*/</style></p><div class="toc-macro rbtoc1505311201473"> +/*]]>*/</style></p><div class="toc-macro rbtoc1505314871519"> <ul class="toc-indentation"><li><a shape="rect" href="#JAX-RSMultiparts-Readingattachments">Reading attachments</a> <ul class="toc-indentation"><li><a shape="rect" href="#JAX-RSMultiparts-MultipartannotationandOptionalattachments">Multipart annotation and Optional attachments</a></li></ul> </li><li><a shape="rect" href="#JAX-RSMultiparts-Writingattachments">Writing attachments</a></li><li><a shape="rect" href="#JAX-RSMultiparts-UploadingfileswithClientAPI">Uploading files with Client API</a></li><li><a shape="rect" href="#JAX-RSMultiparts-Readinglargeattachments">Reading large attachments</a> <ul class="toc-indentation"><li><a shape="rect" href="#JAX-RSMultiparts-Formsandmultiparts">Forms and multiparts</a></li><li><a shape="rect" href="#JAX-RSMultiparts-Content-DispositionUTF-8filenames">Content-Disposition UTF-8 file names</a></li></ul> </li><li><a shape="rect" href="#JAX-RSMultiparts-XOPsupport">XOP support</a></li><li><a shape="rect" href="#JAX-RSMultiparts-MultipartFilters">Multipart Filters</a></li><li><a shape="rect" href="#JAX-RSMultiparts-SigningMultiparts">Signing Multiparts</a></li><li><a shape="rect" href="#JAX-RSMultiparts-NoteaboutStruts">Note about Struts</a></li></ul> </div><h1 id="JAX-RSMultiparts-Readingattachments">Reading attachments</h1><p>Individual parts can be mapped to StreamSource, InputStream, DataSource or custom Java types for which message body readers are available.</p><p>For example:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST @Path("/books/jaxbjson") @Produces("text/xml") public Response addBookJaxbJson( @@ -142,19 +142,19 @@ public Response addBookJaxbJson( } </pre> </div></div><p>Note that in this example it's expected that the root part named 'rootPart' is a text-xml Book representation, while a part named 'book2' is a Book JSON sequence.</p><p>All attachment parts can be accessed as a list of <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/Attachment.java">Attachment</a> with Attachment making it easy to deal with a given part:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST public void addAttachments(List<Attachment> atts) throws Exception { } </pre> </div></div><p>For example, Attachment class can be used to get to a <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/ContentDisposition.java">Content-Disposition</a> header, when dealing with the form submission of files.</p><p>Similarly, the whole request body can be represented as a <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/MultipartBody.java">MultipartBody</a>:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST public void addAttachments(MultipartBody body) throws Exception { body.getAllAtachments(); body.getRootAttachment(); } </pre> </div></div><p>When handling complex multipart/form-data submissions (such as those containing files) MultipartBody (and Attachment) need to be used directly. In simpler cases, when every form part can be captured by a String, the following code will suffice:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST @Consumes("multipart/form-data") public void addForm1(@FormParam("name") String title, @FormParam("id") Long id) throws Exception { } @@ -170,7 +170,7 @@ public void addForm3(MultivaluedMap<S } </pre> </div></div><p>When working with either List of Attachments or MultipartBody, one may want to process the individual parts with the help of some custom procedures. Starting from CXF 2.3.0 it is also possible to do the following:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST public void addAttachments(MultipartBody body) throws Exception { Book book = body.getAttachmentObject("bookPart", Book.class); } @@ -184,7 +184,7 @@ public void addAttachments(List<Attac </pre> </div></div><p>When a user code has <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/MessageContext.java">MessageContext</a> injected, <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/multipart/AttachmentUtils.java">AttachmentUtils</a> can also be used by the application code.</p><p>Please see these <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/MultipartStore.java">test resource class</a> and <a shape="rect" class="external-link" href="http://sberyozkin.blogspot.com/2009/02/multiparts-in-cxf-jaxrs.html" rel="nofollow">blog entry</a> for more examples.</p><h2 id="JAX-RSMultiparts-MultipartannotationandOptionalattachments">Multipart annotation and Optional attachments</h2><p>When you write the code lik e this</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST @Path("/books/jaxbjson") @Produces("text/xml") public Response addBookJaxbJson( @@ -192,7 +192,7 @@ public Response addBookJaxbJson( @Multipart("book2") Book b2) {} </pre> </div></div><p>the runtime will return a 400 status if either "rootPart" or "book2" parts can not be found in the multipart payload.<br clear="none"> Starting from 2.5.1 it is possible to request the runtime to report a null value in case of missing parts:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST @Path("/books/jaxbjson") @Produces("text/xml") public Response addBookJaxbJson( @@ -200,7 +200,7 @@ public Response addBookJaxbJson( @Multipart(value = "book2", required = false) Book b2) {} </pre> </div></div><p>The above code requires the "rootPart" part be available and can handle the case where the "book2" part is missing.</p><h1 id="JAX-RSMultiparts-Writingattachments">Writing attachments</h1><p>Starting from 2.2.4 it is also possible to write attachments to the output stream, both on the client and server sides.</p><p>On the server side it is sufficient to update the @Produces value for a given method:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">public class Resource { +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">public class Resource { private List<Book> books; @Produces("multipart/mixed;type=text/xml") public List<Book> getBooksAsMultipart() { @@ -214,7 +214,7 @@ public Response addBookJaxbJson( } </pre> </div></div><p>Note that a 'type' parameter of the 'multipart/mixed' media type indicates that all parts in the multiparts response should have a Content-Type header set to 'text/xml' for both getBooksAsMultipart() and getBookAsMultipart() method responses. The getBooksAsMultipart() response will have 3 parts, the first part will have its Content-ID header set to "root.mess...@cxf.apache.org", the next parts will have '1' and '2' ids. The getBookAsMultipart() response will have a single part only with its Content-ID header set to "root.mess...@cxf.apache.org".</p><p>When returning mixed multiparts containing objects of different types, you can either return a Map with the media type string value to Object pairs or MultipartBody:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">public class Resource { +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">public class Resource { private List<Book> books; @Produces("multipart/mixed") public Map<String, Object> getBooks() { @@ -236,7 +236,7 @@ public Response addBookJaxbJson( } </pre> </div></div><p>Similarly to the method returning a list in a previous code fragment, getBooks() will have the response serialized as multiparts, where the first part will have its Content-ID header set to "root.mess...@cxf.apache.org", the next parts will have ids like '1', '2', etc.</p><p>In getBooks2() one can control the content ids of individual parts.</p><p>You can also control the contentId and the media type of the root attachment by using a Multipart annotation:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">public class Resource { +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">public class Resource { @Produces("multipart/form-data") @Multipart(value = "root", type = "application/octet-stream") public File testGetImageFromForm() { @@ -245,7 +245,7 @@ public Response addBookJaxbJson( } </pre> </div></div><p>One can also have lists or maps of DataHandler, DataSource, Attachment, byte arrays or InputStreams handled as multiparts.</p><p>On the client side multiparts can be written the same way. For example:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">WebClient client = WebClient.create("http://books"); +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">WebClient client = WebClient.create("http://books"); client.type("multipart/mixed").accept("multipart/mixed"); List<Attachment> atts = new LinkedList<Attachment>(); atts.add(new Attachment("root", "application/json", new JSONBook())); @@ -253,7 +253,7 @@ atts.add(new Attachment("image", "applic List<Attachment> atts = client.postAndGetCollection(atts, Attachment.class); </pre> </div></div><p>Note a new WebClient.postAndGetCollection which can be used for a type-safe retrieval of collections. A similar WebClient.getCollection has also been added.</p><p>When using proxies, a Multipart annotation attached to a method parameter can also be used to set the root contentId and media type. Proxies do not support at the moment multiple method parameters annotated with Multipart (as opposed to the server side) but only a single multipart parameter:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">public class Resource { +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">public class Resource { @Produces("multipart/mixed") @Consumes("multipart/form-data") @Multipart(value = "root", type = "application/octet-stream") @@ -261,7 +261,7 @@ List<Attachment> atts = client.pos } </pre> </div></div><p>A method-level Multipart annotation will affect the writing on the server side and the reading on the client side. A parameter-level Multipart annotation will affect writing on the client (proxy) side and reading on the server side. You don't have to use Multipart annotations.</p><h1 id="JAX-RSMultiparts-UploadingfileswithClientAPI">Uploading files with Client API</h1><p>At the moment the only way to upload a file is to use a MultipartBody, Attachment or File:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">WebClient client = WebClient.create("http://books");t +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">WebClient client = WebClient.create("http://books");t client.type("multipart/form-data"); ContentDisposition cd = new ContentDisposition("attachment;filename=image.jpg"); Attachment att = new Attachment("root", imageInputStream, cd); @@ -275,7 +275,7 @@ client.post(getClass().getResource("imag </pre> </div></div><p>Using File provides a simpler way as the runtime can figure out how to create a ContentDisposition from a File.</p><h1 id="JAX-RSMultiparts-Readinglargeattachments">Reading large attachments</h1><p>One can use the following properties to set up folder, memory threshold and max size (from CXF 2.4.4 and 2.5) values when dealing with large attachments:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;"><beans> +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;"><beans> <jaxrs:server id="bookstore1"> <jaxrs:properties> <entry key="attachment-directory" value="/temp/bookstore1"/> @@ -288,20 +288,20 @@ client.post(getClass().getResource("imag </beans> </pre> </div></div><p>Note that such properties can be set up on a per-endpoint basis. Alternatively you can set "attachmentDirectory", "attachmentThreshold" and "attachmentMaxSize" properties directly on either org.apache.cxf.jaxrs.provider.MultipartProvider or, when dealing with multipart/form-data payloads, org.apache.cxf.jaxrs.provider.FormEncodingProvider.</p><p>Alternatively, you might want to set the following system properties which will apply to all endpoints:</p><p>> -Dorg.apache.cxf.io.CachedOutputStream.Threshold=102400 <br clear="none"> and<br clear="none"> > -Dorg.apache.cxf.io.CachedOutputStream.OutputDirectory=/temp</p><p>Starting from CXF 2.5.0 and 2.4.4:<br clear="none"> > -Dorg.apache.cxf.io.CachedOutputStream.MaxSize=10000000</p><p>Note that if a given attachment exceeds the maximum size property (default is no-limit) then HTTP 413 status will be returned.</p><h2 id="JAX-RSMultiparts-Formsandmultiparts">Forms and multiparts</h2><p>The <a shape="rect" class="ext ernal-link" href="http://www.w3.org/TR/html401/interact/forms.html" rel="nofollow">Forms in HTML documents</a> recommendation <a shape="rect" class="external-link" href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2" rel="nofollow">suggests</a> that multipart/form-data requests should mainly be used to upload files.</p><p>As mentioned in the previous section, one way to deal with multipart/form-data submissions is to deal directly with a CXF JAXRS Attachment class and get a Content-Disposition header and/or the underlying input stream.</p><p>It is now possible (since 2.2.5) to have individual multipart/form-data parts read by registered JAX-RS MessageBodyReaders, something that is already possible to do for types like multipart/mixed or multipart/related.</p><p>For example this <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/attachmentFormJson">request</a> can be handled by a method with the following signature:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST @Path("/books/jsonform") @Consumes("multipart/form-data") public Response addBookJsonFromForm(Book b1) {...} </pre> </div></div><p>Similarly, this <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/attachmentFormJsonJaxb">request</a> can be handled by a method with the following signature:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST @Path("/books/jsonjaxbform") @Consumes("multipart/form-data") public Response addBookJaxbJsonForm(@Multipart("jsonPart") Book b1, @Multipart("jaxbPart") Book b2) {} </pre> </div></div><p>Note that once a request has more than two parts then one needs to start using @Mutipart, the values can refer to either ContentId header or to ContentDisposition/name. Note that at the moment using @Multipart is preferred to using @FormParam unless a plain name/value submission is dealt with. The reason is that @Multipart can also specify an expected media type of the individual part and thus act similarly to a @Consume annotation.</p><p>When dealing with multiple parts one can avoid using @Multipart and just use List, ex, List\<Atachment\>, List\<Book\>, etc.</p><p>Finally, multipart/form-data requests with multiple files (file uploads) can be supported too. For example, this <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/attachmentFormJsonFiles">request</a> can be handled by a method with the signature like :</p><div class="code panel pdl" style="b order-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST @Path("/books/filesform") @Produces("text/xml") @Consumes("multipart/form-data") @@ -309,7 +309,7 @@ public Response addBookFilesForm(@Multip @Multipart("files") List<Book> books) {} </pre> </div></div><p>If you need to know the names of the individual file parts embedded in a "files" outer part (such as "book1" and "book2"), then please use List<Attachment> instead. It is currently not possible to use a Multipart annotation to refer to such inner parts but you can easily get the names from the individual Attachment instances representing these inner parts.</p><p>Note that it is only the last request which has been structured according to the recommendation on how to upload multiple files but it is more complex than the other simpler requests linked to in this section.</p><p>Please note that using JAX-RS FormParams is recommended for dealing with plain application/www-url-encoded submissions consisting of name/value pairs only.</p><h2 id="JAX-RSMultiparts-Content-DispositionUTF-8filenames">Content-Disposition UTF-8 file names</h2><p>Starting from CXF 3.0.4 it is possible to specify a Content-Disposition file names in a UTF-8 format, using a "filename*" Content-Di sposition extension parameter as opposed to the "filename" one.</p><p>Please see <a shape="rect" class="external-link" href="https://tools.ietf.org/html/rfc6266" rel="nofollow">RFC 6266</a> and <a shape="rect" class="external-link" href="https://git-wip-us.apache.org/repos/asf?p=cxf.git;a=blob;f=core/src/test/java/org/apache/cxf/attachment/AttachmentUtilTest.java;h=6eeedd42e965f4df8390ee6077222b34e1520732;hb=HEAD">this unit test</a> for more information. </p><h1 id="JAX-RSMultiparts-XOPsupport">XOP support</h1><p>CXF JAXRS clients and endpoints can support <a shape="rect" class="external-link" href="http://www.w3.org/TR/xop10/" rel="nofollow">XML-binary Optimized Packaging (XOP)</a>.<br clear="none"> What it means at a practical level is that a JAXB bean containing binary data is serialized using a multipart packaging, with the root part containing non-binary data only but also linking to co-located parts containing the actual binary payloads. Next it is deserialized into a JAX B bean on the server side.</p><p>If you'd like to experiment with XOP then you need to set an "mtom-enabled" property on CXF jaxrs endpoints and clients.<br clear="none"> Please see <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSMultipartTest.java">JAXRSMultipartTest</a> (testXopWebClient) and <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/MultipartStore.java">MultipartStore</a> (addBookXop) for more details.</p><h1 id="JAX-RSMultiparts-MultipartFilters">Multipart Filters</h1><p> </p><p>It is possible to intercept the attachment write or read process starting from CXF 3.1.12.</p><p><a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/MultipartInputFilter.java" rel="nofollow">Multipart InputFilter</a> and <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/MultipartOutputFilter.java" rel="nofollow">MultipartOutputFilter</a> have been introduced. These filters can be used to modify the list of the attachment parts or customize some of the individual part's properties, example, replace the part input stream, etc.</p><p>These filters can be registered from JAX-RS 2.0 client or container request/response filters or CXF in/out interceptors. <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/MultipartInputFilter.java" rel="nofollow">MultipartInputFilter</a> <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/multipart/AttachmentUtils.java#L71" rel="nofollow">can be added</a> to t he list of the input filters which is identified by a "multipart.input.filters" property on the current CXF message. Likewise, <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/MultipartOutputFilter.java" rel="nofollow">MultipartOutputFilter</a> <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/multipart/AttachmentUtils.java#L61" rel="nofollow">can be added</a> to the list of the output filters which is identified by a "multipart.output.filters" property on the current CXF message.</p><h1 id="JAX-RSMultiparts-SigningMultiparts">Signing Multiparts</h1><p>See <a shape="rect" href="http://cxf.apache.org/docs/jax-rs-jose.html#JAX-RSJOSE-SigningandVerificationofHTTPAttachments">this section</a> for more information.</p><h1 id="JAX-RSMultiparts-NoteaboutStruts">Note about Struts</h1><p>If you are using CXF and <a shape="rect" class="external-link" href="http://struts.apache.org/2.2.1/index.html">Struts2</a> within the same application and expecting CXF to process multipart/form-data payloads then you need to make sure Struts2 dispatcher is not consuming the request input stream.</p><p>One option is to let Struts2 handle URIs matching some specific patterns only, for example:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;"><web-app> +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;"><web-app> <filter> <filter-name>struts2</filter-name> <filter-class>
Modified: websites/production/cxf/content/docs/jax-rs-nio.html ============================================================================== --- websites/production/cxf/content/docs/jax-rs-nio.html (original) +++ websites/production/cxf/content/docs/jax-rs-nio.html Wed Sep 13 15:05:52 2017 @@ -117,18 +117,18 @@ Apache CXF -- JAX-RS NIO <!-- Content --> <div class="wiki-content"> <div id="ConfluenceContent"><p> </p><p><style type="text/css">/*<![CDATA[*/ -div.rbtoc1505311242794 {padding: 0px;} -div.rbtoc1505311242794 ul {list-style: disc;margin-left: 0px;} -div.rbtoc1505311242794 li {margin-left: 0px;padding-left: 0px;} +div.rbtoc1505314966990 {padding: 0px;} +div.rbtoc1505314966990 ul {list-style: disc;margin-left: 0px;} +div.rbtoc1505314966990 li {margin-left: 0px;padding-left: 0px;} -/*]]>*/</style></p><div class="toc-macro rbtoc1505311242794"> +/*]]>*/</style></p><div class="toc-macro rbtoc1505314966990"> <ul class="toc-indentation"><li><a shape="rect" href="#JAX-RSNIO-NIOExtension">NIO Extension</a> <ul class="toc-indentation"><li><a shape="rect" href="#JAX-RSNIO-Introduction">Introduction</a></li><li><a shape="rect" href="#JAX-RSNIO-NIORead">NIO Read</a></li><li><a shape="rect" href="#JAX-RSNIO-NIOWrite">NIO Write</a> <ul class="toc-indentation"><li><a shape="rect" href="#JAX-RSNIO-EvenEasierNIOWrite">Even Easier NIO Write</a></li></ul> </li></ul> </li></ul> </div><h1 id="JAX-RSNIO-NIOExtension">NIO Extension</h1><h2 id="JAX-RSNIO-Introduction">Introduction</h2><p>Servlet 3.1 API introduces a support for Non-Blocking IO, see <a shape="rect" class="external-link" href="http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HTML5andServlet31/HTML5andServlet%203.1.html" rel="nofollow">this tutorial</a> for more information.</p><p>The idea is that when the service code reads or writes the stream it does not block at all and only does a read or write action when a servlet container is ready to handle it effectively.</p><p>Early JAX-RS 2.1 API had a server-side prototype to help the JAX-RS service code utilize this Servlet 3.1 NIO features in a JAX-RS friendly way. Unfortunately that prototype was dropped from the final 2.1 API with the future major JAX-RS version expected to provide a much more complete and sophisticated NIO API.</p><p>CXF 3.2.0 has retained the implementation of the original JAX-RS 2.1 NIO API prototype and made it possible for the users to experiment with it.</p><h2 id="JAX-RSNIO-NIORead">NIO Read</h2><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: java; gutter: false; theme: Confluence" style="font-size:12px;">@POST +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@POST @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public void uploadBookStream(@Suspended AsyncResponse response) { @@ -161,7 +161,7 @@ public void uploadBookStream(@Suspended ); }</pre> </div></div><h2 id="JAX-RSNIO-NIOWrite">NIO Write</h2><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: java; gutter: false; theme: Confluence" style="font-size:12px;">@GET +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@GET @Produces(MediaType.TEXT_PLAIN) public Response getBookStream() throws IOException { final ByteArrayInputStream in = new ByteArrayInputStream( @@ -195,7 +195,7 @@ public void uploadBookStream(@Suspended </pre> </div></div><h3 id="JAX-RSNIO-EvenEasierNIOWrite">Even Easier NIO Write</h3><p> </p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: java; gutter: false; theme: Confluence" style="font-size:12px;">import org.apache.cxf.annotations.UseNio; +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">import org.apache.cxf.annotations.UseNio; @GET @Produces(MediaType.TEXT_PLAIN) @Path("/is") Modified: websites/production/cxf/content/docs/jax-rs-oauth.html ============================================================================== --- websites/production/cxf/content/docs/jax-rs-oauth.html (original) +++ websites/production/cxf/content/docs/jax-rs-oauth.html Wed Sep 13 15:05:52 2017 @@ -32,8 +32,8 @@ <link type="text/css" rel="stylesheet" href="/resources/highlighter/styles/shThemeCXF.css"> <script src='/resources/highlighter/scripts/shCore.js'></script> -<script src='/resources/highlighter/scripts/shBrushJava.js'></script> <script src='/resources/highlighter/scripts/shBrushXml.js'></script> +<script src='/resources/highlighter/scripts/shBrushJava.js'></script> <script> SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); @@ -121,11 +121,11 @@ Apache CXF -- JAX-RS OAuth  </p><p> </p><p><style type="text/css">/*<![CDATA[*/ -div.rbtoc1505311198312 {padding: 0px;} -div.rbtoc1505311198312 ul {list-style: disc;margin-left: 0px;} -div.rbtoc1505311198312 li {margin-left: 0px;padding-left: 0px;} +div.rbtoc1505314851657 {padding: 0px;} +div.rbtoc1505314851657 ul {list-style: disc;margin-left: 0px;} +div.rbtoc1505314851657 li {margin-left: 0px;padding-left: 0px;} -/*]]>*/</style></p><div class="toc-macro rbtoc1505311198312"> +/*]]>*/</style></p><div class="toc-macro rbtoc1505314851657"> <ul class="toc-indentation"><li><a shape="rect" href="#JAX-RSOAuth-Introduction">Introduction</a></li><li><a shape="rect" href="#JAX-RSOAuth-Mavendependencies">Maven dependencies</a></li><li><a shape="rect" href="#JAX-RSOAuth-DevelopingOAuth1.0Servers">Developing OAuth 1.0 Servers</a> <ul class="toc-indentation"><li><a shape="rect" href="#JAX-RSOAuth-RequestTokenService">RequestTokenService</a></li><li><a shape="rect" href="#JAX-RSOAuth-AuthorizationRequestService">AuthorizationRequestService</a> <ul class="toc-indentation"><li><a shape="rect" href="#JAX-RSOAuth-OOBcallbacks">OOB callbacks</a></li></ul> @@ -138,14 +138,14 @@ div.rbtoc1505311198312 li {margin-left: </li><li><a shape="rect" href="#JAX-RSOAuth-SingleSignOn">Single Sign On</a></li></ul> </li><li><a shape="rect" href="#JAX-RSOAuth-WhatIsNext">What Is Next</a></li></ul> </div><h1 id="JAX-RSOAuth-Introduction">Introduction</h1><p>CXF 2.5.0 implements <a shape="rect" class="external-link" href="http://tools.ietf.org/html/rfc5849" rel="nofollow">OAuth 1.0</a>. Please also see the <a shape="rect" href="jax-rs-oauth2.html">JAX-RS OAuth2</a> about the OAuth2 support in CXF.</p><p>While <a shape="rect" class="external-link" href="http://oauth.net/2/" rel="nofollow">OAuth 2.0</a> (which is very close to becoming the final recommendation) is the next major version of OAuth, OAuth 1.0 has been implemented by many providers and the CXF OAuth 1.0 module should make it easy for developers to start writing OAuth 1.0 applications.</p><p>OAuth 1.0 offers a complex yet elegant solution toward helping the end users (resource owners) authorize third-party providers to access their resources.</p><p>The classical OAuth flow is also called a 3-leg OAuth flow as it involves 3 parties: the end user (resource owner), the third party service (client, consumer) and the resou rce server which is protected by OAuth filters. Typically a consumer offers a service feature that an end user requests and which requires the former to access one or more resources of this end user which are located at the resource server. For example, the consumer may need to access the end user's photos in order to print them and post to the user or read and possibly update a user's calendar in order to make a booking.</p><p>In order to make it happen, the third-party service application/consumer needs to register itself with the OAuth server. This happens out-of-band and after the registration the consumer gets back a consumer key and secret pair. For example, see this page for one <a shape="rect" class="external-link" href="http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html" rel="nofollow">approach</a>. The registrations of third-party application does not have to be very involved for simpler applications.</p><p>From then on, the typical flow works like t his:<br clear="none"> 1. End User requests the third-party service using a browser.</p><p>2. Third-party service requests a temporarily request token from OAuth RequestToken Service; this token will represent a consumer's intention to access whatever end user resources it needs to complete the current user's request.</p><p>3. After getting a request token back, the consumer redirects the end user to OAuth Authorization Service and adds the request token to the target URI.</p><p>4. Authorization Service will get all the details about the current consumer using a request token, build an HTML form and return it to the end user. The form will ask the user if a given third-party application can be allowed to access some resources on behalf of this user.</p><p>5. If the user approves it then Authorization Service will redirect the user back to the callback uri provided by the consumer when requesting a request token, including a generated verifier (authorization key) which 'links' the use r's approval with the request token.</p><p>6. Now the third-party service requests an access token from OAuth AccessToken Service by providing a request token and its verifier.</p><p>7. After getting an access token, the service finally proceeds with accessing the current user's resources and completes the user's request.</p><p>As noted above, the consumer needs to register first with the OAuth server. It's a good practice to provide an application name and so called connect URI which is typically a public URI of this application; the former will be used by OAuth Authorization Service at step 4 above and the latter will be used at step 2 to validate the provided callback URI to make sure it starts from the URI which was actually provided during the registration.</p><p>As you can see the flow can be complex yet it is functional. A number of issues may need to be taken care along the way such as managing expired tokens, making sure that the OAuth security layer is functioning properly and is not interfering with the end user itself trying to access its own resources, etc.</p><p>Please check the <a shape="rect" class="external-link" href="http://tools.ietf.org/html/rfc5849" rel="nofollow">specification</a> and the <a shape="rect" class="external-link" href="http://en.wikipedia.org/wiki/OAuth" rel="nofollow">Wikipedia article</a> as well as other resources available on the WEB for more information you may need to know about OAuth.</p><p>CXF JAX-RS gives the best effort to making this process as simple as possible and requiring only a minimum effort on behalf of OAuth server developers. It also offers the utility code for greatly simplifying the way the third-party application can interact with the OAuth service endpoints.</p><h1 id="JAX-RSOAuth-Mavendependencies">Maven dependencies</h1><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;"><dependency> +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;"><dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-security-oauth</artifactId> <version>2.5.0</version> </dependency> </pre> </div></div><h1 id="JAX-RSOAuth-DevelopingOAuth1.0Servers">Developing OAuth 1.0 Servers</h1><p>OAuth server is the core piece of the complete OAuth-based solution. Typically it contains 3 services for:</p><ul class="alternate"><li>Initiating the flows by issuing temporarily tokens to consumers</li><li>Authorizing request tokens by asking the end users to let consumers access some of their resources and returning the<br clear="none"> confirmation back to the consumer</li><li>Exchanging authorized request tokens for access tokens</li></ul><p>CXF offers 3 JAX-RS service implementations that can be used to create OAuth 1.0 servers fast: <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/services/RequestTokenService.java" rel="nofollow">RequestTokenService</a>, <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/ oauth/src/main/java/org/apache/cxf/rs/security/oauth/services/AuthorizationRequestService.java" rel="nofollow">AuthorizationRequestService</a> and <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/services/AccessTokenService.java" rel="nofollow">AccessTokenService</a>.</p><p>All of these 3 services rely on the custom <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/provider/OAuthDataProvider.java" rel="nofollow">OAuthDataProvider</a> which manages request and access tokens. Writing your own OAuthDataProvider implementations is what is needed to get the OAuth server up and running.</p><h2 id="JAX-RSOAuth-RequestTokenService">RequestTokenService</h2><p>The main responsibility of <a shape="rect" class="external-link" href="https://github.com/apache/c xf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/services/RequestTokenService.java" rel="nofollow">RequestTokenService</a> is to create a temporarily request token and return it back to the consumer. It supports POST and GET requests and returns a form payload containing the new request token and its secret.</p><p>Here is an example request log:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Address: http://localhost:8080/services/oauth/initiate +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Address: http://localhost:8080/services/oauth/initiate Encoding: ISO-8859-1 Http-Method: POST Content-Type: */* @@ -164,22 +164,22 @@ Authorization=[OAuth oauth_callback="htt } </pre> </div></div><p>It is an empty POST request which includes an Authorization OAuth header. The value of the header has a consumer key (obtained during the third-party registration), callback URI pointing to where AuthorizationRequestService will return an authorized token and a signature which was calculated using a consumer key and secret pair as <a shape="rect" class="external-link" href="http://tools.ietf.org/html/rfc5849#section-3.4.2" rel="nofollow">described in the specification</a>.</p><p>First RequestTokenService validates the signature and then it retrieves a <a shape="rect" class="external-link" href="http://svn.apache.org/repos/asf/cxf/trunk/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/Client.java">Client</a> instance from OAuthDataProvider using a consumer key.</p><p>Before asking OAuthDataProvider to generate a request token, it attempts to validate a callback URI against a <a shape="rect" class="external-link" href="https://github .com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/Client.java" rel="nofollow">Client</a>'s application URI.</p><p>Finally it delegates to OAuthDataProvider to create a request token, passing to it a populated <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/RequestTokenRegistration.java" rel="nofollow">RequestTokenRegistration</a> bean.</p><p>This bean references a Client instance, callback URI and a state. State is something that a consumer may also include during the request token request using a "state" parameter and will be returned back to the consumer alongside the verifier after the request token has been authorized. For example, it may represent a key that a consumer will use to retrieve the state of the request that it was processing when requesting a token. For OAuth 1.0<br clear="none"> c onsumers, the request token itself may represent a good enough key for such purposes, but "state" may need to be used too and will become more useful for OAuth 2.0.</p><p>The bean also includes "issuedAt" and "lifetime" values which represent the time a new token is about to be created and a configurable time in milliseconds that this token will 'live' for. OAuthDataProvider will be free to reset those values if needed before actually creating a request token.</p><p>Finally, one more property that may be set on this bean instance: list of scopes. List of scopes represents optional permissions that the consumer may need to access the resources. These can be provided by an "x_oauth_scope" ("scope" in OAuth 2.0) request parameter, for example,</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Authorization=[OAuth ..., +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Authorization=[OAuth ..., x_oauth_scope="readCalendar updateCalendar"] </pre> </div></div><p>It's expected that each of the x_oauth_scope values such as "readCalendar" and "updateCalendar" are translated into <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/OAuthPermission.java" rel="nofollow">OAuthPermission</a>s during the creation of a new request token. If no x_oauth_scope parameter is provided then the OAuth data provider will likely assign a default OAuthPermission instance to the new token.</p><p>After a new request token has been created by OAuthDataProvider, RequestTokenService returns the token key and secret pair to the consumer:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Response-Code: 200 +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Response-Code: 200 Content-Type: application/x-www-form-urlencoded Headers: {Date=[Tue, 08 Nov 2011 10:38:03 GMT]} Payload: oauth_callback_confirmed=true&oauth_token=6dfd5e52-236c-4939-8df8-a53212f7d2a2&oauth_token_secret=ca8273df-b9b0-43f9-9875-cfbb54ced550 </pre> </div></div><p>The consumer is now ready to redirect the current end user to <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/services/AuthorizationRequestService.java" rel="nofollow">AuthorizationRequestService</a>.</p><h2 id="JAX-RSOAuth-AuthorizationRequestService">AuthorizationRequestService</h2><p>The main responsibility of AuthorizationRequestService is to present an end user with a form asking the user to allow or deny the consumer accessing some of the user resources.</p><p>Remember that a third-party consumer redirects the current user to <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/services/AuthorizationRequestService.java" rel="nofollow">AuthorizationRequestService</a>, for example, here is how a redirection may happen:</p><div class="c ode panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Response-Code: 303 +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Response-Code: 303 Headers: {Location=[http://localhost:8080/services/social/authorize?oauth_token=f4415e16-56ea-465f-9df1-8bd769253a7d]} </pre> </div></div><p>The consumer application asks the current user (the browser) to go to a new address provided by the Location header and the follow-up request to AuthorizationRequestService will look like this:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Address: http://localhost:8080/services/social/authorize?oauth_token=6dfd5e52-236c-4939-8df8-a53212f7d2a2 +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Address: http://localhost:8080/services/social/authorize?oauth_token=6dfd5e52-236c-4939-8df8-a53212f7d2a2 Http-Method: GET Content-Type: Headers: { @@ -189,7 +189,7 @@ Referer=[http://localhost:8080/services/ } </pre> </div></div><p>First, <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/services/AuthorizationRequestService.java" rel="nofollow">AuthorizationRequestService</a> will retrieve <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/RequestToken.java" rel="nofollow">RequestToken</a> (which extends the base <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/Token.java" rel="nofollow">Token</a> class) from OAuthDataProvider using the value provided by the "oauth_token" query parameter.</p><p>Next it uses this token (which also links to Client) to populate an instance of <a shape="rect" class="external-link" href="https://github.com/a pache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/OAuthAuthorizationData.java" rel="nofollow">OAuthAuthorizationData</a> bean and returns it. OAuthAuthorizationData contains application name and URI properties, optional list of <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/Permission.java" rel="nofollow">Permission</a>s and URIs.</p><p>Two other important OAuthAuthorizationData properties are "oauthToken" and "authenticityToken", both are important for processing the decision request coming from the authorization form. The former is a request token key which will be used by AuthorizationRequestService to retrieve the RequestToken again and the latter for validating that the current session has not been hijacked - AuthorizationRequestService generates a random key, stores it in a Servlet HTTPSession ins tance and expects the returned authenticityToken value to match it - this is a recommended approach and it also implies that the authenticityToken value is hidden from a user, for example, it's kept in a 'hidden' form field.</p><p>The helper "replyTo" property is an absolute URI identifying the AuthorizationRequestService handler processing the user decision and can be used by view handlers when building the forms or by other OAuthAuthorizationData handlers.</p><p>So the populated OAuthAuthorizationData is finally returned. Note that it's a JAXB XMLRootElement-annotated bean and can be processed by registered JAXB or JSON providers given that AuthorizationRequestService supports producing "application/xml" and "application/json" (See the OAuth Without Browser section below for more). But in this case we have the end user working with a browser so an HTML form is what is really expected back.</p><p>AuthorizationRequestService supports producing "text/html" and simply relies on a regi stered <a shape="rect" href="http://cxf.apache.org/docs/jax-rs-redirection.html#JAX-RSRedirection-WithRequestDispatcherProvider">RequestDispatcherProvider</a> to set the OAuthAuthorizationData bean as an HttpServletRequest attribute and redirect the response to a view handler (can be JSP or some other servlet) to actually build the form and return it to the user. Alternatively, registering <a shape="rect" href="http://cxf.apache.org/docs/jax-rs-advanced-xml.html#JAX-RSAdvancedXML-XSLTsupport">XSLTJaxbProvider</a> would also be a good option for creating HTML views.</p><p>Assuming RequestDispatcherProvider is used, the following example log shows the initial response from AuthorizationRequestService:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">08-Nov-2011 13:32:40 org.apache.cxf.jaxrs.provider.RequestDispatcherProvider logRedirection +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">08-Nov-2011 13:32:40 org.apache.cxf.jaxrs.provider.RequestDispatcherProvider logRedirection INFO: Setting an instance of "org.apache.cxf.rs.security.oauth.data.OAuthAuthorizationData" as HttpServletRequest attribute "data" and redirecting the response to "/forms/oauthAuthorize.jsp". @@ -199,7 +199,7 @@ Response-Code: 200 Content-Type: text/html </pre> </div></div><p>Note that a "/forms/oauthAuthorize.jsp" view handler will create an HTML view - this is a custom JSP handler and whatever HTML view is required can be created there, using the OAuthAuthorizationData bean for building the view. Most likely you will want to present a form asking the user to allow or deny the consumer accessing some of this user's resources. If OAuthAuthorizationData has a list of Permissions set then adding the information about the permissions is needed, same for a list of URIs.</p><p>Next the user makes a decision and selects a button allowing or denying the consumer accessing the resources. AuthorizationRequestService does not need to know how a user has been asked to make the decision, but it expects to receive a form-based submission containing the following 3 parameters, named "session_authenticity_token" and "oauth_token" with values matching those of OAuthAuthorizationData's "authenticityToken" and "oauthToken" properties, and "oAuthDecision" wi th either "allow" or "deny" values:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Address: http://localhost:8080/services/social/authorize/decision +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Address: http://localhost:8080/services/social/authorize/decision Http-Method: POST Content-Type: application/x-www-form-urlencoded Headers: { @@ -213,14 +213,14 @@ INFO: session_authenticity_token=e52b503 &oauth_token=6dfd5e52-236c-4939-8df8-a53212f7d2a2 </pre> </div></div><p>AuthorizationRequestService will use a session_authenticity_token to validate that the session is valid and will process the user decision next.<br clear="none"> If it is set to "allow" then it will ask OAuthDataProvider to generate an authorization key (verifier) and return this verifier alongside with the request token key and the state if any by redirecting the current user back to the callback URI provided during the request token request:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Response-Code: 303 +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Response-Code: 303 Headers: { Location=[http://localhost:8080/services/reservations/reserve/complete? oauth_token=6dfd5e52-236c-4939-8df8-a53212f7d2a2&oauth_verifier=00bd8fa7-4233-42a2-8957-0a0a22c684ba] } </pre> </div></div><p>which leads to a browser redirecting the user:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Address: http://localhost:8080/services/reservations/reserve/complete? +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Address: http://localhost:8080/services/reservations/reserve/complete? oauth_token=6dfd5e52-236c-4939-8df8-a53212f7d2a2&oauth_verifier=00bd8fa7-4233-42a2-8957-0a0a22c684ba Http-Method: GET Content-Type: @@ -231,7 +231,7 @@ Referer=[http://localhost:8080/services/ User-Agent=[Mozilla/5.0 (X11; Linux x86_64; rv:2.0) Gecko/20100101 Firefox/4.0]} </pre> </div></div><p>If a user decision was set to "deny" then no verifier will be sent back to the consumer.</p><p>Assuming the decision was "allow", the consumer has now received back the request token and its verifier and is ready to exchange this pair for an access token.</p><h3 id="JAX-RSOAuth-OOBcallbacks">OOB callbacks</h3><p>The OAuth 1.0 mentions so called "oob" (out-of-band) callbacks. If the third-party client is not running as a web application or if it is known it can not receive the redirect response from AuthorizationRequestService for whatever reasons, then a callback URI can be set to "oob", when a request token is <br clear="none"> requested:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Address: http://localhost:8080/services/oauth/initiate +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Address: http://localhost:8080/services/oauth/initiate Encoding: ISO-8859-1 Http-Method: POST Content-Type: */* @@ -250,7 +250,7 @@ Authorization=[OAuth oauth_callback="oob } </pre> </div></div><p>RequestTokenService will only accept the "oob" value if a client callbackURI property has been set to "oob" during the client application registration process. Specifically, RequestTokenService will expect that a <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/Client.java" rel="nofollow">Client</a> bean will have its callbackURI property being set to "oob".</p><p>When a callback URI is set to "oob", it means that a user decision response needs to be presented directly to the current user - which will then make the request token and verifier info somehow available to the client application. In case of "oob", AuthorizationRequestService, instead of redirecting the user back to the callback URI as shown earlier on, will simply return an instance of <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/o auth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/services/OOBAuthorizationResponse.java" rel="nofollow">OOBAuthorizationResponse</a>. RequestDispatcherProvider will need to be used for redirecting this data to the view handler exactly how it is done when a user is asked to authorize the client application, with the view handler formatting the data and actually returning it to the user</p><h2 id="JAX-RSOAuth-AccessTokenService">AccessTokenService</h2><p>The role of AccessTokenService is to exchange an authorized request token for a new access token which will be used by the consumer to access the end user's resources. <br clear="none"> Here is an example request log:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Address: http://localhost:8080/services/oauth/token +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Address: http://localhost:8080/services/oauth/token Http-Method: POST Headers: { Accept=[application/x-www-form-urlencoded], @@ -265,13 +265,13 @@ Authorization=[OAuth oauth_signature_met } </pre> </div></div><p>This request is very similar to a temporarily token request. Note that the request token key is also included and this token key and its secret pair, as well as the consumer key and secret pair are used to calculate the signature.</p><p>AccessTokenService validates the signature, asks OAuthDataProvider to remove a RequestToken identified by the "oauth_token" and compares the "oauth_verifier" value against the one stored in this RequestToken.</p><p>Note that if the "oauth_verifier" is missing then AccessTokenService will check that RequestToken has been preauthorized and that its UserSubject property is initialized. If both conditions are met then the access token request is allowed to continue.</p><p>Next it asks the data provider to create a new <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/AccessToken.java" rel="nofollow">AccessToken</a> base d on this RequestToken. The resulting access token key and secret pair is returned back to a consumer:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Response-Code: 200 +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Response-Code: 200 Content-Type: application/x-www-form-urlencoded Headers: {Date=[Tue, 08 Nov 2011 13:50:59 GMT]} Payload: oauth_token=abc15aca-2073-4bde-b1be-1a02dc7ccafe&oauth_token_secret=859dfe9e-ca4c-4b36-9e60-044434ab636c </pre> </div></div><p>The consumer will use this access token to access the current user's resources in order to complete the original user's request, for example, the request to access a user's calendar may look like this:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Address: http://localhost:8080/services/user/calendar +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Address: http://localhost:8080/services/user/calendar Http-Method: GET Headers: { Accept=[application/XML], @@ -283,7 +283,7 @@ Authorization=[OAuth oauth_signature_met } </pre> </div></div><p>Note that the access token is set and the access token key and secret pair, as well as the consumer key and secret pair are used to create a signature.</p><h2 id="JAX-RSOAuth-WritingOAuthDataProvider">Writing OAuthDataProvider</h2><p>Using CXF OAuth service implementations will help a lot with setting up an OAuth server. As you can see from the above sections, these services rely on a custom <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/provider/OAuthDataProvider.java" rel="nofollow">OAuthDataProvider</a> implementation.</p><p>The main task of OAuthDataProvider is to persist request and access tokens and generate authorization/verifier keys. The way it's done is really application-specific. Consider starting with a basic memory based implementation and then move on to keeping the data in some DB.</p><p>Note that OAuthDataProvider supports retrieving <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/Client.java" rel="nofollow">Client</a> instances but it has no methods for creating or removing Clients. The reason for it is that the process of registering third-party consumers is very specific to a particular OAuth application, so CXF does not offer a registration support service and hence OAuthDataProvider has no Client create/update methods. You will likely need to do something like this:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">public class CustomOAuthProvider implements OAuthDataProvider { +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">public class CustomOAuthProvider implements OAuthDataProvider { public Client registerClient(String applicationName, String applicationURI, ...) {} public void removeClient(String cliendId) {} // etc @@ -291,7 +291,7 @@ Authorization=[OAuth oauth_signature_met } </pre> </div></div><p>CustomOAuthProvider will also remove all tokens associated with a given Client in removeClient(String cliendId).</p><p>When creating RequestToken or AccessToken tokens as well as authorization keys, OAuthDataProvider will need to create unique identifiers.<br clear="none"> The way it's done is application specific and custom implementations may also use a utility <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/provider/MD5SequenceGenerator.java" rel="nofollow">MD5SequenceGenerator</a> shipped with CXF, for example:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">public String setRequestTokenVerifier(RequestToken requestToken) throws OAuthServiceException { +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">public String setRequestTokenVerifier(RequestToken requestToken) throws OAuthServiceException { requestToken.setVerifier(generateSequence()); return requestToken.getVerifier(); } @@ -306,7 +306,7 @@ private String generateSequence() throws </pre> </div></div><p>Generating tokens/keys and persisting them effectively is what OAuthDataProvider all about.<br clear="none"> Note that CXF will check that Request and Access tokens have not expired every time it uses them and will ask OAuthDataProvider to remove the expired tokens, but the custom OAuthDataProvider implementation may do its own checks too.</p><p>Finally OAuthDataProvider may need to convert opaque scope values such as "readCalendar" into a list of <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/OAuthPermission.java" rel="nofollow">OAuthPermission</a>s. AuthorizationRequestService and OAuth security filters will depend on it (assuming scopes are used in the first place). In the former case AuthorizationRequestService will use this list to populate <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/ oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/OAuthAuthorizationData.java" rel="nofollow">OAuthAuthorizationData</a> - the reason this bean only sees <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/Permission.java" rel="nofollow">Permission</a>s is that the properties OAuthPermission keeps are of no interest to OAuthAuthorizationData handlers.</p><h2 id="JAX-RSOAuth-OAuthServerJAX-RSendpoints">OAuth Server JAX-RS endpoints</h2><p>With CXF offering OAuth service implementations and a custom OAuthAuthorizationData provider in place, it is time to deploy the OAuth server. <br clear="none"> Most likely, you'd want to deploy RequestTokenService and AccessTokenService as two root resources inside a single JAX-RS endpoint (or have one RequestTokenService and one AccessTokenService endpoint), for example:</p><div class="code panel pdl" style="b order-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;"><!-- implements OAuthDataProvider --> +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;"><!-- implements OAuthDataProvider --> <bean id="oauthProvider" class="oauth.manager.OAuthManager"/> <bean id="requestTokenService" class="org.apache.cxf.rs.security.oauth.services.RequestTokenService"> @@ -325,7 +325,7 @@ private String generateSequence() throws </jaxrs:server> </pre> </div></div><p>RequestTokenService listens on a relative "/initiate" path, AccessTokenService - on "/token". Giving the that jaxrs:server/@adress is "/oauth" and assuming a context name is "/services", the absolute address of RequestTokenService would be something like "http://localhost:8080/services/oauth/initiate" and that of AccessTokenService - "http://localhost:8080/services/oauth/token".</p><p>AuthorizationRequestService is better to put where the main application endpoint is. It can be put alongside RequestTokenService and AccessTokenService - but the problem is that the end user is expected to authenticate itself with the resource server after it has been redirected by a third-party consumer to AuthorizationRequestService. That would make it more complex for the OAuth server endpoint to manage both OAuth (third-party consumer) and the regular user authentication - that can be done, see more on it below in the Design considerations section, but the simpler option is to simply get AuthorizationRequestService under the control of the security filter enforcing the end user authentication:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;"><bean id="authorizationService" class="org.apache.cxf.rs.security.oauth.services.AuthorizationRequestService"> +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;"><bean id="authorizationService" class="org.apache.cxf.rs.security.oauth.services.AuthorizationRequestService"> <property name="dataProvider" ref="oauthProvider"/> </bean> @@ -341,7 +341,7 @@ private String generateSequence() throws </jaxrs:server> </pre> </div></div><p>AuthorizationRequestService listens on a relative "/authorize" path so in this case its absolute address will be something like "http://localhost:8080/services/myapp/authorize". This address and those of RequestTokenService and AccessTokenService will be used by third-party consumers.</p><h1 id="JAX-RSOAuth-ProtectingresourceswithOAuthfilters">Protecting resources with OAuth filters</h1><p><a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/filters/OAuthRequestFilter.java" rel="nofollow">OAuthRequestFilter</a> request handler can be used to protect the resource server when processing the requests from the third-party consumers. Add it as a jaxrs:provider to the endpoint which deals with the consumers requesting the resources.</p><p>When checking a request like this:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelCon tent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">Address: http://localhost:8080/services/user/calendar +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">Address: http://localhost:8080/services/user/calendar Http-Method: GET Headers: { Accept=[application/XML], @@ -353,7 +353,7 @@ Authorization=[OAuth oauth_signature_met } </pre> </div></div><p>the filter will do the following:</p><p>1. It will validate the signature and will get Client and AccessToken from OAuthDataProvider.</p><p>2. It will check if <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/AccessToken.java" rel="nofollow">AccessToken</a> have a "uris" property set and if yes then it will validate the current request URI against it.</p><p>3. If AccessToken has a list of <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/OAuthPermission.java" rel="nofollow">OAuthPermissions</a>. For every permission it will:</p><ul class="alternate"><li>If it has a uri property set then the current request URI will be checked against it</li><li>If it has an httpVerb property set then the current HTTP verb will be checked agains t it</li></ul><p>4. Finally, it will create a CXF SecurityContext using this list of <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/OAuthPermission.java" rel="nofollow">OAuthPermissions</a> and the <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/Client.java" rel="nofollow">Client</a> loginName property.</p><p>This loginName property is something that can be optionally associated with the new Client during the registration - if it is not set then the filter will use a Client "applicationName" property instead. The application code checking the user Principal will see the chosen value. Additionally every OAuthPermission may have a list of application-specific roles such as "consumer", etc, which will be added to SecurityContext and will be checked during SecurityContext.isUserInRole(roleName) calls.</p><p>If a "useUserSubject" property is set on the filter then a UserSubject associated with the access token will be used to populate the SecurityContext.</p><p>This SecurityContext will not necessarily be important for some of OAuth applications. Most of the security checks will be done by OAuth filters and security filters protecting the main application path the end users themselves use. Only if you would like to share the same JAX-RS resource code and access URIs between end users and consumers then it can become handy. More on it below.</p><p>Note that <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/filters/OAuthServletFilter.java" rel="nofollow">OAuthServletFilter</a> can be deployed instead. It will need the OAuthDataProvider full class name referenced as an "oauth.data.provider-class" servlet cont ext parameter.</p><h1 id="JAX-RSOAuth-Howtogettheuserloginname">How to get the user login name</h1><p>When one writes a custom server application which needs to participate in 3-leg OAuth flows, the major question which needs to be addressed is<br clear="none"> how one can access a user login name that was used during the end-user authorizing the third-party client. This username will help to uniquely identify the resources that the 3rd party client is now attempting to access.<br clear="none"> The following code shows one way of how this can be done starting from CXF 2.5.1:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;"> +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;"> @Path("/userResource") public class ThirdPartyAccessService { @@ -377,7 +377,7 @@ public class ThirdPartyAccessService { </pre> </div></div><p>The above shows a fragment of the JAX-RS service managing the access to user resources from authorized 3rd-party clients (see the Design Considerations section for more information).</p><p>The injected MessageContext provides an access to <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/OAuthContext.java" rel="nofollow">OAuthContext</a> which has been set by OAuth filters described in the previous section. OAuthContext will act as a container of the information which can be useful to the custom application code which do not need to deal with the OAuth internals which will likely change between OAuth 1.0 and OAuth 2.0. At the moment OAuthContext provides an access to <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/UserSubject. java" rel="nofollow">UserSubject</a> which is created by CXF AuthorizationService at the moment of the end user authorizing the third-party client and captures the end user's login name (and roles which will be available if CXF JAASLoginInterceptor is used to authenticate end users) and associates it with the current <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/RequestToken.java" rel="nofollow">RequestToken</a>. It will be a responsibility of custom OAuthDataProviders to make sure this UserSubject bean is copied across to a corresponding <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/AccessToken.java" rel="nofollow">AccessToken</a>. OAuthContext also references the list of the permissions which have been validated againt the current cl ient request.</p><p>Additionally you may get OAuth filters to set up a SecurityContext which will use the information available in <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/UserSubject.java" rel="nofollow">UserSubject</a>, in other words, get the 3rd-party client impersonating the end user (which authorized this client in the first place) for the duration of the current request. Set a jaxrs contextual "org.apache.cxf.rs.security.oauth.use_user_subject" property to 'true' for this to happen.</p><h1 id="JAX-RSOAuth-Client-sidesupport">Client-side support</h1><p>When developing a third party application which needs to participate in OAuth flows one has to write the code that will redirect users to OAuth AuthorizationRequestService, interact with RequestTokenService and AccessTokenService in order to get request and access tokens as well as correctly build Au thorization OAuth headers when accessing the end users' resources. JAX-RS makes it straightforward to support the redirection, while <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/client/OAuthClientUtils.java" rel="nofollow">OAuthClientUtils</a> class makes it possible to encapsulate most of the complexity away from the client application code.</p><p>OAuthClientUtils has utility methods for getting request and access tokens, the consumer is expected to provide a properly initialized WebClient pointing to either RequestTokenService and AccessTokenService, Consumer bean containing the registration key and secret, a callback URI for requesting a request token and the request Token and the verifier for requesting the access token which is all quite straightforward. It also helps to create a proper URI for redirecting to AuthorizationRequestService. A correct Authorizat ion header will also need to be used when accessing the user resources at the resource server and OAuthClientUtils will help with creating this header as well.</p><p>For example, the following custom code can be used by the third-party application:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">public class OAuthClientManager { +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">public class OAuthClientManager { private WebClient accessTokenService; private WebClient requestTokenService; @@ -411,7 +411,7 @@ public class ThirdPartyAccessService { } </pre> </div></div><p>The reason such a simple wrapper can be introduced is to minimize the exposure to OAuth of the main application code to the bare minimum, this is why in this example OAuthServiceExceptions are caught, presumably logged and null values are returned which will indicate to the main code that the request failed. Obviously, OAuthClientUtils can be used directly as well.</p><h1 id="JAX-RSOAuth-2-legOAuthFlow">2-leg OAuth Flow</h1><p>Please see this blog <a shape="rect" class="external-link" href="http://blog.nerdbank.net/2011/06/what-is-2-legged-oauth.html" rel="nofollow">entry</a> for a good overview of the OAuth 2-leg flow.<br clear="none"> Here are the variations of the 2-leg flow that CXF supports:</p><h2 id="JAX-RSOAuth-ClientrequestsPreAuthorizedRequestToken">Client requests PreAuthorized RequestToken</h2><p>In this variation the client accesses the request token as usual but skips the explicit authorization step.<br clear="none"> Instead, after the request token has been obtained, it requests the access token without providing an "oauth_verifier" parameter. <br clear="none"> For this to work RequestToken needs to be pre-authorized and have its UserSubject property set.</p><p>This is the only distinction from the typical 3-OAuth flow. OAuth filters will validate the request as usual.</p><h2 id="JAX-RSOAuth-SignaturewithConsumerKeyandSecret">Signature with Consumer Key and Secret</h2><p>In this mode the consumer key and secret pairs are used to create the "oauth_signature", Authorization header will look pretty much the same as it does during RequestToken requests.</p><p>In this mode the Client is expected to reference a pre-authorized AccessToken. OAuth filters validate this token as usual.</p><h2 id="JAX-RSOAuth-OnlyConsumerKeyandSecretinAuthorizationheader">Only Consumer Key and Secret in Authorization header</h2><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;"> +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;"> Address: http://localhost:8080/services/user/calendar Http-Method: GET Headers: { @@ -420,7 +420,7 @@ Authorization=[OAuth oauth_consumer_key= } </pre> </div></div><p>Alternatively, the consumer key and secret can be joined by a ":" character and encoded with the Base64 encoding:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;"> +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;"> Address: http://localhost:8080/services/user/calendar Http-Method: GET Headers: { @@ -429,7 +429,7 @@ Authorization=[Basic base64EncodedValue] } </pre> </div></div><p>In this mode the Client is expected to reference a pre-authorized AccessToken. OAuth filters validate this token as usual.</p><h1 id="JAX-RSOAuth-OAuthWithoutaBrowser">OAuth Without a Browser</h1><p>When an end user is accessing the 3rd party application and is authorizing it later on, it's usually expected that the user is relying on a browser. <br clear="none"> However, supporting other types of end users is easy enough. Writing the client code that processes the redirection requests from the 3rd party application and AuthorizationRequestService is simple with JAX-RS and additionally CXF can be configured to do auto-redirects on the client side.</p><p>Also note that AuthorizationRequestService can return XML or JSON <a shape="rect" class="external-link" href="https://github.com/apache/cxf/blob/master/rt/rs/security/oauth-parent/oauth/src/main/java/org/apache/cxf/rs/security/oauth/data/OAuthAuthorizationData.java" rel="nofollow">OAuthAuthorizationData</a> representat ions. That makes it easy for a client code to get OAuthAuthorizationData and offer a pop-up window or get the input from the command-line. Authorizing the third-party application might even be automated in this case - which can lead to a complete 3-leg OAuth flow implemented without a human user being involved.</p><h1 id="JAX-RSOAuth-Reportingtheerrordetails">Reporting the error details</h1><p>CXF OAuth 1.0 services will report only HTTP status code in case of various OAuth-related errors to minimize the information about the actual cause of the failure and will log the details locally. If providing the extra error information can help with debugging 3rd-party applications or if such application can indeed recover from the failures based on such details, then setting a contextual "report.failure.details" property to "true" will get the error messages available in the response body. Some OAuth1.0 implementers have chosen to return a custom "oauth_problem" HTTP header instead - this o ption can be supported by additionally setting a contextual "report.failure.details.as.header" property to "true", for example:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;"><jaxrs:server id="oauthServer" address="/initiate"> +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;"><jaxrs:server id="oauthServer" address="/initiate"> <jaxrs:serviceBeans> <bean class="org.apache.cxf.rs.security.oauth.services.RequestTokenService"/> </jaxrs:serviceBeans> @@ -441,7 +441,7 @@ Authorization=[Basic base64EncodedValue] </pre> </div></div><h1 id="JAX-RSOAuth-Designconsiderations">Design considerations</h1><p>This section will talk about various design considerations one need to take into account when deploying OAuth-based solutions.</p><h2 id="JAX-RSOAuth-ControllingtheAccesstoResourceServer">Controlling the Access to Resource Server</h2><p>One of the most important issues one need to resolve is how to partition a URI space of the resource server application.</p><p>We have two different parties trying to access it, the end users which access the resource server to get to the resources which they own and 3rd party consumers which have been authorized by the end users to access some of their resources.</p><p>In the former case the way the authentication is managed is completely up to the resource server application: basic authentication, two-way TLS, OpenId (more on it below), you name it.</p><p>In the latter case an OAuth filter must enforce that the 3rd party consumer has been registered using the provide d consumer key and that it has a valid access token (authorization key in OAuth 2.0) which represents the end user's approval. It's kind of the authentication and the authorization check at the same time.</p><p>Letting both parties access the resource server via the same URI(s) complicates the life for the security filters but all the parties are only aware of the single resource server URI which all of them will use.</p><p>Providing different access points to end users and consumers may significantly simplify the authentication process - the possible downside is that multiple access points need to be mantained by the resource server.</p><p>Both options are discussed next.</p><h3 id="JAX-RSOAuth-Sharingthesameaccesspathbetweenendusersandconsumers">Sharing the same access path between end users and consumers</h3><p>The first problem which needs to be addressed is how to distinguish end users from third-party consumers and get both parties authenticated as required.<br clear="none"> P erhaps the simplest option is to extend a CXF OAuth filter (JAX-RS or servlet one), check Authorization header, if it is OAuth then delegate to the superclass, alternatively - proceed with authenticating the end users:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">public class SecurityFilter extends org.apache.cxf.rs.security.oauth.filters.OAuthRequestFilter { +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">public class SecurityFilter extends org.apache.cxf.rs.security.oauth.filters.OAuthRequestFilter { @Context private HttpHeaders headers; @@ -457,7 +457,7 @@ Authorization=[Basic base64EncodedValue] } </pre> </div></div><p>The next issue is how to enforce that the end users can only access the resources they've been authorized to access.<br clear="none"> For example, consider the following JAX-RS resource class:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl"> -<pre class="brush: bash; gutter: false; theme: Confluence" style="font-size:12px;">@Path("calendar") +<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">@Path("calendar") public class CalendarResource { @GET