Securing Swagger API Documentation with an API Key (JWT) | FREE COURSE
Summary
TLDREste curso se enfoca en la creación y seguridad de la documentación de APIs utilizando Swagger. Aprenderás qué es la documentación de una API, por qué es importante y cómo Swagger puede ayudar en este proceso. Seguidamente, se aborda la implementación y configuración de Swagger para requerir una clave API, crucial para la seguridad de tu aplicación. El instructor te guía a través de la construcción de un angular application que permitirá a los usuarios obtener una clave API. Al finalizar, tendrás un sólido entendimiento de la documentación de APIs y cómo crearla y protegerla adecuadamente. Además, se discuten los prerrequisitos, incluyendo el conocimiento de Java, Spring Framework, Spring Security, JSON Web Token, Angular, HTML, CSS y TypeScript. El curso ofrece una visión general de la aplicación base, que es una aplicación de gestión de facturas, y cómo se integra con Swagger para proporcionar una experiencia de usuario mejorada y facilidad en el mantenimiento y actualización de la API.
Takeaways
- 📚 **Creación de documentación de API**: Se discute cómo utilizar Swagger para crear documentación de API que sea útil para los usuarios y cómo integrarla con una aplicación existente.
- 🛡️ **Seguridad con API Key**: Se aborda la configuración de Swagger para requerir un API key, explicando cómo proteger la documentación de la API y los endpoints.
- 🔗 **Swagger como herramienta**: Se menciona que Swagger es una herramienta para crear documentación de API y se da una visión general de sus ventajas.
- 🚀 **Angular para aplicaciones front-end**: Se indica que se construirá una aplicación Angular para que los usuarios puedan obtener un API key y usarlo para acceder a la API.
- 💻 **Pre-requisitos técnicos**: Se resalta la importancia de entender tecnologías como Java, Spring Framework, Spring Security, API, JSON Web Token, Angular, HTML, CSS, JavaScript y TypeScript antes de tomar el curso.
- 🏗️ **Sobre la configuración de Swagger**: Se detalla el proceso para agregar la configuración de Swagger a una aplicación existente en lugar de construir una aplicación desde cero.
- 🔑 **JWT como API Key**: Se explica que un JSON Web Token (JWT) se usará como el API key y se destaca la necesidad de comprender su estructura y uso.
- 📝 **Importancia de la documentación de API**: Se discuten las razones por las cuales crear documentación de API es beneficioso, incluyendo mejora de la experiencia del usuario, aumento de la conciencia, ahorro de tiempo y dinero, y facilidad de mantenimiento.
- 🏛️ **Aplicación de ejemplo**: Se presenta una visión general de la aplicación de gestión de facturas que se utilizará a lo largo del curso para示范strar cómo se integra Swagger.
- 🛠️ **Configuración de seguridad existente**: Se asume que la configuración de seguridad para la API ya está en su lugar y se indica que el curso en seguridad es un requisito previo para comprender estos aspectos.
- ⚙️ **Adición de dependencias de Swagger**: Se proporciona una guía para agregar la dependencia de Swagger en el archivo pom.xml para poder utilizar las funcionalidades de Swagger en la aplicación.
Q & A
¿Qué es la documentación de una API y por qué es importante crearla?
-La documentación de una API es un conjunto de instrucciones que permite a los usuarios entender cómo usar o integrarse con la API. Es importante porque mejora la adaptación del usuario, aumenta el conocimiento sobre la API, ahorra tiempo y dinero al evitar la necesidad de soporte directo, y facilita el mantenimiento de la API al proporcionar una especificación clara de cómo funciona.
¿Por qué se utiliza Swagger para la documentación de la API?
-Swagger es una herramienta que permite crear y visualizar la documentación de una API de manera interactiva. Se utiliza porque proporciona una forma fácil de generar y mantener la documentación, y permite a los desarrolladores probar y ejecutar las operaciones de la API directamente desde la interfaz de usuario de Swagger.
¿Qué es un JSON Web Token (JWT) y cómo se relaciona con la seguridad de una API?
-Un JSON Web Token (JWT) es un estándar abierto (RFC 7519) que define una estructura de codificación compacta que representa una cadena de notificaciones que pueden ser decodificada y verificadas en un servidor. Se relaciona con la seguridad de una API porque actúa como un API key, proporcionando una forma de autenticación segura para acceder a los recursos de la API.
¿Qué tecnologías son necesarias para comprender y aprovechar este curso sobre documentación de API con Swagger?
-Se necesita entender Java, el framework Spring y Spring Security, así como conceptos de API y JSON Web Token. Del lado del cliente, se espera que el estudiante tenga conocimientos en Angular, HTML, CSS, JavaScript y TypeScript.
¿Cómo se puede obtener el mejor rendimiento del curso y qué recursos externos son útiles?
-Para obtener el mejor rendimiento del curso, se recomienda tomar el curso de seguridad previo, entender JSON Web Token, ver todos los videos, utilizar recursos en línea para investigar dudas, codificar junto con el curso si es posible y, si hay preguntas, comunicarse con el instructor.
¿Qué es una 'Docket' en el contexto de configuración de Swagger?
-Una 'Docket' en Swagger es un objeto que se utiliza para configurar y personalizar la documentación de la API. Se define en una clase de configuración y se utiliza para链定 ('chain') múliples configuraciones juntas, como la información de la API, el esquema de seguridad y las anotaciones de Swagger.
¿Cómo se define la información de contacto en la documentación de Swagger?
-La información de contacto se define mediante un método que devuelve un objeto 'Contact'. Este objeto se construye con detalles como el nombre de contacto, la URL de contacto y el correo electrónico de contacto, que generalmente son proporcionados por el desarrollador de la API.
¿Cómo se indica en Swagger que se requiere un API key para acceder a la documentación de la API?
-Se indica que se requiere un API key definiendo un objeto 'ApiKey' en la configuración de Swagger. Se especifica el nombre del encabezado (como 'Authorization') y se asocia con un 'Security Reference' que describe el tipo de autorización requerida.
¿Qué es una 'Security Context' y cómo se define en Swagger?
-Una 'Security Context' en Swagger define el alcance y las reglas de seguridad que se aplicarán a una o varias rutas de la API. Se define utilizando el método 'securityContexts' y se asocia con un 'Security Reference' que se puede aplicar a las rutas de la API para requerir autenticación.
¿Cómo se asegura que los usuarios obtengan un API key para usar la documentación de la API?
-Los usuarios obtienen un API key a través de una aplicación frontal, como se describe en la documentación de Swagger. Generalmente, implica que el usuario se registre o inicie sesión en la aplicación, solicita un token y luego lo utiliza para autorizar su acceso a la documentación de la API.
¿Por qué se recomienda tomar el curso de seguridad antes de este curso sobre documentación de API con Swagger?
-Se recomienda tomar el curso de seguridad primero porque este curso asume que el estudiante ya tiene un conocimiento sólido de Spring Security y JSON Web Token, que son fundamentales para entender cómo proteger una API y requerir un API key. El curso de seguridad proporciona las bases necesarias para comprender la configuración de seguridad en el curso de Swagger.
Outlines
😀 Introducción al curso de Swagger API Documentation
El primer párrafo presenta el curso centrado en la creación de documentación de API con Swagger, utilizando una clave API para la seguridad. Se menciona que el curso incluirá la definición de la documentación de API, la implementación y configuración de Swagger para requerir una clave API, y la construcción de una aplicación Angular para la obtención de claves de API. Además, se ofrece una visión general de la documentación de API, su importancia y cómo el usuario puede interactuar con ella, incluyendo el proceso de autenticación para obtener una clave API.
📚 Requisitos previos y tecnologías clave
Este párrafo aborda los conocimientos previos necesarios para aprovechar el curso, incluyendo Java, Spring Framework, Spring Security, API, JSON Web Token, Angular, HTML, CSS, JavaScript y TypeScript. Se destaca la importancia de comprender estos conceptos para no encontrarse estancado durante el curso y se sugiere tomar un curso de seguridad previo que cubrirá Spring Security y JSON Web Token.
📋 Contenidos y objetivos del curso
Se describe el plan de estudios del curso, que incluye introducciones, explicación de los conceptos básicos de la documentación de API, detalles sobre Swagger, una revisión general de la API y su seguridad, configuración de Swagger para requerir una clave API, uso de anotaciones de Swagger y construcción de una aplicación Angular. Se enfatiza la importancia de entender la documentación de API y se ofrece orientación para obtener el máximo beneficio del curso.
🛠️ Ventajas de crear documentación de API
En este párrafo se discuten las razones por las cuales crear documentación de API es beneficioso, como mejorar la adaptación del usuario, aumentar la conciencia, ahorrar tiempo y dinero, y facilitar el mantenimiento. Se proporciona una breve explicación de cómo la documentación de API puede ser una herramienta valiosa para los desarrolladores y la empresa.
🏢 Aplicación base y su configuración de seguridad
Se presenta una visión general de la aplicación base que se utilizará en el curso, la cual es una aplicación de gestión de facturas. Se describen las operaciones CRUD típicas y cómo se realiza la inyección de dependencias. Además, se menciona la configuración de seguridad, la cual es un requisito previo para el curso, y se sugiere tomar un curso específico de seguridad para comprender plenamente la configuración.
📄 Adición de dependencia y configuración inicial de Swagger
Se detalla el proceso para comenzar con Swagger en la aplicación, incluyendo la adición de la dependencia de Swagger en el archivo pom.xml y la creación de una clase de configuración de Swagger. Se enfatiza la importancia de la dependencia para que Swagger funcione correctamente en la aplicación.
📝 Configuración avanzada de Swagger con constantes y beans
Este párrafo se enfoca en la creación de una clase de constantes para almacenar información que se utilizará en la configuración de Swagger, como la información de contacto, el título y la descripción de la página, entre otros. Se describe cómo se estructurará la configuración de Swagger utilizando beans y se menciona la importancia de la separación de los métodos para una mejor legibilidad y facilidad de mantenimiento.
🔐 Definición de seguridad y contexto para Swagger
Se explica cómo definir la seguridad para Swagger, incluyendo la creación de un esquema de seguridad que utiliza una clave API en el encabezado de las solicitudes. Se detalla la definición de un contexto de seguridad y cómo se especifica el alcance y la descripción de la autorización. Este párrafo culmina con la expectativa de crear el bean de Swagger en la siguiente lección.
Mindmap
Keywords
💡Swagger
💡API Key
💡Spring Framework
💡Spring Security
💡JSON Web Token (JWT)
💡Angular
💡API Documentation
💡Security Configuration
💡RESTful API
💡CRUD Operations
💡Docket Bean
Highlights
The course aims to teach how to create and secure API documentation using Swagger with an API key.
Swagger is used to define what an API is, its capabilities, and how it can be utilized.
The course covers the importance of API documentation for developers and end-users.
Swagger is not only a documentation tool but also helps in implementing and configuring API security.
The course will guide through building an Angular application for users to obtain an API key.
Prerequisites include understanding Java, Spring Framework, Spring Security, and JSON Web Tokens.
The course is a continuation of a security course focusing on securing APIs with Spring Security and JSON Web Tokens.
The instructor emphasizes the importance of understanding the basics of Angular, HTML, CSS, JavaScript, and TypeScript.
The course outline is provided to give learners a clear expectation of what will be covered.
The course is designed to be concise, covering high-level concepts and practical implementation.
The instructor recommends taking a security course before this one for a better understanding of Spring Security.
API documentation serves as a technical content deliverable that instructs users on how to use an API effectively.
Benefits of API documentation include improved user adoption, increased awareness, time and cost savings, and easier maintenance.
The base application used in the course is an invoice management system with typical CRUD operations.
The application uses Spring Boot and has security configurations that protect endpoints requiring authentication.
Swagger configuration involves adding a dependency and creating a Swagger Config class.
The course will detail how to configure Swagger annotations to customize the UI page.
The final project involves building an Angular application from scratch to work in conjunction with the secured API.
Transcripts
hello and welcome to this course
securing swagger api documentation with
an api key
in this course i'm going to show you how
you can use swagger to create an api
documentation
photo api we'll start by defining what
an api documentation is
why you would want to create one why you
might want to use swagger
for your api documentation then we'll
move on to the ide
and i'll show you how to implement and
configure swagger to require an api key
for your application
and finally i'll show you how to build
an angular application
where you can send your users to get an
api key so that they can use it for your
api
by the end of this course you will have
a solid understanding of what an api
documentation is
and how to properly create and secure
api documentation
using swagger we have a lot to cover in
this course
i hope you're excited and i will see you
in the course
so this is your api documentation where
your user would come in to look at your
api documentation
and possibly try it out so for instance
if i go to the
get request here and i can read about
this
and then i can also try it out so i'll
click on try it out and then
execute this as you can see here i got
this four or three forbidden
so the idea here would be your user
would go
to say hey i need to get an api key so
they'll just go ahead and click here
and then here i'm gonna go ahead and log
in with jade and
i put in my information click on login
and you can see now i'm logged into the
frontend application
and then i would navigate to my security
tab and then here show token
well you have to hide the token because
it's sensitive information and then to
show the token you would click here and
then
click on it and then it says token
copied and then the user would go back
here and authorize so they would click
here
and then pass in the token and then
click on authorize
and then close this and then now if they
go ahead and say execute again
you can see now they get an actual
response so this was the whole
idea of what i wanted to do with the
front end and with this api
documentation application and if you
guys have any questions uh go ahead and
reach out to me
thank you for taking the course i hope
you find it valuable and i will see you
guys in the next one
i wanted to go over the pre-requisite
for this course
and this is really something that you
really have to understand as far as
understanding how to
take advantage of this course so let's
go ahead and get started so the first
technology
you need to really understand is java
because everything is java base for the
back end
so you need to understand java the
spring framework and also spring
security
because we're going to be working with
spring security as well now the reason
i want to make sure that you understand
this is because
we will not be building the application
that we're going to be working on in
this course
we will only be adding the swagger
configuration on top of this application
and this application is already using
java spring framework and spring
security
so when i give you the overview of that
application i'm expecting you to
understand
what the application is doing because
we're not going to go into the basics
of those technologies so you have to
understand you know java spring
framework and spring security
to some degree and then you need to
understand application programming
interface
because this is a concept that we will
also be working on since this whole
application
at least the back end is an application
programming interface
so you need to make sure you understand
that as well and then a json web token
so this one web token is going to be
our api key and you also need to
understand what that means right so you
need to understand
what kind of information a json web
token is carrying and why it's used and
things like that so
make sure you understand on json web
token and then from the front
application we'll be building on angular
applications so i'm expecting you to
understand the basics of angular and for
that of course you have to understand
html css and javascript so
make sure you get those covered and then
since angular uses typescript
so you need to understand typescript as
well now i'm not
expecting anyone to be an expert in any
of those technologies but at least
you have to be comfortable uh with them
uh so that you don't get stuck
during the course so make sure you
understand those technologies
well or make sure you're comfortable
with them uh or even if you get stuck
then you know how to you know research
it and fix whatever
problem that you have but you have to be
comfortable in those technology
let's go over the course outline so that
you guys understand what to expect from
this course so the first thing i want to
say
is this course is not a very long course
so we're not going to have like a dozen
sections or anything like that so what
you're looking at right now is just a
high level of exactly
what we're going to be doing in this
course so the first part is going to be
for the introductions uh this is the
part that we
we're in now and this is just going to
be me introducing the course to you
uh telling you how to get the best out
of this course and etc and the next part
is going to be me going over
the concepts with you so i'm going to be
talking about api documentation
what is api why do we need api
documentations what are the advantages
of having an api documentation
and why you want to do that and then
after that we're going to cover swagger
so
swagger is like an implementation of an
api documentation
or just an api documentation tool just a
tool that you can use to
create a documentation for api so we're
going to go over swagger
and then i'm going to give you some
resources as well regarding swagger
and then we're going to look at an
overview of the api that we have so
we're going to start off with some base
code and i'm going to walk you through
this code and that's going to be
our api overview and then i'm also going
to go over the security aspect of that
application as well
so you're gonna understand you know what
kind of security that the application
has in place
and what it's expecting from a user
trying to access the application
in order for that user to successfully
access it and then we're gonna
put in the configuration for swagger so
we're going to put this wire
configuration
which is going to require us to put in
an api key in order to be able to access
the api documentation
so after that we're going to move over
to some other swagger annotations and
those annotations we're mostly going to
be using
them in the controller so i'm going to
show you um how you can customize the
ui page for swagger and most of that
those annotations i'm going to be
putting them in the controller and then
lastly we're going to build the angular
app so we're going to start from scratch
with that application and then build it
from there now
as you can see this is a very condensed
high level
overview of the course but there's a lot
more in this course so
there's no way i'm going to be able to
you know list every single technology
that is being used on here
but at least i hope you guys understand
what exactly
we're going to be doing in this course
i want to talk a little bit about how to
get the most out of this course and as
the creator of the course
i always think that it's a good idea for
me to actually tell you how to get the
best out of this course so
this course is a continuation of a
security course that i built and
one of the first thing that i would
highly recommend every student who want
to take this course to do
is to take the security course the
security course is really a continuation
of this course now the reason i didn't
mention this and that we work with it is
because
you know there might be some students
that are already very
savvy with spanx security so there's no
point for them to take this spring
security course that i built
and i'm going to show that course in a
second but i would highly encourage
everyone
if you're not really good with spanx
security then you have to take the
security course first before you can
take this course
because this will cover pretty much
everything you need to know about spanx
security and json web token
and how to secure an api using spam
security and json web token
and what you're looking at right now is
the actual course and it's called json
web token with spring security and
angular and in that course i
show how to secure an angular
application using json web token
amongst other things so that's the first
thing i would highly encourage
everyone to take unless you're really
good with spring security
um then you have to take this course
before you actually take this
swagger course and this will really help
you a lot and even the base application
is the same the base application that
i'm using
in this swagger course that application
is coming from the security course so
i would highly encourage everyone to
take the security course
and then come back to this course to
understand how we can
add swagger on top of the security of an
api
using a json web token or an api key the
next thing to get the most out of this
course is going to be to
understand json web token because we're
going to use json web token as our api
key now
an api key doesn't necessarily have to
be a json web token
it can be any string character that you
use um
preferably something that's not really
easy to read but it can be any string of
characters so make sure you understand
json web token and what it means and
what it why it's used to
a secure api or why you can use it as an
api key
if you want to access the secure api
application and the next you have to
watch the lectures remember this is a
lecture slash
video based course so you have to watch
all the lectures
because this is where the content of the
course uh actually is
and this is where you will see what the
instructor is doing
uh and the explanation of everything
that the instructor is doing as well and
then next you have to use your online
resources now
i wouldn't say don't ask a question if
you have a question but
if something happens or you're stuck or
you have a quick question
i usually just google it because i take
courses myself so
if something happened to my application
or i have an issue or there's something
that i don't know
or just something just popped in my head
while i'm watching the course i would
just google it
and if i can't find the solution then i
would contact the professor
and or the instructor and see if they
can answer the question but first i
would
definitely use my online resources to
see if i can find a solution in the next
i would say if you can you can try to
code along
now this is not really required mostly
if you're already
experienced so you don't necessarily
have to code you can just watch what i'm
doing but
if you are a newbie then i would
definitely say if you can code along
then
you know try to do that because this is
going to build uh muscle memory
along with actual memory of what you're
learning and this is all going to stick
together because you know you're going
to be coding
writing code and thinking as you do that
as well so if you code along
you'll develop those meso memories that
you need and lastly you can go ahead and
ask me a question
so if you're stuck or your application
is not running or you have just some
questions or it can actually be any
question then you can
reach out in the q a or just send me a
message um
and then i will try to answer your
questions so another thing is i
answer every question in less than 24
hours
so you're not going to be waiting for
days and me not getting back to you i
try to answer all questions
within 24 hours so those are the main
points that i would say
um you need to have covered if you want
to take advantage of this course and get
the best of this course like i said
uh the security course really i would
recommend it because
the base application we're going to be
using it's coming straight from this
course
and if you don't really know what spanx
security is or you're not really good
with spring security you don't really
understand
everything about it then i would
definitely say take the security course
first
and then come and take this course
one of the most important questions that
we have to answer
in this course is what exactly is an api
documentation
so an api documentation is really just
something you can deliver to people
and they can use that to understand
exactly how to
effectively use or integrate with your
api so it's just a way that you're gonna
be able to tell them
say hey if you want to use my api here
is the link or here's the url
here are the different endpoints and
this is how you call those endpoints and
this is these are the parameters that
you need to pass
etc so it's really just something you
can deliver which is why it says the
technical content deliverable meaning
you can deliver it
and it has instructions on how to
effectively use and integrate with
your api and i have another more defined
definition below and i'm not going to
go ahead and read it to you but it's
really just saying the same thing hey
you want to be able to be as
thorough as possible because there might
be people that are not developers or
they're not very tech savvy and they
might still be able to
you know go to your api and try to
understand what it's doing and they
should be able to understand exactly
um how to use it and what it's doing i
mean of course they're not gonna be
able to understand everything uh like a
software engineer or
a developer but they should be able to
understand exactly
what the api is and what it's doing and
how to actually use it to to some degree
so it's really just a way for you to
tell people or tell the world
say hey this is my api and this is how
you're supposed to use that obviously
this is a very
high level summary but you have to be as
thorough as possible you have to define
what kind of information you're going to
give them back how they need to call
your api
if there is any authentication that they
need to do and things like that so it's
really just
explaining to people how to use your api
now the next question that we need to
answer is
why would you want to create an api
documentation so why would you want to
do that
well there are many advantages to
creating an api documentation
for your api and i've read many articles
about this there are
dozens of reasons why you would want to
do that but i'm just going to go over
a few of them so the first one we're
going to look at is going to be
improved user adaption so if your api
documentation
is very nice and detailed and people
come in and they can use it and it's
very easy for them to use
and what this is going to do is just
gonna make it easier for them to
use your api because it's very easy to
understand
and they love the experience so what's
gonna happen is they're gonna tell
other people about that they're gonna
say hey you should try to
use this api because they have a very
nice api documentation
and everything is going to be easy for
you and this overall
improved experience for your developers
is going to go a very long way because
you know they will just adapt or use
your api
more and more and more because the
documentation is just so great it makes
everything so easy to use it the next
reason you might want to do that
is to increase awareness so that ties
into the first point
so if one person uses your api and they
like the experience
and they're just gonna go ahead and tell
other people and then
more people are gonna come in and use
our api which is what you want in the
long run so those two points they're
very close to each other
the first one is just improve the
experience and as a result
of that more people are going to use it
you know people are going to tell
other people and then more people are
just going to use your api which is what
you want in the end
the next reason you might want to do
that is because it's going to save you a
lot of time and
a lot of money so let's imagine you have
like some api
that people can use but you don't have
an api documentation so
every time someone needs to use your api
they're going to have to
reach out to you or reach out to someone
in the company or
one of the owners of the api or someone
who can answer the question so
you know you might just be sending
emails out and you would have to do that
every time someone needs to use your api
and that's just gonna cost you time
and money so that's not the best way to
do things when you can just
say hey just go to this website or if
they google the the google
api or they you know hey there's this
company or
this service have a free api or even if
it's not free
or some api that they can use and then
your api documentation page will come up
so that will just save you
uh not having to deal with people coming
in and asking you directly or sending
you email
or whatever the case might be so it's
going to save you a lot of time
and with that a lot of money and the
last point i want to touch on
is maintenance so if everyone knows
how the api works and what kind of
methods and functions
and domain that is supposed to return
that's just going to make for
a better production application because
in the api documentation you have to be
very very clear as to what your api is
doing what's
returning uh what are the domains like i
said and what are some of the methods
etc so since this is already clear it's
gonna help
developers internal developers making
your api
even better because everyone understands
how the api works so that's gonna make
it easier for maintenance whenever you
have to make changes or to
improve parts of the api and things like
that and those are just four reasons
there's
way more reasons that i haven't even
read or i don't even know about
but it's definitely very important for
you to have api documentation for
api because that's just how you're going
to tell people
how to use it and integrate with it
i want to give you guys an overview of
the base application that we're going to
start with
and unlike all my other courses for this
course we're not going to start from
scratch because the focus is to create
the square configuration so i'm going to
give you a quick walkthrough of the
application that we're going to start
with so i'm just going to open my id
here and let's take a look at the main
application
and by the way this application is more
like an invoice management application
and the idea is you have some sort of a
store online or something where like you
have transactions going on
and then you have this api where you
know your clients can come and
look at invoices and things like that so
this is the main application class you
know nothing
here has been changed it's still the
same and let's go ahead and take a look
at the resource so we only have the
invoice resource here
just gonna collapse this for now and you
can see we have the typical risk
controller because this is a rest avi
and then we have this injection here
where we do the dependency injection for
the invoice service and in here
we have all of the typical crud
operations so add update
get a list of everything get invoices
for a specific customer
we can also get an invoice if we know
the invoice number
and we can delete an invoice so that's
just typical
credit operation nothing too complicated
here and
this controller or this rest resource is
calling
the service here so let's go ahead and
take a look at the service
just gonna click here so the service is
pretty simple we're just using the gpa
repository for everything
as you can see here it's imported here
and we inject it in this class here
and for saving an invoice we call the
save to get all the invoices we call the
find all
um we can also find an invoice by the
invoice number if we can find it we'll
through this custom exception that i
created and i'm going to take a look at
this in a second
and then we can you know update an
invoice which is the same as the save
the only difference is we have to pass
in the
primary key for that invoice and we can
also delete an invoice
or find invoice by specific customer
this application
is really very simple i didn't want to
add any you know crazy logic
and here just keeping it simple since
the point is to just show you how to
actually create the configuration for
the actual documentation for this api
so let's go ahead and take a look at the
repository here
since we're injecting it here and we're
calling it here in this class so the
repository is very typical
we just extend the jpa repository pass
the actual
model and the primary key for it and
then we're just using the jpa query
language and our method name so that we
can get the information that we need
from the backend
and all of this code is gonna be in the
video resource so you can just go ahead
and download it
so that we can get started and then we
also have the configuration for security
here
so i'm just gonna collapse this for now
and scroll up
so this is the typical security
configuration that you would see for
like a restful api
build with spring boot so we're just
allowing here
all of the resources that swagger needs
so that we don't black those
and then everything else you need to be
authenticated and this is just the
configuration here
with the http security and like i
mentioned before
the security course is a requirement for
this course so if you want to understand
exactly what's going on here in terms of
the security configurations
um then you just have to take that
course and you know pretty much
everything is going to be almost the
same
um i mean the course is going in depth
into a lot of detail in terms of
security
but it's a requirement for this course
so we're not going to be going over
everything in details here but please
what's going on here we have this filter
that we injecting in this class and we
pass it in here as a filter
before every request and then we're just
saying hey for our statement policy
we're going to use stateless because
we're not going to be using session or
anything that we're going to track
this is going to be you know every
request comes in we check
for an api key so we're not tracking any
values or any any logged in users or
anything like that and then down below
on line 35 we say hey for every url that
contains these
paths just allow everyone to access them
and then for any other request we need
to authenticate so
that way we can block every other access
to the application
only the swagger resources will pass our
security filter
and we can also take a look at this
filter real quick
and this filter is pretty much the same
filter that was built in the security
course because this course is required
and all we're doing here is to check to
make sure that every request coming
in has on you know a valid api key
before we allow it to go through the
application so
again if you want to understand this you
have to take the security course because
this can get a little bit complicated
and the point of this course is to go
over the configuration for swagger
and other things that we have here is
this utility class that we're using
and it's using the same library that is
used in the security course for
uh you know decoding creating token and
validating token and things like that
and we have all of these methods in
there like i mentioned
you have to take the security course so
that you can understand this so even
though you will have this
code and your as part of the course you
need to understand
everything that's going on here and to
do that you have to take the security
course
since this course is like a continuation
of the security course
and then we already looked at the
service we can take a look at that
exception
that i mentioned earlier so this
exception is just extending the runtime
exception
and it's calling the super constructor
so the constructor in this class
passing in the message that we're
passing in here and then we have the
invoice entity so we can take a look at
this real quick
it's annotated with at entity because
it's going to be saved in a database or
mapped to a database
and then we have the you know the
typical id for the primary key
the invoice number a list of product on
a real products
uh customer name and a total so very
typical simple poju
just trying to keep it simple and lastly
we're going to take a look at our
configuration so in our
properties file uh you know i have the
typical database
this is digital secret obviously this is
a joke
our secret has to be fair secure and has
to be very complicated string not just
this word secret
and then i have the credential for the
database and some other
configuration for jpa so
that's pretty much everything for this
application again if you don't know how
to create an api you can take my other
courses on api
and if you want to understand the
security aspect of this how we create
the security configuration
and this uh generality filter and this
dudability utility class that we're
using to validate the token
then you have to take the security
course which is a requirement for taking
this course because in this course
we're going to be focusing on creating
the configuration for swag just make
sure you remember that because we will
not
be building you know all of these in
this course
this is something that we already worked
on in the previous course which is a
requirement for this course so
i hope you guys understand this and if
you have any questions you can just
reach out to me
if you have any questions if you want
coupons or anything like that i can give
you like
a discount on the security course but
it's required for this course so
any questions just reach out and i'll
see you guys in the next one
the first thing we need to do in our app
to get started with swagger is to add
the dependency for swagger so let's go
into the
pom file so i'm gonna click here and go
all the way down to the pom file
gonna collapse this for now and this is
the dependency that we're gonna need for
swagger so
i'm gonna uncomment it so we're gonna be
using the latest version which is
version three so you have to make sure
that you have this dependency here
well you're gonna have the code so that
events is probably going to be there
already
but this is the dependency that's going
to bring all of these swagger jars that
we need
so that we can create our configuration
so make sure you have this dependency
in your application and then in the next
lecture we're gonna actually get started
with the actual configuration so i'll
see you guys in the next one
let's go ahead and add our swagger
configuration class
so i'm going to go ahead and close all
of these tabs that i'm not using
and you can create a new package for
this like a swagger package
but i'm just going to go ahead and put
it in this configuration here so i'm
going to put it in class
and i'm just going to name it swagger
config
you can name it whatever you want just
make sure it's something that's
meaningful
so first thing we want to do here since
this is the configuration class we want
to put the add configuration annotation
on it
so i'm going to do add and then
configuration
and this is supposed to come from spring
and after that we have a lot of constant
that we need
so that we can create the content for
the page itself so this is like
something that's going to be up to you
whatever you want to show when someone
comes to your api
what you want them to read about the api
and things like that so i'm going to go
ahead and copy and paste those
constant because they're just constant
like there's no logic or anything like
that
and then i'm gonna walk you through each
one of them so i'm gonna go ahead and
paste them i've already copied them
and put them there as you can see
they're all just constant so
the first one is the security reference
the security reference means
you know what type of access it's going
to be and that's a token
access or api key access in the
authorization description so
we're going to tell the user what kind
of authorization that they're getting
and this is like full api permission
because once you get a token then you
can access all of the endpoints now
if that specific token um was not going
to access
specific endpoints um but only like
certain endpoints
then you probably would have to change
this to be hey this can access
everything under
slash whatever or you know or only
this specific api and then the scope is
unlimited
you know the scope of the token is
unlimited once you have a token then
you can access everything and this is
for the contact information so i put
some dummy email here
some dummy url here for our organization
invoice.com
uh and then to contact me it's gonna be
like invoice api support you can click
on that
and it's gonna take you to this email or
whatever so that's just going to be the
text of it i believe
and then the title of the page so that's
invoice management api
and this is the big title that you see
like in bold
once you first access the swagger ui
page and we're going to see that in a
second
and this below is the description and
inside the description
you can actually put html elements as
you can see i'm doing here i'm putting
this note
in bold so you just put a text in here
you can see that all this plus to
concat the text because it's really long
and inside that string i also
embed the actual link that i want as you
can see here
inside the whole string i put this
anchor tag here
and then put the actual url that i want
whenever they click to get the
actual api token which is going to be
the front-end application
then this is going to take them to this
and you know i put the target to blank
so that you can open in a new page and
if i'm using this backlash is to escape
this other uh double quote here because
we're already inside of double quote we
have the
terms of service here so you know terms
of service will go here
whatever you want them to know the api
version i just put 1.1
but that would be the actual api version
because you might have different version
the license whatever the license is i'm
using apache here because i don't have
an actual license
and that's the page for that so if they
want to use more about the licensing
and the path that we want to secure is
going to be like every path in the
application
except the one that we configure in the
security configuration
if you guys remember so if we go to the
secure configuration except those paths
right here
because um those are needed whenever we
try to access the
swagger ui because then he needs to go
ahead and fetch some
jars and things like that so we have to
allow all of those
endpoints by default for swagger to work
otherwise you won't be able to fetch
those
pages and jars and then we have the tag
and i'm going to show you what the tag
is the tag is gonna be like
the text that you see on top of the api
before you
start seeing the end points so we can
have like an invoice tab or user tag or
things like that
but since we're only having invoice and
um that's the only
attack that we're going to have and i'm
going to show you how this is going to
come into play
everything here is going to come into
play once we have the ui and i can
access the ui and we can see all of
those in action
then i'll go and say hey this text here
represents this and this is that
so you will understand um why we need
all of these things and again you didn't
have to create constant for
all of these i just like to use constant
because it's a little bit cleaner
and you can actually put all of this in
a separate class if you want like a
swagger
constant class or something like that
because you know this is just constant
just you know it's text nothing's going
to change on this
uh or every day or there's no logic in
it or anything like that
but i just put them in here and then i
can just reach out and then
pass them in my configuration so we just
added the configuration class we haven't
actually added the
configuration for swagger yet and we
just put in some constant are we gonna
need
to create this configuration so i'll see
you guys in the next one
i know i said that we could actually
keep those constant in this class
but i have a better idea so i decided to
just put them in a constant class
because
they're taking a big chunk of this class
as you can see here because it's too
many of them so
i'm gonna just cut everything here
and then i'm gonna create a new package
so in the main package
i'm gonna add a new package and i'm just
going to call it constant
in that constant package i'm going to
create a new class
and i'm just going to call it swagger
constant
and i'm just going to add them here so
i'm gonna do ctrl v
and paste them here now i can use them
by just calling this class and then call
the actual
constant that i need but i have to make
those um public
because right now they're all private so
i'm just gonna copy this public here
and then change those so i just changed
all of them to public so that i can use
them
outside of this class at this point i
can just close the class
and then use everything from this class
so let's just
collapse this most of the swagger
configuration
is depending on one bin and this bin is
called a docket bin and that's the bin
that we have to define
and then we can chain all of the rest of
the configuration
all of the api information and api keys
information
etc so let's go ahead and define these
speeds i'm going to go down here and
then i'm just going to do bin
and then underneath here i'm going to
create a public method
i'm using the public and remember this
is the docket so i'm going to do docket
and i'm just going to call it api docket
and it doesn't take any parameters and
i'm just going to open and close for the
body of the method
and what i want to do here is just
return a new docket so i'm going to
return new dacket and then in here i
have to pass in the
swagger version so i'm going to do
swagger version 2
and we can click on this to take a look
at it so if i hold ctrl on my
keyboard and i just click that you can
see here it's going to take us to the
documentation for this
so here you can see we're using swagger2
not swagger 1.2
and this one down below is for open api
so we're not using that one but we're
using
swagger2 here so let's go ahead and
close that and go back to the
configuration
so now you can actually chain all of the
information in this configuration
but i don't think that's the best way to
do it and i'm going to show you what
that looks like in a minute
so you can actually chain everything you
can do api info and then you pass in
your api information
so i'm not gonna just chain everything
on that one configuration because it
just makes it harder to read and
understand
so i'm gonna separate this and put as
much as i can and separate methods
and then we can just call those methods
inside of here so i'm going to go down
here and then i'm going to create a
private method
oops and this method is going to
return the api info so i'm going to do
api info as you can see here
i'm going to give it the same name and
it's not going to accept any parameters
open and close
the braces and what i have to return
here is just a new api info so i'm going
to do return
a new api info and in that constructor
i can actually pass in the information
that i need to construct this
constructor and the first one is going
to be the api title
and of course we need to import that so
let's go here
my action and import static another
thing i want to do is to just go ahead
and import everything from the
let's see close this so we have the
constant here
so our constant so we know that we're
going to use all this constant in this
configuration class so we can just
import everything
so what i'm going to do here i'm going
to go back here and in this list of
import
as you can see the api title is being
imported here so i'm just going to put
an asterisk
so that i can import everything and then
collapse this that way i don't have to
do an import for
every time i want to access something
here it will be imported so the next
thing i want to do for the api info so
this is where you're passing the api
information
i have to pass in the api description
and then
pass in the api version so i'm going to
do api
version and i'm going gonna also pass in
the terms of use so terms of service
and then next i have to pass in a
contact so i'm gonna do
contact and this is gonna be a method
that i'm gonna create in a second
and then we can pass in the license and
i'm just gonna put this on a new line
and after the license we have to pass in
um
well let me just take a look at the
constructor so you guys can understand
what's going on here so you can see here
we have to pass in in this constructor
not this one though we're not using the
deprecated one so in this one we have to
pass in the title description version
terms of service contact license
license url and then we have to pass in
an array of
our list of version vendor extensions so
we don't have any vendors extensions and
i'm not using that now so we're just
going to pass in
an empty list for this but i just wanted
to show you
uh exactly what how do i know what i
have to pass in is to just read the
documentation
or i can just use the quick help from
the from the id so i can do control
space
and then it will show me uh what i have
to pass in here so after the license
we have to pass in the license url and
then after that we can pass in the empty
list and this empty list is going to be
for the
vendors extension or vendor extension so
we can close this for now
close this constant class and we can
pass in the
collection that empty list okay so
because we don't have any windows
extension
so this is going to be the api info and
we can use this api info
to chain it in this bin right here okay
so instead of doing all of this in that
one
bin or in this one method we're just
going to separate them
in in different methods and we can call
those methods
up here so next we have to define the
contacts i'm gonna just copy this name
i'm gonna scroll up here go down and
then here i'm just gonna create another
private and this is gonna be the contact
so i'm going to do contact
and i'm going to call it contact and of
course it's not going to take me
parameters
and i need to return a new contact so
i'm going to return new and for the
contact we just have to pass in
the contact name contact url and the
contact email so here i'm just gonna do
contact name
pass in the contact url and then pass in
the contact email
and then i can put a semicolon here and
then that's it you can see that you can
actually chain
all of these into this bin right here or
in this method
but i'm just decoupling everything so
that in case you have
to make changes then it becomes a lot
easier for you as you can see here and
like i said before
most of the swagger documentation is
going to be defined
in this bin right here and you're going
to see how this is going to look as we
put all of this together so i'll see you
guys in the next one
so let's go ahead and continue with the
configuration so what i have to define
next
is to tell swagger that i'm going to be
using an api key
and this api key is going to be in the
header of every request and that header
is going to be
the authorization header so i have to go
down here and then i'm going to do
oops i'm going to do private
and this is called api key so api key
and i'm just going to call the api key
and it doesn't take any parameters open
and close curly braces for the body of
the method and what i want to do here
is to return a new api key so i'm going
to do return
new api key and then inside here i have
to pass in the security reference so i'm
gonna do security
reference and this is the token access
as you can see here
and then i have to pass in the header
name so i'm gonna do
authorization okay as you can see here
the string authorization which is gonna
be the header
and then i have to say the security
scheme is going to be and the header so
i have to do security scheme
and and then i say header and then
get the name from the header so this is
how to find that you're going to be
using an api key
and that api key is going to be in the
header which is going to be
in the header of every request that gets
sent to the actual
backend or with the request and then
next we have to define our security
context so i'm going to go down here and
then define another private method
and this time i'm going to call it
security context
and i just name it security context and
it's not going to accept any parameters
and then here i have to return a
security context so i'm going to do
security context
and then call the builder on that and
then here i have to pass in
a list of security references so i'm
going to do
security references and then here i'm
going to pass in a security reference so
security
references or reference and i'm going to
define this method in a second and then
i can call build on that as well so that
we can build
our security context so in the security
reference here which is going to be
a list we're gonna define just the scope
of that security
uh or this key that we're gonna give to
users so that they can access the api so
this is gonna define the authorization
scope
uh the description of that as well so
let's go ahead down here
and let's define that method so i'm
going to do private and i'm just going
to copy this name
and here i'm going to say remember this
is a list so i'm going to do list
and it's going to be a list of security
reference
and i'm going to call it security
reference and then what i have to do
here
is to define the authorization scope so
i'm going to do authorization scope
and that's an array and i'm just going
to give it a name here
and then i have to set this equal to
an array and then inside that array i'm
going to pass in a new authorization
scope
and inside that constructor i can pass
in the authorization scope that i
defined which is unlimited
and then here i can also pass the
description so i'm going to do
authorization
description so once i have that in place
i can just return it as a singleton list
so i can go down here and then i can do
return
singleton list and then inside here i
can just pass in a new security
reference
and then in this constructor of the
security reference i can pass in the
security reference
and the scope that we just defined here
which is the authorization scope
so i'm gonna rename this
uh because it's plural so we only have
one
i'm gonna rename this and then just pass
it here
okay so now we're done so at this point
we have everything that we need to
actually create
this bin for the dacket so in the next
lecture
we're going to go ahead and use all of
this and you're going to see how this is
all going to come together
and then we're going to create this bean
and then after that we'll be able to see
something
when we try to access the url for daca
so
i'll see you guys in the next lecture
تصفح المزيد من مقاطع الفيديو ذات الصلة
cómo CREAR NOTAS en NOTION con SIRI 🤖 (fácil) con Atajos [2024]
Consumir API REST con #ANGULAR 17 con MANEJO DE ERRORES e INTERCEPTORS
30. Rutas dinámicas con vue-router y useRoute | AbiDev
Dockerize an Angular Application using Nginx
Curso Android. Trabajo con API y Eventos I. Vídeo 20
CÓMO CONSUMIR UN API con JAVASCRIPT desde la web
5.0 / 5 (0 votes)