SecurityConfig.java
package com.ivoronline.springboot_security_expression_preauthorized.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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
@EnableGlobalMethodSecurity(prePostEnabled = true)
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)
//REDIRECT TO LOGIN FORM
httpSecurity.formLogin();
}
}
MyController.java
package com.ivoronline.springboot_security_expression_preauthorized.controllers;
import org.springframework.security.access.prepost.PreAuthorize;
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("/endPoint1")
public String ep1() { return "endPoint1"; }
@ResponseBody
@RequestMapping("/endPoint2")
public String ep2() { return "endPoint2"; }
@PreAuthorize("hasRole('ADMIN')")
@ResponseBody
@RequestMapping("/endPoint3")
public String ep3() { return "endPoint3"; }
@PreAuthorize("hasAnyRole('ADMIN', 'USER')")
@ResponseBody
@RequestMapping("/endPoint4")
public String ep4() { return "endPoint4"; }
}