#32 Spring Security | Custom Configuration
Summary
TLDRThis video tutorial delves into customizing Spring Security configurations beyond the default settings. It guides viewers through creating a config class to define beans and override the default security filter chain. The presenter demonstrates disabling CSRF protection, enforcing authentication for all requests, and toggling between form login and HTTP basic authentication. The tutorial also touches on making the application stateless for session management, providing a foundation for more advanced security implementations like JWT in future videos.
Takeaways
- 😀 The video discusses configuring a Spring Security application with custom settings beyond the default configurations.
- 🔒 It explains how to disable the default Spring Security configuration and set up a custom security filter chain.
- 🛠️ The presenter demonstrates creating a config class to customize Spring Security settings, emphasizing the use of the @Configuration annotation.
- 📝 The video covers changing application properties, such as usernames and passwords, and the importance of modifying the security filter chain.
- 🔄 The process of disabling CSRF (Cross-Site Request Forgery) protection in Spring Security is detailed, showing both lambda and imperative syntax.
- 🚫 It illustrates how to enforce authentication for every HTTP request, ensuring no page can be accessed without proper credentials.
- 🔑 The video guides through enabling form login with customizer and handling HTTP basic authentication for tools like Postman.
- 🔄 The presenter discusses the implications of disabling CSRF and making the HTTP session stateless using session management configurations.
- 📱 The script touches on the challenges of form login in a stateless session and how it requires credentials with every request.
- 🛑 The video shows how to disable the default logout functionality when implementing custom security configurations.
- 🔍 Finally, the script provides insights into the builder pattern for configuring HTTP security settings in a readable and sequential manner.
Q & A
What is the default configuration provided by Spring Security when it is first implemented?
-When Spring Security is first implemented, it provides a default configuration that includes a basic security setup. This includes a default user with a preset username and password, and a simple login form for authentication.
How can one customize the security settings in a Spring Security application?
-To customize the security settings in a Spring Security application, one needs to create a configuration class annotated with `@Configuration` and use the `@EnableWebSecurity` annotation to override the default security configuration. This allows the developer to define their own beans and security configurations.
What is the purpose of the `SecurityFilterChain` in Spring Security?
-The `SecurityFilterChain` in Spring Security is responsible for defining the sequence of security filters that are applied to the application's HTTP requests. Customizing this filter chain allows developers to control the security mechanisms applied to different parts of the application.
How can one disable CSRF (Cross-Site Request Forgery) protection in Spring Security?
-To disable CSRF protection in Spring Security, one can use the `HttpSecurity` object's `csrf()` method with a customizer that disables CSRF, either by using lambda syntax for a cleaner code or by using the imperative style with a custom `CsrfConfigurer`.
What does the `authorizeRequests()` method do in Spring Security configuration?
-The `authorizeRequests()` method in Spring Security configuration is used to specify the authorization rules for HTTP requests. It allows developers to define which requests should be authenticated, which can be done using lambda expressions or an `AuthorizationManager` object.
How can one implement form-based authentication in Spring Security?
-Form-based authentication can be implemented in Spring Security by using the `formLogin()` method on the `HttpSecurity` object. This method can be customized with default settings using `withDefaults()` or by specifying custom configurations.
What is HTTP Basic authentication and how is it enabled in Spring Security?
-HTTP Basic authentication is a simple authentication scheme built into the HTTP protocol, where credentials are sent in the HTTP headers. In Spring Security, it can be enabled by calling the `httpBasic()` method on the `HttpSecurity` object, which can also be customized with default settings.
Why might one want to disable the default logout functionality in a customized Spring Security setup?
-One might want to disable the default logout functionality in a customized Spring Security setup because when implementing custom authentication mechanisms, the default logout may not work as expected. Developers may need to implement their own logout logic that integrates with their custom authentication system.
What is the session creation policy and how does it relate to making a session stateless in Spring Security?
-The session creation policy in Spring Security determines when and how sessions are created. To make a session stateless, one can set the session creation policy to 'stateless' using the `sessionManagement()` method on the `HttpSecurity` object. This means that the server does not need to maintain session information between requests.
How can one make HTTP requests stateless to avoid CSRF issues in Spring Security?
-To make HTTP requests stateless and avoid CSRF issues, one can configure the session management in Spring Security to be stateless by setting the session creation policy to 'stateless'. This requires passing credentials with every request, effectively making each request independent of any session state.
What is the builder pattern mentioned in the script and how does it simplify Spring Security configuration?
-The builder pattern mentioned in the script is a method of constructing an object step by step, often used in configurations. In Spring Security, it simplifies the configuration by allowing developers to chain method calls on a single object, making the code more readable and easier to manage.
Outlines
🛠️ Customizing Spring Security Configuration
The video script begins with an explanation of how to configure Spring Security by default and then customize it. The speaker details the process of setting up Spring Security with default configurations through dependency inclusion and then modifying the application properties for username and password. The focus then shifts to connecting with a database and disabling form login. The script emphasizes the creation of a separate config class to customize the security filter chain, explaining the importance of marking the class with the @Configuration annotation and using@EnableWebSecurity to override default configurations. The speaker also demonstrates how to create a security filter chain bean and the necessity of using HTTP security to build the custom filter chain, including handling errors related to missing exception signatures.
🔒 Disabling CSRF and Restricting Access for Authentication
This paragraph delves into the process of disabling Cross-Site Request Forgery (CSRF) protection in Spring Security, highlighting the changes in Spring six that require different syntax for disabling CSRF using either Lambda or imperative style. The speaker illustrates how to enforce authentication for every HTTP request, ensuring no one can access any page without proper credentials. The summary includes the steps to enable form login using customizer with default settings and the implications of disabling CSRF on browser-based login forms. It also touches on enabling HTTP basic authentication for API access through Postman and the importance of understanding the underlying configurations for securing applications.
🔄 Implementing Stateless Sessions and HTTP Basic Authentication
The speaker discusses the concept of stateless sessions in Spring Security and how to implement them by modifying the session management configuration. By setting the session creation policy to stateless, the application no longer relies on session IDs for maintaining user state, which simplifies the authentication process, especially with HTTP basic authentication. The script covers the challenges of using stateless sessions with form login in browsers and how to work around them by disabling form login and using HTTP basic authentication instead. It also explains the use of builder patterns for configuring HTTP security settings in a readable and organized manner.
🛑 Troubleshooting Configuration Issues and Anticipating Future Enhancements
In the final paragraph, the speaker encounters issues with the application's configuration settings and decides to comment out the current setup to understand what happens behind the scenes. The explanation includes the technical details of the HTTP security object and how CSRF, authorize requests, and HTTP basic configurations work. The speaker simplifies the understanding by breaking down the interface implementations and method definitions required for each security feature. The paragraph concludes with a look ahead to future videos that will cover more advanced topics such as integrating with databases, using JWT, and other security enhancements, inviting viewers to share their excitement for the upcoming content.
Mindmap
Keywords
💡Spring Security
💡Configuration Class
💡Security Filter Chain
💡@EnableWebSecurity
💡HTTP Security
💡CSRF (Cross-Site Request Forgery)
💡Form Login
💡HTTP Basic
💡Builder Pattern
💡Stateless
💡Session Management
Highlights
Introduction of configuring the application with Spring Security and its default settings.
Explanation of how to change application properties for username and password customization.
Desire to connect with a database and disable form login for enhanced security settings.
Step-by-step guide on creating a custom security configuration class in Spring.
The importance of marking a class as a configuration class with the @Configuration annotation.
Enabling web security by overriding the default configuration with @EnableWebSecurity.
Creating a method to return a custom Security Filter Chain object.
Using HTTP security to build the custom security filter chain.
Disabling CSRF protection with the new approach in Spring 6.
Authorizing HTTP requests to require authentication for every request.
Demonstration of the application working without security leading to unauthorized access.
Enabling form login with customizer and default properties.
Testing form login functionality and its successful implementation.
Explanation of HTTP basic authentication and its necessity for Postman access.
Making the application work with HTTP basic authentication in Postman.
Discussion on disabling form login for direct API access and its implications.
Making the application stateless to handle CSRF by using session creation policy.
Understanding the builder pattern to apply multiple settings to the HTTP security object.
Final demonstration of the application with customized security settings working as expected.
Conclusion and anticipation for upcoming videos on advanced security topics like JWT.
Transcripts
so till this point we were able to
configure the application right and we
are basically able to implement Spring
Security but then most of the settings
are default right so we implemented
Spring Security by saying hey I got the
dependency this project is secured by
Spring Security and Spring Security says
okay since you are using me let me give
you some default configuration and then
we have changed something okay so
basically we went to application
properties we we set the username
password we have done some changes but
then we want to do more we want to
connect with database we want to uh
disable let's say I don't want to go go
for a form login so there are a lot of
settings which you have to do and then
we'll do that step by step in this video
let's see how do we configure that how
do we create our own settings how do we
change the way the security filter chain
works so to do that of course we want to
change the way it works right by default
Spring Security provides you a filter
chain there are lot of filters which
comes into and then it will check for
the defaults but now I want to customize
it I want to have my own filter chain
and the way you can do that is by
creating a config class see when you
talk about spring framework and if you
want to customize something or when you
want to have your own configuration you
create a separate Class A config class
and then you define beans there which
will inject the object so now what I
will do is to achieve that I will create
a class but then I will create that
class in a package I will name this your
package as config and in this package I
want to have that class which is the
security config so this is the class we
have and in this class we have to do
that first of all I want to say that
this is a configuration file to Spring
and to do that you will say
configuration now your spring knows that
this is a configuration class and I have
to search for the configuration here
next I don't want to go for the default
Spring Security configuration I want to
implement it here so to do that you will
say enable web security Now by doing
this you are saying hey don't go for the
default flow go with the flow which I
mentioned here so by doing this we are
doing two things first we are saying
this is the configuration and we are
saying that go with this configuration
now what I want to change see by default
it will work for the security filter
chain I want to customize it so in order
to do that what you have to do is you
have to return a bean for security
filter chain so let's do that so I will
create a method which will return you
the object of
security filter chain which is coming
from uh springf framework. security.
web. security filter chain and then we
can give any method name here so I will
say security filter chain and this will
basically give you the object of
security chain but how so of course you
have to return the object of security
filter chain now who will give you this
so there is a type called HTTP security
have to use this let's create reference
for it called HTTP you can also say HTP
security but HTTP is a small word so it
makes sense and I will be using that
because sttp has a method called build
so basically the build here Returns the
object of security filter chain now it
is giving you some error here is because
we have to add the exception throw
exception here a signature now this will
do so what we are doing is we are saying
hey Spring Security don't go for the
default this is a security chain you
have to go for so this is a filter chain
follow this and you're good to go now
since we have not specified find any
filter here by default no filter is
applied I will show you so what I will
do is I will just uh restart this in
fact you know let's comment the bean tag
and let's restart then or maybe we have
to also comment enable security so I've
commented both enable web security and
the bean here that means this is still
not applicable what we are doing and I
want to check without those things if I
hit the URL you can see it is still
enabling the login form so that means
spring secur is still implemented but if
I do this and if I UNC commmand this B
now and if I restart so let's see if
disables the default configuration so
let's go back here and instead of
hitting the login I will hit the URL and
it's working without login it is working
so if I refresh it is still there that
means security is not implemented now we
are bypassing all the security it's
something like you're buying a lock and
you have not closing it properly or
maybe you're not even locking it so we
don't want to do that right so let's
Implement so how do we secure it how do
we provide that uh layer the first thing
I want to do is I will Implement
different security I want to achieve
that login form I want to maybe uh send
the request through the post Postman uh
but the first thing I want to do is I
want to disable the csrf so let's do
that so I will go back to http because
that's the object which using which you
are creating this build right so we have
to make some changes in this object of
HTTP which is the object of HTTP
security and in this the first thing I
will do is I will say see
srf I want to disable this right in the
initial days it was very simple you can
simply say uh csrf do disable but it
will not work now in Spring six uh
things are bit different now I will show
you this in two steps one using the
Lambda syntax and one without it with
lambra it becomes very easy to read and
write but then if you want to understand
what is happening behind the scene we'll
go for imperative as well so here I'm
I'm saying hp. csrf and to disable it I
will use customizer again I'm not
explaining that now I will do that bit
after some time so I will say customizer
do disable so what we doing is we are
disabling the csrf the next thing I want
is even if you write this you're still
you will still not get the login form I
want it to be authorized so if I don't
authorize it anyone can go there and
they can log in so even if I open a new
incognitive mode here so if I go to
incognitive mode and if I say local SC
880 you can still open it so there's no
login restriction now and to achieve
that what I will do is I will say http
do
authorize HTTP request for every request
and people who are good with lamb
expression they know what I'm writing
but in case if you're not familiar I
will show you the imperative style so
request dot any request should be
authenticated so by doing this what we
are doing is no one should be able to
access any page without authentication
so now after making those changes if I
restart my uh ID or the application go
back to the browser Ander refresh and
now you can see it says access to local
host was denied that means
authentication is applied here so now
that means you have to enter username
password but then where you will do that
even if I do that in Postman and let's
try to fetch the homepage here and if I
say send you can see it says forbidden
even if I pass the values you can see
I'm passing the username password it
still says forbidden because you are
sending username password but no way we
are using it here so how do we do that
first of all I want to enable the form
login so yesterday P dot you can use
something called a form login using
customizer dot with default so it will
pick up the default properties and it
will Implement form login now just by
saying form login let's see what happens
so let's go back here and refresh and
you can see we got a form login now is
it working let's try so I will say naven
teliscope and it's working you can see
if I refresh it works so that means the
form login is been implemented so
whatever customization want you want to
do you can do that in The Code by using
the this HTP object but what about if I
try to do that from Postman let's try
from Postman and if I say send okay we
got this status okay and we are happy
about it but look at the response
response is basically a login form why
we got login form here it's because we
are saying form login that's why we got
it so if you want to do that from the
postman in that case you have to add one
more uh thing here which is HTTP do HTTP
basic you have to implement this or you
have to enable this for the postman for
the rest access rest API access so let's
go back here and see if that Postman is
working now says send and you got it so
you can see we got the page cool so we
have used two things one is form login
for the browser and one is HTTP basic so
form login still works now log out will
not work since we're implementing our
own it is expecting you to have your own
login page so log out will not work or
it will it will sign out directly it
will not give you login form so now if I
do naven and the list
okay wrong
password so you can see it is working so
basically uh by doing this we are
enabling that that feature of course you
can disable your form login if you want
uh you can directly use your Postman to
access it uh next thing I want to do is
I want to make sure that you don't see
we are disabling this CSF right now why
we disabling it is because in one of the
video we have talked about different
ways of handling csrf one of them is
what if you make your HTTP stateless and
if you do that you don't have to worry
about the session ID so how do you make
it stateless is you have to say HTTP do
session management and you will take the
session object and you will say session
dot how do you specify that you want to
go for stateless or stateful in that
case you have to use something called a
session creation policy so there's
something called session creation policy
in this you have to say session creation
policy so you can see we have different
options we got never if required
stateless I want to go for stateless
and job done so by doing it stateless
what we are doing is see the problem
with this is you can't login from your
browser with the login form is because
for every request you have to pass the
credentials and when you have a form
login let me show you what on what I'm
talking about uh so if I refresh and if
I say naven and Tesco so it will give
you login form again because now you are
accessing a new resource a new resource
is a new session right new request so
you have to pass this detail every time
but with Postman this will work so if I
go to postman if I say send you can see
this is working and every time you send
a request you will get a new session ID
if you can see the number is changing
here so that's how you get the new
session ID right but if you want this to
work on a browser what you can do is you
can disable your form login because then
you have to maintain your own sessions
and now if I restart let's see what
happened with the browser enter okay so
you can see we got a popup not the login
for a popup and in this popup you can
say nin Tesco enter and now it will work
so not with the form login but HTTP
basic will give you this popup refresh
and I mean if you say enter you will get
new S ID every time cool right so that's
how basically you can uh do this but
again the problem is how all these
things are working so what I will do is
time being I will just comment this
everything and let's see what is
happening behind the scene so comment
why is not a commenting here
comment am I using a wrong uh I don't
know shortcut is that maybe they have
done some changes so now let's
understand what is happening behind the
scene see we understand what is this
object HTTP SEC HTTP object right which
is HTP security and we also know that
method object will have some methods
right so we got csrf and in this we are
passing this customizer and disabled so
what is this thing to understand this
thing let's do that in a imper
imperative way so I will say HTP Dot and
I will use this method which is csrf and
if You observe csrf you can see what it
takes it takes the object of customizer
in fact that's a big name can't even
copy this so yeah we have a big name
customizer uh in in the I mean the type
it takes is csrf configure the type and
again the type is HTTP security I hope I
will remember this U so I will say
customizer so that's a part of security
config package and this will take
csrf
configur and uh it was checking
something I forgot so let me just say
control space again I don't want to do
dictate uh HTTP security object so
inside this it should be HTTP security
so this is a type you have to work with
Okay and then let's create the object of
it because csrf method takes the object
of customizer of type csrf configure of
type HTP security and let's give a name
to it I will say cust or CSF cust cust
CSF equal to and then you have to say
new and the object for this now the
customizer itself is interace you can
see we have the interface and the method
name is customize that means if you are
using this if you want to create the
object of it we have to create a method
you have to define the method of it
using Anonymous in a class okay and in
this particular method you you using
this object I will name I will not use
the name as HTTP configurer uh csrf
configurer I can use any other name I
will say customizer I mean you can use
usern name name right so the name I'm
using here is customizer and using this
object I can do whatever I want now so
using customizer you can you can use
different methods what we are using it
for is disable right now this is the way
you create the object of customizer csrf
configure HTTP security because this
object you to pass inside HTTP do csrf
I'll pass this object and your job is
done so by doing all these things you
are disabling your csrf oh let the task
right now since this is an interface and
this is a functional interface if I show
you configure this is a function
interface which means you can use lambra
here and people who are familiar with
lambra they know how to create lambra
it's very simple you create uh you
remove the extra stuff and I mean if you
don't know lambra just search for lambra
expression on YouTube or telis lambra
Java lambra that should make sense so
you can replace the entire code this
this entire code with one line so this
line here which I'm which I've written
is equal to this number of
lines oh we can do the same thing for
authorized request let's let's try that
uh HTTP do
authorize HTTP request and look what it
is asking you for look at the name
customizer authorization manager request
matcher registry and then you have to
create object for this and then you have
to pass it in the method like authorized
HTTP request same goes for HTTP basic
let's try for that HTTP basic it is
asking you for the object of again
customizer but since we want to go for
default configuration we are not
changing anything we are saying
customizer do with defaults so it will
pick up the default settings and that's
how it is working behind the scene and
now you know what is happening behind so
for all the methods here same thing you
have to implement certain uh interface
and Define the method and pass the
object here uh another thing which you
can do here is uh instead of doing all
these things one by one you can use a
builder pattern what I'm saying is
remove this semicolon and remove this
HTTP so you can just add at the end
something like this so HTTP dot
csrf that particular setting then
authorize request and then I will just
put that below somewhere okay what's
wrong with my uh ID settings all the
settings have been
changed this is weird Okay I'll just say
enter here remove the semicolon and now
you can put this after this so you can
see for one object you are applying
different settings I can remove this and
the same thing goes for this part cut
and paste it here just that you don't
have to put semicolon at the end and put
it together if it is Big you can just
Center here to make it more readable and
remove this so by doing this you are
making it more readable and in proper
sequence so this is this is called build
a pattern so for this object you are
doing this then you are doing this you
know we when you have a belt in the
factory where the object passes from one
machine to other machine same thing is
happening here one object is passing to
different methods and customizing it in
fact what you can also do is you can
directly say return here then you don't
have to write return again it's just
that at the end have to say
dot build even this looks cool so that's
it uh let me just run this after making
all those changes I hope this will work
if you see a Waring here just that it is
saying you to use method reference in of
lambra uh you can replace this uh method
reference of Lambda to Method reference
even that works okay this start done
let's verify from the postman H this
you're getting the response maybe also
try to work with students if you're
getting all the students and you got it
okay let's also see if the post request
is working so I will say post you can
see we have a post request here uh I'm
sending the headers okay we are sending
CSF token let's let's let's not send it
and done you can see it is working so
even without the token it is working
because we are disabling the csrf
request or csrf setting so yeah that's
it from this where we talked about
different settings or different things
you can do the reason we are doing this
is because in the upcoming videos we
have to do a lot of changes right
working with the uh user username
password coming from database working
with uh JWT and different stuff so I
hope you're excited for the entire
series I'm enjoying it I hope you are if
you are let me know in the comments and
see you in the next video bye-bye right
Посмотреть больше похожих видео
5.0 / 5 (0 votes)