Spring boot security

Fri, Nov 29, 2019

Read in 2 minutes

What will you learn here? In this blog, you will learn how to use a spring boot security project.

Create a Spring Boot Project:

dependencies added springboot

Then We have to create WebSecurityConfig.java to configure the security details.

package com.theprogrammerguide.springbootsecurityproject;
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;
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
	@Override
	protected void configure(AuthenticationManagerBuilder auth  ) throws Exception {

		PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
		auth.inMemoryAuthentication()
		.withUser("test").password(encoder.encode("test")).roles("USER");
	}
	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception{
		httpSecurity
        .authorizeRequests()
        .anyRequest()
        .fullyAuthenticated()
        .and()
        .httpBasic();
		httpSecurity.csrf().disable();
	}
}

WebSecurityConfig.java springbootsecurity

Create a Hello Service to check the security

package com.theprogrammerguide.springbootsecurityproject.service;

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

@RestController
public class HelloService {
	@GetMapping("/index")
	public String sayHello(){
	return "Hello ";
	}
}

In the HelloService, we have /index mapping to return Hello.

Request without Adding Authentication Details: Postman securitypostman

Request with Authentication Details :

successful response in postman tool securitypostmansuccess