Categories
security spring-boot

spring-boot-security using http basic authentication

In this post, we will learn about spring-boot-security using http basic authentication

In this tutorial we will use spring security where we can enable security for our spring applications

Dependency
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Add above dependency in your pom.xml

In this example, we are creating two rest endpoints, which I named as hello and hi

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

	@GetMapping("hello")
	public String getHello() {
		return "Hello";
	}

	@GetMapping("hi")
	public String getHi() {
		return "Hi";
	}

}

Now we can create new class SecurityConfig.java to configure our security
we need to add @Configuration @EnableWebSecurityannotations in our SecurityConfig.java and also we need to extend WebSecurityConfigurerAdapter 

And also we need to override two configure methods in SecurityConfig.java

In the first configure method we need to configure user and role details, Here I added two users with two roles 


import org.springframework.context.annotation.Configuration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
		auth.inMemoryAuthentication()
		.withUser("admin").password(encoder.encode("password")).roles("ADMIN").and()
		.withUser("user").password(encoder.encode("pass")).roles("USER");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
		.authorizeRequests().antMatchers("/hello").permitAll()
		.anyRequest().authenticated().and().httpBasic();
		
	}

}

In the above snippet, we allowed /hello endpoint and remaining endpoints are authenticated with httpBasic authentication

We are using PasswordEncoder to encode the password

Run the application as spring boot application

Testing

Conclusion

The above example is a simple spring security authentication using http basic. Here we added user details in-memory authentication

Github

https://github.com/rkumar9090/spring-security