Spring Security Basic Authentication Example

This tutorial shows you how to create Spring Security Basic Authentication Example using Annotation. With this example you are easy to secure your application using Basic Authentication.

You are similar to the REST API via the tutorial Spring MVC RESTFul Web Service CRUD Example. Now i make sure that you are concerned about the security issue of this application. How can we secure this application? Of course we can do that by using Basic Authentication or OAuth2 security solution.

2. Configure authentication entry point: this entry point will be triggered if the authentication fails and it will response to client error message. Actually, we create the MyBasicAuthenticationEntryPoint class which is extended from BasicAuthenticationEntryPoint for customizing the response message.

Spring REST API Here, we reuse source code of the tutorial Spring MVC RESTFul Web Service CRUD Example to build Spring REST API. So we don’t introduce about how to create Rest Controller here. Notices that we have to put two above classes and spring security dependencies into the current source code. You can refer to the completely project by downloading attachment.

Deploy Spring Security Basic Authentication Example After building the project by maven we deploy the file war on application server (Tomcat 8 for example). Run the URL http://localhost:8080/spring-basic-authentication/fruits and the authentication popup appears like below

We fill the credentials (javabycode/123456) with user role and click Login. The response appears with HTTP Status 403 – Access is denied like below

Next, we fill the credentials (admin/admin123) with admin role and click Login. The response appears with the json

format. It mean that this URL is applied for the admin role. The screen shot looks like below

That’s all on tutorial how to create Spring Security Basic Authentication Example. If you have any opinion please leave comment.