<@U04UQ68083H> Which Ory Hydra flow should be used...
# ory-copilot
h
@chilly-king-10285 Which Ory Hydra flow should be used for Server-to-server communication: Authorize communication between servers without a user present.
b
A message from kapa.ai
For server-to-server communication—where you need to authorize communication between servers without a user present—the recommended Ory Hydra flow is the OAuth2 Client Credentials Flow. This flow is specifically designed for non-interactive applications, such as automated processes or microservices, where the client (server) authenticates using its client ID and client secret to obtain an access token. No user interaction is required in this scenario, making it ideal for machine-to-machine authorization [OAuth2 client credentials flow](https://www.ory.sh/docs/oauth2-oidc/client-credentials) [Try common OAuth2 Grants](https://www.ory.sh/docs/getting-started/ory-network-oauth2) [Use cases](https://www.ory.sh/docs/oauth2-oidc#use-cases).
h
@chilly-king-10285 show example nodejs and fastify code of how to implement an OAuth2 authenticated API route that can be called from another server using OAuth2 Client Credentials flow
b
A message from kapa.ai
Certainly! Here’s how you can implement an OAuth2 authenticated API route in Node.js using Fastify, where the route can be called from another server using the OAuth2 Client Credentials flow. ### 1. Obtain an Access Token Using Client Credentials Flow First, the calling server needs to obtain an access token from Ory Hydra using its client credentials. Here’s a Node.js example using
fetch
and the
client_secret_post
method:
Copy code
js const fetch = require("node-fetch");  const clientID = "the-client-id"; const clientSecret = "the-secret-id";  const qs = new URLSearchParams(); qs.set("grant_type", "client_credentials"); qs.set("client_id", clientID); qs.set("client_secret", clientSecret); qs.set("scope", "read"); // adjust scope as needed  const requestOptions = {   method: "POST",   headers: { "Content-Type": "application/x-www-form-urlencoded" },   body: qs.toString(), };  fetch("<https://your-project.projects.oryapis.com/oauth2/token>", requestOptions)   .then((response) => response.json())   .then((data) => console.log(data.access_token));
This will return an access token to be used in the Authorization header when calling the protected API route [OAuth2 client credentials flow](https://www.ory.sh/docs/oauth2-oidc/client-credentials). --- ### 2. Fastify API Route Protected by OAuth2 Access Token On the receiving server, you need to verify the access token. The recommended way is to use the Ory Hydra token introspection endpoint to validate the token on each request [Accessing APIs](https://www.ory.sh/docs/oauth2-oidc/overview/oauth2-concepts#accessing-apis). Here’s a Fastify route example that checks the Bearer token:
Copy code
js const fastify = require('fastify')(); const fetch = require('node-fetch');  fastify.addHook('preHandler', async (request, reply) => {   const authHeader = request.headers['authorization'];   if (!authHeader || !authHeader.startsWith('Bearer ')) {     reply.code(401).send({ error: 'Missing or invalid Authorization header' });     return;   }    const token = authHeader.replace('Bearer ', '');    // Introspect the token with Ory Hydra   const introspectRes = await fetch('<https://your-project.projects.oryapis.com/oauth2/introspect>', {     method: 'POST',     headers: { 'Content-Type': 'application/x-www-form-urlencoded' },     body: `token=${token}`,   });    const introspectData = await introspectRes.json();    if (!introspectData.active) {     reply.code(401).send({ error: 'Invalid or expired token' });     return;   }    // Optionally, check scopes or other claims here   request.user = introspectData; });  fastify.get('/protected', async (request, reply) => {   return { message: `Hello, your client_id is ${request.user.client_id}` }; });  fastify.listen({ port: 3000 }, err => {   if (err) throw err;   console.log('Server listening on <http://localhost:3000'>); });
Notes: - Replace
<https://your-project.projects.oryapis.com>
with your actual Ory Hydra project URL. - The client (calling server) must include the access token in the
Authorization: Bearer <token>
header when calling
/protected
. - You can further check for required scopes or other claims in the
introspectData
object. This approach follows the recommended Ory pattern for API protection using OAuth2 Client Credentials flow [Accessing APIs](https://www.ory.sh/docs/oauth2-oidc/overview/oauth2-concepts#accessing-apis) [OAuth2 client credentials flow](https://www.ory.sh/docs/oauth2-oidc/client-credentials). If you need more advanced policy enforcement, consider using Ory Oathkeeper as an API gateway in front of your Fastify app.
h
@chilly-king-10285 now show example code of the same thing but using Java Spring Boot and Spring Security
b
A message from kapa.ai
I'm sorry, but the knowledge sources provided do not contain a complete, explicit code example for implementing an OAuth2 authenticated API route in Java Spring Boot and Spring Security for the OAuth2 Client Credentials flow. However, the documentation does mention that Spring Security is a popular OAuth2 client library for Java and provides a [community example](https://github.com/ardetrick/ory-hydra-refrence-java) of integrating Ory Hydra with Java Spring, which may be helpful as a reference [Popular OAuth2 client libraries](https://www.ory.sh/docs/hydra/guides/using-oauth2) [Community examples](https://www.ory.sh/docs/getting-started/overview). If you need a step-by-step code example, please refer to the linked community resources or the official Spring Security documentation. If you have a more specific question about Ory Hydra integration details, feel free to ask!