mardi 23 février 2016

Spring Security MockMvc controller unit tests

I am a newbie to Spring security. I have gone through various posts o how to resolve the issue I am facing and tried literally all of them with no luck. Here is the problem I am facing. I am trying to unit test my REST controller methods which are secured using

@PreAuthorize("isAuthenticated() and hasPermission(null, 'Test_Permission')")

using MockMvc.

I have the correct set of annotations on my Test class

@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes=ApplicationConfiguration.class, loader = SpringApplicationContextLoader.class)

I set up MockMVC in my test as follows

@Before public void setup() { myServiceMock = mock(myServiceImpl.class); this.mockMvc = standaloneSetup(new myController(myServiceMock)) .apply(springSecurity(springSecurityFilterChain)).build(); MockitoAnnotations.initMocks(this); }

Although my actual controller class is annotated to be run with a user who has "Test_Permission" , when I run my test it just results in HTTP 200 instead of 403.

I also tried with following in my setup

this.mockMvc = standaloneSetup(new myController(myServiceMock)) .apply(springSecurity()).build();

and

this.mockMvc = standaloneSetup(new myController(myServiceMock)) .addFilters(springSecurityFilterChain).build();

Could somebody please explain what I might be missing in order for my tests to take the authorities on my REST methods take into account. Thanks a lot in advance for your help.

Aucun commentaire:

Enregistrer un commentaire