Generator-jhipster: Test REST controllers with an autenticated user

Created on 16 Jun 2016  路  9Comments  路  Source: jhipster/generator-jhipster

Overview of the issue

REST controller has no current user in junit test; the context contains only the Anonymous un-authenticated user.

Motivation for or Use Case

It should be possible to write and test controllers who's behavior depends on the current user data.

JHipster Version(s)

3.4.0

JHipster configuration, a .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"
    ]
  }
}
Entity configuration(s) 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"
}
Reproduce the error

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?

area

Most helpful comment

My jhipster4-demo tutorial shows how to use WithMockUser to test something like this:

All 9 comments

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.

https://github.com/jhipster/jhipster-sample-app/blob/master/src/test/java/io/github/jhipster/sample/web/rest/AccountResourceIntTest.java#L97-L107

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

frantzynicolas picture frantzynicolas  路  3Comments

pascalgrimaud picture pascalgrimaud  路  4Comments

trajakovic picture trajakovic  路  4Comments

Steven-Garcia picture Steven-Garcia  路  3Comments

chegola picture chegola  路  4Comments