DEV Community

Ginto P
Ginto P

Posted on

Spring Security Basics: Implementing Authentication and Authorization-PART 2

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:

  1. Add the Spring Security dependency

  2. Restart the application

  3. 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'
}
Enter fullscreen mode Exit fullscreen mode

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.

Image description

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.

Image description

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 Classpath

  • One 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.

  1. http://localhost:8080/api/hello

  2. http://localhost:8080/api/protected

  3. http://localhost:8080/api/admin


Top comments (0)