Skip to content
Permalink
Browse files

How to mock Spring Security context

  • Loading branch information...
slem1 committed Oct 27, 2017
1 parent e3d143c commit c64058e7f64f0cf28634e53306ad9ec027aa2a39
@@ -1,5 +1,6 @@
package fr.sle.testhowto.rest.facade;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -34,6 +34,7 @@ public void before() {
}

@Test
@WithMockBasicAuth(principal = "user", roles = "ROLE_USER")
public void getAStringTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get(MyRestFacade.ROOT_RESOURCE))
.andExpect(MockMvcResultMatchers.status().isOk());
@@ -0,0 +1,18 @@
package fr.sle.testhowto.test;

import org.springframework.security.test.context.support.WithSecurityContext;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
* @author slemoine
*/
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockBasicAuthSecurityContextFactory.class)
public @interface WithMockBasicAuth {

String principal();

String[] roles() default {};
}
@@ -0,0 +1,34 @@
package fr.sle.testhowto.test;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
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.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.test.context.support.WithSecurityContextFactory;

import java.util.ArrayList;
import java.util.List;

/**
* @author slemoine
*/
public class WithMockBasicAuthSecurityContextFactory implements WithSecurityContextFactory<WithMockBasicAuth>{

@Override
public SecurityContext createSecurityContext(WithMockBasicAuth basicAuth) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

for (final String role : basicAuth.roles()) {
grantedAuthorities.add(new SimpleGrantedAuthority(role));
}

User principal = new User(basicAuth.principal(), "", grantedAuthorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null, grantedAuthorities);
context.setAuthentication(authentication);
return context;
}
}

0 comments on commit c64058e

Please sign in to comment.
You can’t perform that action at this time.