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.

This example will inherit from source code of the tutorial Spring MVC RESTFul Web Service CRUD Example.

Other interesting posts you may like

Table of conents:
1. Configure Basic Authentication with Spring Security
2. Spring REST API
3. Deploy Spring Security Basic Authentication Example

Configure Basic Authentication with Spring Security
Here, we have to enable the Basic Authentication in Spring Security via two steps.

1. Configures HTTP Basic authentication.

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

Spring Security Basic Authentication Example using Annotation json

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

Spring Security Basic Authentication Example using Annotation denied

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

Spring Security Basic Authentication Example using Annotation success

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

Download complete source code, click link below

Spring-Basic-Authentication.zip (76 downloads)

2 thoughts on “Spring Security Basic Authentication Example

Leave a Comment

*

Please share it if you found this useful
Hide Buttons