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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.javabycode.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private static String REALM = "EXAMPLE_REALM"; @Autowired public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("javabycode").password("123456").roles("USER"); auth.inMemoryAuthentication().withUser("admin").password("admin123").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().antMatchers("/user/**").hasRole("ADMIN").and().httpBasic() .realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint()) // No need session. .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Bean public MyBasicAuthenticationEntryPoint getBasicAuthEntryPoint() { return new MyBasicAuthenticationEntryPoint(); } /* To allow Pre-flight [OPTIONS] request from browser */ @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**"); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com.javabycode.security; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { @Override public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException { //Authentication failed response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + ""); PrintWriter writer = response.getWriter(); writer.println("HTTP Status 401 : " + authException.getMessage()); } @Override public void afterPropertiesSet() throws Exception { setRealmName("EXAMPLE_REALM"); super.afterPropertiesSet(); } } |
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
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 (507 downloads)
Hello,
Thanks for this great tutorial.
Do you have the xml configuration ?
Here you are https://javabycode.com/spring-framework-tutorial/spring-security/spring-security-4-authentication-annotation-xml-example.html