Configure spring security Authorization

  • HttpSecurity helps to setup Authorization in SpringSecurity
  • We do that by overriding WebSecurityConfigurerAdapter method called configure(HttpSecurity http)
  • While chaining the HttpSecurity object, go with the most restrective urls first and end it with the least restrictive urls

Code :

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.2.5.RELEASE'
    id 'io.spring.dependency-management' version '1.0.7.RELEASE'
}

repositories {
    jcenter()
}

dependencies {
    implementation 'com.google.guava:guava:28.0-jre'
    testImplementation 'junit:junit:4.12'
    implementation 'org.springframework.boot:spring-boot-dependencies:2.0.5.RELEASE'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
	implementation 'org.springframework.boot:spring-boot-starter-security:2.2.4.RELEASE'

    components {
        withModule('org.springframework:spring-beans') {
            allVariants {
                withDependencyConstraints {
                    it.findAll { it.name == 'snakeyaml' }.each { it.version { strictly '1.19' } }
                }
            }
        }
    }
}

task runJar{
	dependsOn 'assemble'
	dependsOn 'jar'
	doLast{
  		javaexec { 
    		main="-jar";
    		args = [
            	"build/libs/"+rootProject.name+".jar"
           	]
		} 
	}
}

App.java

package SpringSecurityAuthorization;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

AppController.java

package SpringSecurityAuthorization;

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

@RestController
public class AppController {
	
	@GetMapping("/")
	public String home() {
		return "Welcome home";
	}
	
	@GetMapping("/user")
	public String user() {
		return "Welcome User";
	}
	
	@GetMapping("/admin")
	public String admin() {
		return "Welcome Admin";
	}
}

SecurityConfig.java

package SpringSecurityAuthorization;

import org.springframework.context.annotation.Bean;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity //inform spring that this is a spring security configuration class
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//		super.configure(auth);
		auth.inMemoryAuthentication()
			.withUser("tyson")
			.password("tyson")
			.roles("USER")
			.and()//returns the object of inMemoryAuthentication
			.withUser("justin")
			.password("justin")
			.roles("ADMIN");
	}
	
	
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//super.configure(http);
		http.authorizeRequests()
			.antMatchers("/admin").hasRole("ADMIN")
			.antMatchers("/user").hasAnyRole("USER","ADMIN")
			.antMatchers("/","static/css","static/js").permitAll()
			//.antMatchers("/**").hasAnyRole("USER","ADMIN")//matches all paths in the current level and nested levels below it
			.and().formLogin();//oauth2Login,openidLogin,httpBasic
	}



	@Bean
	public PasswordEncoder getPasswordEncoder() {
		return NoOpPasswordEncoder.getInstance();
		//return new BCryptPasswordEncoder();
	}
	
	
	
	public static void main(String[] args) {
		String hasedPass = new BCryptPasswordEncoder().encode("tyson");
		System.out.println(hasedPass);
	}
}

Methods of HttpSecurity :

1. authorizeRequests()

Allows restricting access based upon the HttpServletRequest

Example :

@Override
        protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin();
        }

2. antMatchers(String pattern)

This method is chained with authorizeRequest() to match with the pattern

3. .exceptionHandling()

For an example refer :

https://www.devglan.com/spring-security/exception-handling-in-spring-security

4. sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

The purpose of REST (ST = Statetransfer) is to make the calls stateless i.e server never stores the session information in memeory or JDBC but state is transferred to the client itself inform of JWT hence we need to disable the sessionManagement()

Leave a Comment