Enable Spring Security
In the previous section, we built a foundational application. In this section, we will enable Spring Security in the application. For that let's do the following steps:
Add the Spring Security dependency
Restart the application
Verify Spring Security is enabled
Add the Spring Security dependency
To Enable spring security the library org.springframework.boot:spring-boot-starter-security
must be present in the Classpath. This can be achieved by adding the library as a dependency in the build.gradle
file. Note the first item in the dependencies list
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
Restart the application
Just restart the application. Then go to the next step.
Verify Spring Security is enabled
Open the browser and attempt to access the API endpoints. If a login page appears for each endpoint you try to access, it confirms that Spring Security is enabled and functioning as expected.
Yeah that's it.
At this point the application is running with the default implementation of Spring Security. You will not able to access the APIs without entering login credentials. In the default implementation, Spring Security provides a default user with username as “user” and a randomly generated password . This generated password can be obtained from the console logs.
Note the line Using generated security password: dd05314d-2856-48b4-9c81-fcc480e0b4bf
The default behavior of Spring Security, unless configured otherwise is as follows:
All end points are protected by default when the library
org.springframework.boot:spring-boot-starter-security
is present in the ClasspathOne cannot access the resources without authentication.
Provides a default user that can be overridden.
In this default setup the APIs can be accessed by entering the username as user and password as the one which is printed in the console. Try accessing the APIs by entering the default credentials.
Top comments (0)