Spring Security Basic Example

First, go to the https://start.spring.io/ and create the spring boot project by adding all required dependies to enable SpringSecurity in SpringBoot application. Download and import the project into the IDE.


Write a simple GetMapping inside the controller like below:


                    @RestController
                    @RequestMapping("/api/v1/auth")
                    public class HelloSpringSecurityController {
                    
                        @GetMapping("/message")
                        public String getMessage() {
                            return "Welcome to spring security basic example";
                        }
                    }                                                
                    

Now run the application then you will see the auto generated password in the console logs like below:


If we try to access the endpoint (http://localhost:8096/api/v1/auth/message) through Postman will receive 401-Unauthorized error. The same endpoint if we try to access through any browser then it will navigate to the login page. We can login using default username as user and the generated password (which will be generated while starting the service) from the applicaiton console.


Once we login then will be able to see the result.
Full source code is available in follwong GitHub repository: Spring Security Basic example

If we want to see the see the result using Postman call, Inside the postman tool first we need to navigate the authorization tab and select the Basic Auth type. Then next enter the default username as user and the generated password (which will be generated while starting the service) from the applicaiton console. Then send the request you will be able to see the output like below