REST controller has no current user in junit test; the context contains only the Anonymous un-authenticated user.
It should be possible to write and test controllers who's behavior depends on the current user data.
3.4.0
.yo-rc.json
file generated in the root folder{
"generator-jhipster": {
"jhipsterVersion": "3.4.0",
"baseName": "testjwt",
"packageName": "com.mycompany.myapp",
"packageFolder": "com/mycompany/myapp",
"serverPort": "8080",
"authenticationType": "jwt",
"hibernateCache": "ehcache",
"clusteredHttpSession": "no",
"websocket": "no",
"databaseType": "sql",
"devDatabaseType": "h2Disk",
"prodDatabaseType": "mysql",
"searchEngine": "no",
"buildTool": "maven",
"enableSocialSignIn": false,
"jwtSecretKey": "c801dd5d5973063641bf9d8f3514d2ee515b9baf",
"useSass": false,
"applicationType": "monolith",
"testFrameworks": [
"gatling"
],
"jhiPrefix": "jhi",
"enableTranslation": true,
"nativeLanguage": "it",
"languages": [
"it"
]
}
}
entityName.json
files generated in the .jhipster
directory$ cat .jhipster/Receipe.json
{
"relationships": [],
"fields": [
{
"fieldName": "rnumber",
"fieldType": "String"
}
],
"changelogDate": "20160616144530",
"dto": "no",
"service": "no",
"entityTableName": "receipe",
"pagination": "pagination"
}
Add to all REST controllers log something like
log.debug("REST {} auth {} request to save Receipe : {}", SecurityUtils.getCurrentUserLogin(), SecurityUtils.isAuthenticated(), receipe);
The output will be
REST anonymous auth false request to save Receipe : ...
I've unsuccessfully tried to include in pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
and replaced in ReceipeResourceIntTest setup() method
this.restReceipeMockMvc = MockMvcBuilders.standaloneSetup(receipeResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setMessageConverters(jacksonMessageConverter).build();
with
this.restReceipeMockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
... any suggestions?
Same for
"authenticationType": "oauth2",
It seems to me that it's done in AccountResourceIntTest so it should be easy to do it in other tests too.
Spring Security Test dependency also provides convenient annotation @WithMockUser
to allow security context in tests.
Both solutions from @gmarziou and @Vaelyr looks OK to me, and no comments here for 1 month, so I'm closing this.
Sorry for being absent for a while.
I've further investigated with no success.
I've changed the logging statement in each EntityResource.java including SecurityUtils.getCurrentUserLogin()
See https://github.com/jhipster/generator-jhipster/compare/master...lrkwz:rest_auhentication
If you run tests the current user login is always 'null' since there is no Authentication object in the current security context.
I've tried to change the tests adding (has in @gmarziou suggestion)
.with(request -> {
request.setRemoteUser("user");
return request;
})
with no luck: use ha still no login name not is is authenticated.
My second unfortunate guess (has in @Vaelyr suggestion) has been changing the test setup adding .apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
to the StandaloneMockMvcBuilder
generated by MockMvcBuilders.standaloneSetup()
and @WithMockUser
.
Something like this:
@Autowired
private FilterChainProxy springSecurityFilterChain;
@PostConstruct
public void setup() {
MockitoAnnotations.initMocks(this);
UserProfileResource userProfileResource = new UserProfileResource();
ReflectionTestUtils.setField(userProfileResource, "userProfileService", userProfileService);
this.restUserProfileMockMvc = MockMvcBuilders.standaloneSetup(userProfileResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setMessageConverters(jacksonMessageConverter).apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain)).build();
}
In this scenario the test ends with a (somewhat encouraging) 403 http status (forbidden).
@lrkwz any luck? I encountered the same issue when I use getCurrentUserLogin() in my EntityResource file. The Unit Test always fail and I don't know how to create a Mock User...
@Vaelyr is right
There is an official article about how to use it, it resolved my issue:
http://docs.spring.io/spring-security/site/docs/current/reference/html/test-method.html
My jhipster4-demo tutorial shows how to use WithMockUser
to test something like this:
Hi! I just had this issue and I used:
@WithMockUser(username="user@localhost",authorities={"ROLE_USR"}, password = "user")
You can place this annotation on a specific test or a class of tests, so that all tests benefit from this MockUser!
Then all my Ressources using SecurityUtils.getCurrentLogin()
work, the user is found with all of his information.
Most helpful comment
My jhipster4-demo tutorial shows how to use
WithMockUser
to test something like this: