[BAEL-9552] - Create spring-security-modules folder
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.app;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
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);
|
||||
}
|
||||
|
||||
public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
@Override
|
||||
protected javax.servlet.Filter[] getServletFilters() {
|
||||
DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy();
|
||||
delegateFilterProxy.setTargetBeanName("loggingFilter");
|
||||
return new Filter[] { delegateFilterProxy };
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.auditing;
|
||||
|
||||
import org.springframework.boot.actuate.audit.AuditEvent;
|
||||
import org.springframework.boot.actuate.security.AbstractAuthorizationAuditListener;
|
||||
import org.springframework.security.access.event.AbstractAuthorizationEvent;
|
||||
import org.springframework.security.access.event.AuthorizationFailureEvent;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class ExposeAttemptedPathAuthorizationAuditListener extends AbstractAuthorizationAuditListener {
|
||||
|
||||
public static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE";
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(AbstractAuthorizationEvent event) {
|
||||
if (event instanceof AuthorizationFailureEvent) {
|
||||
onAuthorizationFailureEvent((AuthorizationFailureEvent) event);
|
||||
}
|
||||
}
|
||||
|
||||
private void onAuthorizationFailureEvent(AuthorizationFailureEvent event) {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("type", event.getAccessDeniedException().getClass().getName());
|
||||
data.put("message", event.getAccessDeniedException().getMessage());
|
||||
data.put("requestUrl", ((FilterInvocation)event.getSource()).getRequestUrl() );
|
||||
if (event.getAuthentication().getDetails() != null) {
|
||||
data.put("details", event.getAuthentication().getDetails());
|
||||
}
|
||||
publish(new AuditEvent(event.getAuthentication().getName(), AUTHORIZATION_FAILURE,
|
||||
data));
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.auditing;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.actuate.audit.AuditEvent;
|
||||
import org.springframework.boot.actuate.audit.listener.AuditApplicationEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class LoginAttemptsLogger {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(LoginAttemptsLogger.class);
|
||||
|
||||
@EventListener
|
||||
public void auditEventHappened(AuditApplicationEvent auditApplicationEvent) {
|
||||
AuditEvent auditEvent = auditApplicationEvent.getAuditEvent();
|
||||
LOGGER.info("Principal " + auditEvent.getPrincipal() + " - " + auditEvent.getType());
|
||||
|
||||
WebAuthenticationDetails details = (WebAuthenticationDetails) auditEvent.getData().get("details");
|
||||
LOGGER.info(" Remote IP address: " + details.getRemoteAddress());
|
||||
LOGGER.info(" Session Id: " + details.getSessionId());
|
||||
LOGGER.info(" Request URL: " + auditEvent.getData().get("requestUrl"));
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.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;
|
||||
|
||||
@Component
|
||||
public class DatabaseLoader implements CommandLineRunner {
|
||||
|
||||
@Autowired
|
||||
private TaskRepository taskRepository;
|
||||
|
||||
@Override
|
||||
public void run(String... strings) throws Exception {
|
||||
this.taskRepository.save(new Task("Send a fax", "pam"));
|
||||
this.taskRepository.save(new Task("Print a document", "pam"));
|
||||
this.taskRepository.save(new Task("Answer the phone", "pam"));
|
||||
this.taskRepository.save(new Task("Call a client", "jim"));
|
||||
this.taskRepository.save(new Task("Organize a meeting", "michael"));
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
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;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests().antMatchers("/css/**", "/js/**", "/loggedout").permitAll().anyRequest().authenticated().and().httpBasic().and().logout().disable().csrf().disable();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("jim").password(passwordEncoder().encode("jim")).roles("USER", "ACTUATOR")
|
||||
.and().withUser("pam").password(passwordEncoder().encode("pam")).roles("USER")
|
||||
.and().withUser("michael").password(passwordEncoder().encode("michael")).roles("MANAGER");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
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;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("api/tasks")
|
||||
public class TaskController {
|
||||
|
||||
@Autowired
|
||||
private TaskService taskService;
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET)
|
||||
public ResponseEntity<Iterable<Task>> findAllTasks() {
|
||||
Iterable<Task> tasks = taskService.findAll();
|
||||
|
||||
return ResponseEntity.ok().body(tasks);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
|
||||
public ResponseEntity<Iterable<Task>> addTasks(@RequestBody Iterable<Task> newTasks) {
|
||||
Iterable<Task> tasks = taskService.save(newTasks);
|
||||
|
||||
return ResponseEntity.ok().body(tasks);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.entity;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Task {
|
||||
private @Id @GeneratedValue Long id;
|
||||
private String description;
|
||||
|
||||
private String assignee;
|
||||
|
||||
public Task() {
|
||||
}
|
||||
|
||||
public Task(String description, String assignee) {
|
||||
this.description = description;
|
||||
this.assignee = assignee;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getAssignee() {
|
||||
return assignee;
|
||||
}
|
||||
|
||||
public void setAssignee(String assignee) {
|
||||
this.assignee = assignee;
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.filter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component("loggingFilter")
|
||||
public class CustomFilter implements Filter {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(CustomFilter.class);
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig config) throws ServletException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletRequest req = (HttpServletRequest) request;
|
||||
LOGGER.info("Request Info : " + req);
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
// cleanup code, if necessary
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.methodsecurity.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@PreAuthorize("hasRole('VIEWER')")
|
||||
public @interface IsViewer {
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.methodsecurity.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
|
||||
|
||||
@Configuration
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
|
||||
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
|
||||
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.methodsecurity.entity;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class CustomUser extends User {
|
||||
|
||||
private String nickName;
|
||||
|
||||
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
|
||||
super(username, password, authorities);
|
||||
}
|
||||
|
||||
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities, String nickName) {
|
||||
super(username, password, authorities);
|
||||
this.nickName = nickName;
|
||||
}
|
||||
|
||||
public String getNickName() {
|
||||
return nickName;
|
||||
}
|
||||
|
||||
public void setNickName(String nickName) {
|
||||
this.nickName = nickName;
|
||||
}
|
||||
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.methodsecurity.repository;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.methodsecurity.entity.CustomUser;
|
||||
|
||||
@Service
|
||||
public class UserRoleRepository {
|
||||
|
||||
static Map<String, CustomUser> DB_BASED_USER_MAPPING;
|
||||
|
||||
static {
|
||||
DB_BASED_USER_MAPPING = new LinkedHashMap<>();
|
||||
DB_BASED_USER_MAPPING.put("jane", new CustomUser("jane", "1234", getGrantedAuthorities("ROLE_USER", "ROLE_VIEWER"), "jane"));
|
||||
DB_BASED_USER_MAPPING.put("john", new CustomUser("john", "1234", getGrantedAuthorities("ROLE_EDITOR", "ROLE_ADMIN"), "jane"));
|
||||
DB_BASED_USER_MAPPING.put("jack", new CustomUser("jack", "1234", getGrantedAuthorities("ROLE_USER", "ROLE_REVIEWER"), "jane"));
|
||||
}
|
||||
|
||||
private static List<GrantedAuthority> getGrantedAuthorities(String... roles) {
|
||||
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
|
||||
for (String role : roles) {
|
||||
authorities.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
|
||||
public CustomUser loadUserByUserName(String username) {
|
||||
if (DB_BASED_USER_MAPPING.containsKey(username)) {
|
||||
return DB_BASED_USER_MAPPING.get(username);
|
||||
}
|
||||
throw new UsernameNotFoundException("User " + username + " cannot be found");
|
||||
}
|
||||
|
||||
public boolean isValidUsername(String username) {
|
||||
return DB_BASED_USER_MAPPING.containsKey(username);
|
||||
}
|
||||
|
||||
public boolean isValidRole(String roleName) {
|
||||
return roleName.startsWith("ROLE_");
|
||||
}
|
||||
|
||||
public List<String> getAllUsernames() {
|
||||
List<String> usernames = new ArrayList<>();
|
||||
usernames.add("jane");
|
||||
usernames.add("john");
|
||||
usernames.add("jack");
|
||||
return usernames;
|
||||
}
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.methodsecurity.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.methodsecurity.repository.UserRoleRepository;
|
||||
|
||||
@Service("userDetailService")
|
||||
public class CustomUserDetailsService implements UserDetailsService {
|
||||
|
||||
@Autowired
|
||||
UserRoleRepository userRoleRepo;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) {
|
||||
return userRoleRepo.loadUserByUserName(username);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.methodsecurity.service;
|
||||
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
public class SystemService {
|
||||
|
||||
public String getSystemYear(){
|
||||
return "2017";
|
||||
}
|
||||
|
||||
public String getSystemDate(){
|
||||
return "31-12-2017";
|
||||
}
|
||||
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package com.baeldung.methodsecurity.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.security.access.prepost.PostAuthorize;
|
||||
import org.springframework.security.access.prepost.PostFilter;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.access.prepost.PreFilter;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.methodsecurity.annotation.IsViewer;
|
||||
import com.baeldung.methodsecurity.entity.CustomUser;
|
||||
import com.baeldung.methodsecurity.repository.UserRoleRepository;
|
||||
|
||||
@Service
|
||||
public class UserRoleService {
|
||||
|
||||
@Autowired
|
||||
UserRoleRepository userRoleRepository;
|
||||
|
||||
@Secured("ROLE_VIEWER")
|
||||
public String getUsername() {
|
||||
SecurityContext securityContext = SecurityContextHolder.getContext();
|
||||
return securityContext.getAuthentication().getName();
|
||||
}
|
||||
|
||||
@Secured({ "ROLE_VIEWER", "ROLE_EDITOR" })
|
||||
public boolean isValidUsername(String username) {
|
||||
return userRoleRepository.isValidUsername(username);
|
||||
}
|
||||
|
||||
@RolesAllowed("ROLE_VIEWER")
|
||||
public String getUsername2() {
|
||||
SecurityContext securityContext = SecurityContextHolder.getContext();
|
||||
return securityContext.getAuthentication().getName();
|
||||
}
|
||||
|
||||
@RolesAllowed({ "ROLE_VIEWER", "ROLE_EDITOR" })
|
||||
public boolean isValidUsername2(String username) {
|
||||
return userRoleRepository.isValidUsername(username);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_VIEWER')")
|
||||
public String getUsernameInUpperCase() {
|
||||
return getUsername().toUpperCase();
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('SYS_ADMIN')")
|
||||
public String getUsernameLC() {
|
||||
return getUsername().toLowerCase();
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_VIEWER') or hasRole('ROLE_EDITOR')")
|
||||
public boolean isValidUsername3(String username) {
|
||||
return userRoleRepository.isValidUsername(username);
|
||||
}
|
||||
|
||||
@PreAuthorize("#username == authentication.principal.username")
|
||||
public String getMyRoles(String username) {
|
||||
SecurityContext securityContext = SecurityContextHolder.getContext();
|
||||
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
@PostAuthorize("#username == authentication.principal.username")
|
||||
public String getMyRoles2(String username) {
|
||||
SecurityContext securityContext = SecurityContextHolder.getContext();
|
||||
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
@PostAuthorize("returnObject.username == authentication.principal.nickName")
|
||||
public CustomUser loadUserDetail(String username) {
|
||||
return userRoleRepository.loadUserByUserName(username);
|
||||
}
|
||||
|
||||
@PreFilter("filterObject != authentication.principal.username")
|
||||
public String joinUsernames(List<String> usernames) {
|
||||
return usernames.stream().collect(Collectors.joining(";"));
|
||||
}
|
||||
|
||||
@PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames")
|
||||
public String joinUsernamesAndRoles(List<String> usernames, List<String> roles) {
|
||||
return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";"));
|
||||
}
|
||||
|
||||
@PostFilter("filterObject != authentication.principal.username")
|
||||
public List<String> getAllUsernamesExceptCurrent() {
|
||||
return userRoleRepository.getAllUsernames();
|
||||
}
|
||||
|
||||
@IsViewer
|
||||
public String getUsername4() {
|
||||
SecurityContext securityContext = SecurityContextHolder.getContext();
|
||||
return securityContext.getAuthentication().getName();
|
||||
}
|
||||
|
||||
@PreAuthorize("#username == authentication.principal.username")
|
||||
@PostAuthorize("returnObject.username == authentication.principal.nickName")
|
||||
public CustomUser securedLoadUserDetail(String username) {
|
||||
return userRoleRepository.loadUserByUserName(username);
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.repository;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.baeldung.entity.Task;
|
||||
|
||||
public interface TaskRepository extends CrudRepository<Task, Long> {
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.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;
|
||||
|
||||
@Service
|
||||
public class TaskService {
|
||||
|
||||
@Autowired
|
||||
private TaskRepository taskRepository;
|
||||
|
||||
@PostFilter("hasRole('MANAGER') or filterObject.assignee == authentication.name")
|
||||
public Iterable<Task> findAll() {
|
||||
return taskRepository.findAll();
|
||||
}
|
||||
|
||||
@PreFilter("hasRole('MANAGER') or filterObject.assignee == authentication.name")
|
||||
public Iterable<Task> save(Iterable<Task> entities) {
|
||||
return taskRepository.saveAll(entities);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
spring.main.allow-bean-definition-overriding=true
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
|
||||
version="3.1">
|
||||
|
||||
<filter>
|
||||
<filter-name>loggingFilter</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
</filter>
|
||||
|
||||
<filter-mapping>
|
||||
<filter-name>loggingFilter</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
</web-app>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.app.App;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = App.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.methodsecurity;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.methodsecurity.service.SystemService;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration
|
||||
public class ClassLevelSecurityIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
SystemService systemService;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.methodsecurity.*")
|
||||
public static class SpringConfig {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username="john",roles={"ADMIN"})
|
||||
public void givenRoleAdmin_whenCallGetSystemYear_return2017(){
|
||||
String systemYear = systemService.getSystemYear();
|
||||
assertEquals("2017",systemYear);
|
||||
}
|
||||
|
||||
@Test(expected=AccessDeniedException.class)
|
||||
@WithMockUser(username="john",roles={"VIEWER"})
|
||||
public void givenRoleViewer_whenCallGetSystemYear_returnAccessDenied(){
|
||||
String systemYear = systemService.getSystemYear();
|
||||
assertEquals("2017",systemYear);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username="john",roles={"ADMIN"})
|
||||
public void givenRoleAdmin_whenCallGetSystemDate_returnDate(){
|
||||
String systemYear = systemService.getSystemDate();
|
||||
assertEquals("31-12-2017",systemYear);
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package com.baeldung.methodsecurity;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.test.context.support.WithAnonymousUser;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.methodsecurity.service.UserRoleService;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration
|
||||
public class MethodSecurityIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
UserRoleService userRoleService;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.methodsecurity.*")
|
||||
public static class SpringConfig {
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = AuthenticationCredentialsNotFoundException.class)
|
||||
public void givenNoSecurity_whenCallGetUsername_thenReturnException() {
|
||||
String userName = userRoleService.getUsername();
|
||||
assertEquals("john", userName);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "john", roles = { "VIEWER" })
|
||||
public void givenRoleViewer_whenCallGetUsername_thenReturnUsername() {
|
||||
String userName = userRoleService.getUsername();
|
||||
assertEquals("john", userName);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "john", roles = { "EDITOR" })
|
||||
public void givenUsernameJohn_whenCallIsValidUsername_thenReturnTrue() {
|
||||
boolean isValid = userRoleService.isValidUsername("john");
|
||||
assertEquals(true, isValid);
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
@WithMockUser(username = "john", roles = { "ADMIN" })
|
||||
public void givenRoleAdmin_whenCallGetUsername_thenReturnAccessDenied() {
|
||||
userRoleService.getUsername();
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
@WithMockUser(username = "john", roles = { "USER" })
|
||||
public void givenRoleUser_whenCallGetUsername2_thenReturnAccessDenied() {
|
||||
userRoleService.getUsername2();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "john", roles = { "VIEWER", "EDITOR" })
|
||||
public void givenRoleViewer_whenCallGetUsername2_thenReturnUsername() {
|
||||
String userName = userRoleService.getUsername2();
|
||||
assertEquals("john", userName);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "john", roles = { "VIEWER" })
|
||||
public void givenUsernameJerry_whenCallIsValidUsername2_thenReturnFalse() {
|
||||
boolean isValid = userRoleService.isValidUsername2("jerry");
|
||||
assertEquals(false, isValid);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "JOHN", authorities = { "SYS_ADMIN" })
|
||||
public void givenAuthoritySysAdmin_whenCallGetUsernameLC_thenReturnUsername() {
|
||||
String username = userRoleService.getUsernameLC();
|
||||
assertEquals("john", username);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
|
||||
public void givenUserJohn_whenCallGetMyRolesWithJohn_thenReturnRoles() {
|
||||
String roles = userRoleService.getMyRoles("john");
|
||||
assertEquals("ROLE_ADMIN,ROLE_USER,ROLE_VIEWER", roles);
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
|
||||
public void givenUserJane_whenCallGetMyRolesWithJane_thenAccessDenied() {
|
||||
userRoleService.getMyRoles("jane");
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
|
||||
public void givenUserJohn_whenCallGetMyRoles2WithJohn_thenReturnRoles() {
|
||||
String roles = userRoleService.getMyRoles2("john");
|
||||
assertEquals("ROLE_ADMIN,ROLE_USER,ROLE_VIEWER", roles);
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
|
||||
public void givenUserJane_whenCallGetMyRoles2WithJane_thenAccessDenied() {
|
||||
userRoleService.getMyRoles2("jane");
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
@WithAnonymousUser
|
||||
public void givenAnomynousUser_whenCallGetUsername_thenAccessDenied() {
|
||||
userRoleService.getUsername();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockJohnViewer
|
||||
public void givenMockedJohnViewer_whenCallGetUsername_thenReturnUsername() {
|
||||
String userName = userRoleService.getUsername();
|
||||
assertEquals("john", userName);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "jane")
|
||||
public void givenListContainCurrentUsername_whenJoinUsernames_thenReturnUsernames() {
|
||||
List<String> usernames = new ArrayList<>();
|
||||
usernames.add("jane");
|
||||
usernames.add("john");
|
||||
usernames.add("jack");
|
||||
String containCurrentUser = userRoleService.joinUsernames(usernames);
|
||||
assertEquals("john;jack", containCurrentUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "john")
|
||||
public void givenListContainCurrentUsername_whenCallJoinUsernamesAndRoles_thenReturnUsernameAndRoles() {
|
||||
List<String> usernames = new ArrayList<>();
|
||||
usernames.add("jane");
|
||||
usernames.add("john");
|
||||
usernames.add("jack");
|
||||
|
||||
List<String> roles = new ArrayList<>();
|
||||
roles.add("ROLE_ADMIN");
|
||||
roles.add("ROLE_TEST");
|
||||
|
||||
String containCurrentUser = userRoleService.joinUsernamesAndRoles(usernames, roles);
|
||||
assertEquals("jane;jack:ROLE_ADMIN;ROLE_TEST", containCurrentUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "john")
|
||||
public void givenUserJohn_whenCallGetAllUsernamesExceptCurrent_thenReturnOtherusernames() {
|
||||
List<String> others = userRoleService.getAllUsernamesExceptCurrent();
|
||||
assertEquals(2, others.size());
|
||||
assertTrue(others.contains("jane"));
|
||||
assertTrue(others.contains("jack"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "john", roles = { "VIEWER" })
|
||||
public void givenRoleViewer_whenCallGetUsername4_thenReturnUsername() {
|
||||
String userName = userRoleService.getUsername4();
|
||||
assertEquals("john", userName);
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
@WithMockUser(username = "john")
|
||||
public void givenDefaultRole_whenCallGetUsername4_thenAccessDenied() {
|
||||
userRoleService.getUsername4();
|
||||
}
|
||||
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.methodsecurity;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.methodsecurity.service.UserRoleService;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration
|
||||
@WithMockUser(username = "john", roles = { "VIEWER" })
|
||||
public class MockUserAtClassLevelIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenRoleViewer_whenCallGetUsername_thenReturnUsername() {
|
||||
String currentUserName = userService.getUsername();
|
||||
assertEquals("john", currentUserName);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
UserRoleService userService;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.methodsecurity.*")
|
||||
public static class SpringConfig {
|
||||
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.methodsecurity;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.test.context.support.WithUserDetails;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.methodsecurity.entity.CustomUser;
|
||||
import com.baeldung.methodsecurity.service.UserRoleService;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration
|
||||
public class UserDetailsIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
UserRoleService userService;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.methodsecurity.*")
|
||||
public static class SpringConfig {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUserDetails(value = "john", userDetailsServiceBeanName = "userDetailService")
|
||||
public void whenJohn_callLoadUserDetail_thenOK() {
|
||||
CustomUser user = userService.loadUserDetail("jane");
|
||||
assertEquals("jane", user.getNickName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUserDetails(value = "jane", userDetailsServiceBeanName = "userDetailService")
|
||||
public void givenJane_callSecuredLoadUserDetailWithJane_thenOK() {
|
||||
CustomUser user = userService.securedLoadUserDetail("jane");
|
||||
assertEquals("jane", user.getNickName());
|
||||
assertEquals("jane", user.getUsername());
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
@WithUserDetails(value = "john", userDetailsServiceBeanName = "userDetailService")
|
||||
public void givenJohn_callSecuredLoadUserDetailWithJane_thenAccessDenied() {
|
||||
userService.securedLoadUserDetail("jane");
|
||||
}
|
||||
|
||||
@Test(expected = AccessDeniedException.class)
|
||||
@WithUserDetails(value = "john", userDetailsServiceBeanName = "userDetailService")
|
||||
public void givenJohn_callSecuredLoadUserDetailWithJohn_thenAccessDenied() {
|
||||
userService.securedLoadUserDetail("john");
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.methodsecurity;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@WithMockUser(value="john",roles="VIEWER")
|
||||
public @interface WithMockJohnViewer { }
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.test;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
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.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.MethodSorters;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
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;
|
||||
|
||||
import com.baeldung.app.App;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||
public class LiveTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext context;
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(context).dispatchOptions(true).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(roles = "MANAGER")
|
||||
public void givenUserIsManager_whenGetTasks_thenAllTasks() throws Exception {
|
||||
String allTasks = "[{'id':1,'description':'Send a fax','assignee':'pam'}," + "{'id':2,'description':'Print a document','assignee':'pam'}," + "{'id':3,'description':'Answer the phone','assignee':'pam'},"
|
||||
+ "{'id':4,'description':'Call a client','assignee':'jim'}," + "{'id':5,'description':'Organize a meeting','assignee':'michael'}]";
|
||||
|
||||
mockMvc.perform(get("/api/tasks")).andExpect(status().isOk()).andExpect(content().json(allTasks));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "jim")
|
||||
public void givenUserNotManager_whenGetTasks_thenReturnAssignedToMe() throws Exception {
|
||||
String myTasks = "[{'id':4,'description':'Call a client','assignee':'jim'}]";
|
||||
|
||||
mockMvc.perform(get("/api/tasks")).andExpect(status().isOk()).andExpect(content().json(myTasks));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(roles = "MANAGER")
|
||||
public void givenUserIsManager_whenPostTasks_thenIncludeAllTasks() throws Exception {
|
||||
String newTasks = "[{\"description\":\"New to Michael\",\"assignee\":\"michael\"}," + "{\"description\":\"New to Pam\",\"assignee\":\"pam\"}]";
|
||||
|
||||
mockMvc.perform(post("/api/tasks").contentType(MediaType.APPLICATION_JSON).content(newTasks)).andExpect(status().isOk())
|
||||
.andExpect(content().json("[{'id': 6,'description':'New to Michael','assignee':'michael'}, {'id': 7,'description':'New to Pam','assignee':'pam'}]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "jim")
|
||||
public void givenUserNotManager_whenPostTasks_thenIncludeOnlyAssignedToMe() throws Exception {
|
||||
String newTasks = "[{\"description\":\"New to Jim\",\"assignee\":\"jim\"}," + "{\"description\":\"New to Pam\",\"assignee\":\"pam\"}]";
|
||||
|
||||
mockMvc.perform(post("/api/tasks").contentType(MediaType.APPLICATION_JSON).content(newTasks)).andExpect(status().isOk()).andExpect(content().json("[{'id': 8,'description':'New to Jim','assignee':'jim'}]"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Reference in New Issue
Block a user