How do I unit test spring security @PreAuthorize(hasRole)?

前端 未结 3 672
暖寄归人
暖寄归人 2020-12-24 12:15

What do I need in order to unit test the hasRole part of a PreAuthorize annotation on a controller method?

My test should succeed because the logged in user only has

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 12:57

    Just to add to Rob's solution above, as of December 20, 2014, there is a bug in the SecurityRequestPostProcessors class on the master branch from Rob's answer above that prevents the assigned roles from being populated.

    A quick fix is to comment out the following line of code (currently line 181) in the roles(String... roles) method of the UserRequestPostProcessor inner static class of SecurityRequestPostProcessors:

    // List authorities = new ArrayList(roles.length);.

    You need to comment out the local variable, NOT the member variable.

    Alternatively, you may insert this line just before returning from the method:

    this.authorities = authorities;

    P.S I would have added this as a comment had I had enough reputation.

提交回复
热议问题