This library is helpful for integration test based on spring security, especially oauth2 for resource server, works with MockMvc
.
It enhanced spring-security-test by mock an OAuth2 client or on behalf of user.
Attach Map-based claims to mocked user as authentication details, the claims can be extracted from bearer jwt token.
Note: Most code came from the open network. I refactor and enhanced the code, then we have this java-library.
@WithMockOAuth2Client
@WithMockOAuth2User
- mock an oauth2 user, attach claims to OAuth2Authentication details
@AttachClaims
- attach Map-based claims to current authentication, should work with
@WithMockUser
- attach Map-based claims to current authentication, should work with
@WithMockUserAndClaims
- enhanced
@WithMockUser
, attach Map-based claims as authentication details - equal to
@WithMockUser
+@AttachClaims
- enhanced
@WithToken
- add
bearer
token to request header to extract aPreAuthenticatedAuthenticationToken
, load existing OAuth2Authentication from SecurityContext - require
@MockTokenServices
on test class
- add
@ResourcesNonStateless
- allow non token-based authentication to access oauth2 resources
allprojects { repositories { ... maven { url 'https://jitpack.io' } } }
dependencies { implementation 'com.github.ahunigel:spring-security-oauth2-test:{version}' }
Refer to https://jitpack.io/#ahunigel/spring-security-oauth2-test for details.
@WithMockOAuth2User( client = @WithMockOAuth2Client( clientId = "custom-client", scope = {"custom-scope", "other-scope"}, authorities = {"custom-authority", "ROLE_CUSTOM_CLIENT"}), user = @WithMockUser( username = "custom-username", authorities = {"custom-user-authority"}), claims = @AttachClaims({ @Claim(name = "user_id", value = "6", type = Long.class), @Claim(name = "role_id", value = "1"), @Claim(name = "is_social_user", value = "false") }) )
or
@AttachClaims(value = { @Claim(name = "user_id", value = "6", type = Long.class), @Claim(name = "role_id", value = "1"), @Claim(name = "is_social_user", value = "false")}, claims = {"email:ahunigel@gmail.com", "user_name=ahunigel"} ) @WithMockUser()
or
@WithMockUserAndClaims( @AttachClaims(value = { @Claim(name = "user_id", value = "6", type = Long.class), @Claim(name = "role_id", value = "1"), @Claim(name = "is_social_user", value = "false")}, claims = {"email:ahunigel@gmail.com", "user_name=ahunigel"} ) )
- How to get @WebMvcTest work with OAuth?
- Faking OAuth2 Single Sign-on in Spring
- @WithSecurityContext
- Spring MVC Test Integration
- OAuth2 Autoconfig
- Retrieve User Information in Spring Security
- Spring Security OAuth
- Use @WithMockUser with @SpringBootTest inside an oAuth2 Resource Server Application
- Spring Cloud Supported Versions
- Attach claims for @WithMockOAuth2Client/@WithMockOAuth2User via @AttachClaims
- Migrate Spring Security OAuth 2.x application to Spring Security 5.2
- Add support for
RestTemplate
- Add unit test