Authentication
Introduction
In this section, we’ll focus on adding authentication to your REST API. We’ll introduce the @useAuth
decorator, show how to enforce authentication on specific operations, and provide an example using Bearer authentication.
Introduction to the @useAuth
Decorator
The @useAuth decorator is used to enforce authentication on specific operations in your REST API. This decorator allows you to specify the authentication mechanism that should be used for the operation. The TypeSpec HTTP library provides support for several authentication models, including BearerAuth
for Bearer authentication.
Bearer authentication uses tokens for access control. The server generates a token upon login, and the client includes it in the Authorization header for protected resource requests. The server validates the token to grant access to the resource.
Example: Enforcing Authentication on Specific Operations
Let’s update our existing operations to enforce authentication using the @useAuth
decorator. We’ll add authentication to the operations that modify pet data: creating, updating, and deleting pets. We’ll also add a new error model for unauthorized access.
In this example:
- The
@useAuth(BearerAuth)
decorator is applied to thecreatePet
,updatePet
, anddeletePet
operations to enforce authentication using the Bearer authentication mechanism. - A new error model,
UnauthorizedError
, is defined to handle unauthorized access errors. - The
UnauthorizedError
model is used in thecreatePet
,updatePet
, anddeletePet
operations to indicate unauthorized access.
Example: OpenAPI Specification with Authentication
Let’s take a closer look at how the @useAuth
decorator affects the generated OpenAPI specification for the deletePet
operation.
Explanation
- Security Section: The
security
section in thedeletePet
operation specifies that Bearer authentication is required. This is indicated by theBearerAuth
security scheme. - Security Schemes: The
components
section includes asecuritySchemes
definition forBearerAuth
, specifying that it uses the HTTP bearer authentication scheme.
Benefits
- Security: Ensures that only authorized clients can perform certain actions by enforcing authentication on specific operations.
- Consistency: The use of common parameters and authentication mechanisms is consistently applied across relevant operations.
- Clarity: The generated OpenAPI specification clearly shows which operations require authentication and which parameters are needed, improving the documentation and usability of the API.
Conclusion
In this section, we focused on adding authentication to your REST API using TypeSpec. By using the @useAuth
decorator, we can enforce authentication on specific operations, ensuring that only authorized clients can perform certain actions.
In the next section, we’ll dive into versioning your REST API. Versioning allows you to introduce new features and improvements while maintaining backward compatibility for existing clients.