package inspiredbyte.examples.rules;
import java.util.ArrayList;
import java.util.List;
import inspiredbyte.examples.rules.annotations.SecurityContext;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
public class SecurityContextRule implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
SecurityContext securityContext = description.getAnnotation(SecurityContext.class);
return securityContext != null ? new SecurityContextStatement(base, getLoginId(securityContext),
getAuthorities(securityContext)) : base;
}
private String getLoginId(SecurityContext securityContext) {
return securityContext.loginId().trim();
}
private List<GrantedAuthority> getAuthorities(SecurityContext securityContext) {
String[] authorities = securityContext.authorities();
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
for (String authority : authorities) {
grantedAuthorities.add(new SimpleGrantedAuthority(authority.trim()));
}
return grantedAuthorities;
}
static class SecurityContextStatement extends Statement {
private Statement base;
private String loginId;
private List<GrantedAuthority> authorities;
public SecurityContextStatement(Statement base, String loginId, List<GrantedAuthority> authorities) {
this.base = base;
this.loginId = loginId;
this.authorities = authorities;
}
@Override
public void evaluate() throws Throwable {
try {
User user = new User(loginId, "N/A", authorities);
Authentication authentication = new TestingAuthenticationToken(user, "N/A", authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
base.evaluate();
} finally {
SecurityContextHolder.clearContext();
}
}
}
}