BAEL-3495 Code for Deny of Missing Pre/PostAuthorize annotation

- Moved classes around so that the scans do not collide
- Make sure the LiveTest actually stops when done
- Removed some useless gitignore / README parts.
This commit is contained in:
Martin van Wingerden 2019-12-19 18:58:07 +01:00
parent 93b79e272d
commit 03a34d5cf6
20 changed files with 182 additions and 54 deletions

View File

@ -1,13 +1 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
target/

View File

@ -8,8 +8,6 @@ This module contains articles about core Spring Security
- [Introduction to Spring Method Security](https://www.baeldung.com/spring-security-method-security)
- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy)
### @PreFilter and @PostFilter annotations
#### Build the Project
### Build the Project
`mvn clean install`

View File

@ -12,9 +12,6 @@ import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@SpringBootApplication
@EnableJpaRepositories("com.baeldung.repository")
@ComponentScan("com.baeldung")
@EntityScan("com.baeldung.entity")
public class App extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
@ -31,19 +28,16 @@ public class App extends SpringBootServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.auditing;
package com.baeldung.app.auditing;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.security.AbstractAuthorizationAuditListener;

View File

@ -1,4 +1,4 @@
package com.baeldung.auditing;
package com.baeldung.app.auditing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,11 +1,11 @@
package com.baeldung.config;
package com.baeldung.app.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.baeldung.entity.Task;
import com.baeldung.repository.TaskRepository;
import com.baeldung.app.entity.Task;
import com.baeldung.app.repository.TaskRepository;
@Component
public class DatabaseLoader implements CommandLineRunner {

View File

@ -1,4 +1,4 @@
package com.baeldung.config;
package com.baeldung.app.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

View File

@ -1,4 +1,4 @@
package com.baeldung.controller;
package com.baeldung.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.baeldung.entity.Task;
import com.baeldung.service.TaskService;
import com.baeldung.app.entity.Task;
import com.baeldung.app.service.TaskService;
@Controller
@RequestMapping("api/tasks")

View File

@ -1,4 +1,4 @@
package com.baeldung.entity;
package com.baeldung.app.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

View File

@ -1,8 +1,8 @@
package com.baeldung.repository;
package com.baeldung.app.repository;
import org.springframework.data.repository.CrudRepository;
import com.baeldung.entity.Task;
import com.baeldung.app.entity.Task;
public interface TaskRepository extends CrudRepository<Task, Long> {

View File

@ -1,12 +1,12 @@
package com.baeldung.service;
package com.baeldung.app.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.stereotype.Service;
import com.baeldung.entity.Task;
import com.baeldung.repository.TaskRepository;
import com.baeldung.app.entity.Task;
import com.baeldung.app.repository.TaskRepository;
@Service
public class TaskService {

View File

@ -0,0 +1,49 @@
package com.baeldung.denyonmissing;
import static org.springframework.security.access.annotation.Jsr250SecurityConfig.DENY_ALL_ATTRIBUTE;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.method.AbstractFallbackMethodSecurityMetadataSource;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
public class CustomPermissionAllowedMethodSecurityMetadataSource extends AbstractFallbackMethodSecurityMetadataSource {
@Override
protected Collection<ConfigAttribute> findAttributes(Class<?> clazz) {
return null;
}
@Override
protected Collection<ConfigAttribute> findAttributes(Method method, Class<?> targetClass) {
Annotation[] annotations = AnnotationUtils.getAnnotations(method);
List<ConfigAttribute> attributes = new ArrayList<>();
// if the class is annotated as @Controller we should by default deny access to every method
if (AnnotationUtils.findAnnotation(targetClass, Controller.class) != null) {
attributes.add(DENY_ALL_ATTRIBUTE);
}
if (annotations != null) {
for (Annotation a : annotations) {
// but not if the method has at least a PreAuthorize or PostAuthorize annotation
if (a instanceof PreAuthorize || a instanceof PostAuthorize) {
return null;
}
}
}
return attributes;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.denyonmissing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DenyApplication {
public static void main(String[] args) {
SpringApplication.run(DenyApplication.class, args);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.denyonmissing;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.method.MethodSecurityMetadataSource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class DenyMethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
return new CustomPermissionAllowedMethodSecurityMetadataSource();
}
@Bean
public UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
User.withUsername("user").password("{noop}password").roles("USER").build(),
User.withUsername("guest").password("{noop}password").roles().build()
);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.denyonmissing;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DenyOnMissingController {
@GetMapping(path = "hello")
@PreAuthorize("hasRole('USER')")
public String hello() {
return "Hello world!";
}
@GetMapping(path = "bye")
public String bye() {
return "Bye bye world!";
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.app;
import org.junit.Test;
import org.junit.runner.RunWith;

View File

@ -1,4 +1,4 @@
package com.baeldung.test;
package com.baeldung.app.test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@ -22,7 +22,7 @@ import org.springframework.web.context.WebApplicationContext;
import com.baeldung.app.App;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@SpringBootTest(classes = App.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LiveTest {

View File

@ -0,0 +1,53 @@
package com.baeldung.denyonmissing;
import static org.hamcrest.core.Is.isA;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DenyApplication.class)
public class DenyOnMissingControllerIntegrationTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.build();
}
@Test
@WithMockUser(username = "user")
public void givenANormalUser_whenCallingHello_thenAccessDenied() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello world!"));
}
@Test
@WithMockUser(username = "user")
public void givenANormalUser_whenCallingBye_thenAccessDenied() throws Exception {
expectedException.expectCause(isA(AccessDeniedException.class));
mockMvc.perform(get("/bye"));
}
}

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear