Create Project: springboot_security_expressions_api (add Spring Boot Starters from the table)
Edit File: application.properties (specify Username, Password, Role)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside controllers package)
Create Package: config (inside main package)
– Create Class: SecurityConfig.java (inside config package)
application.properties
# SECURITY
spring.security.user.name = myuser
spring.security.user.password = mypassword
spring.security.user.roles = USER, LOADE
MyController.java
package com.ivoronline.springboot_security_urlpatternmatching.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody @RequestMapping("/hello") public String sayHello() { return "hello"; }
@ResponseBody @RequestMapping("/endPoint1") public String ep1() { return "endPoint1"; }
@ResponseBody @RequestMapping("/endPoint2") public String ep2() { return "endPoint2"; }
@ResponseBody @RequestMapping("/endPoint3") public String ep3() { return "endPoint3"; }
@ResponseBody @RequestMapping("/endPoint4") public String ep4() { return "endPoint4"; }
@ResponseBody @RequestMapping("/sublevel/endPoint5") public String ep5() { return "endPoint5"; }
}
SecurityConfig.java
package com.ivoronline.springboot_security_urlpatternmatching.config;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//SPECIFY ACCESS TO ENDPOINTS
httpSecurity.authorizeRequests()
.antMatchers("/endPoint1").denyAll() //No access (even after log in)
.antMatchers("/endPoint2").permitAll() //No log in (anonymous access)
.antMatchers("/endPoint3").hasRole("ADMIN") //ADMIN ROLE can access AFTER log in
.antMatchers("/endPoint4").hasAnyRole("ADMIN", "USER"); //ADMIN/USER ROLE can access AFTER log in
//REDIRECT TO LOGIN FORM
httpSecurity.formLogin();
}
}