|
| 1 | +package org.springframework.security.web.jackson2; |
| 2 | + |
| 3 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 4 | +import org.springframework.security.core.Authentication; |
| 5 | +import org.springframework.security.core.authority.AuthorityUtils; |
| 6 | +import org.springframework.security.jackson2.AbstractMixinTests; |
| 7 | +import org.springframework.security.jackson2.SimpleGrantedAuthorityMixinTests; |
| 8 | +import org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority; |
| 9 | + |
| 10 | +import org.junit.jupiter.api.BeforeEach; |
| 11 | +import org.junit.jupiter.api.Test; |
| 12 | +import org.skyscreamer.jsonassert.JSONAssert; |
| 13 | + |
| 14 | +import static org.assertj.core.api.Assertions.assertThat; |
| 15 | + |
| 16 | +/** |
| 17 | + * @author Markus Heiden |
| 18 | + * @since 5.8 |
| 19 | + */ |
| 20 | +public class SwitchUserGrantedAuthorityMixInTest extends AbstractMixinTests { |
| 21 | + |
| 22 | + // language=JSON |
| 23 | + private static final String SWITCH_JSON = """ |
| 24 | + { |
| 25 | + "@class": "org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority", |
| 26 | + "role": "switched", |
| 27 | + "source": { |
| 28 | + "@class": "org.springframework.security.authentication.UsernamePasswordAuthenticationToken", |
| 29 | + "principal": "principal", |
| 30 | + "credentials": "credentials", |
| 31 | + "authenticated": true, |
| 32 | + "details": null, |
| 33 | + "authorities": %s |
| 34 | + } |
| 35 | + } |
| 36 | + """.formatted(SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON); |
| 37 | + SwitchUserGrantedAuthority expected; |
| 38 | + Authentication source; |
| 39 | + |
| 40 | + @BeforeEach |
| 41 | + public void setupExpected() { |
| 42 | + this.source = new UsernamePasswordAuthenticationToken( |
| 43 | + "principal", "credentials", |
| 44 | + AuthorityUtils.createAuthorityList("ROLE_USER")); |
| 45 | + this.expected = new SwitchUserGrantedAuthority("switched", this.source); |
| 46 | + } |
| 47 | + |
| 48 | + @Test |
| 49 | + public void serializeWhenPrincipalCredentialsAuthoritiesThenSuccess() throws Exception { |
| 50 | + String serializedJson = this.mapper.writeValueAsString(this.expected); |
| 51 | + JSONAssert.assertEquals(SWITCH_JSON, serializedJson, true); |
| 52 | + } |
| 53 | + |
| 54 | + @Test |
| 55 | + public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws Exception { |
| 56 | + SwitchUserGrantedAuthority deserialized = this.mapper.readValue(SWITCH_JSON, SwitchUserGrantedAuthority.class); |
| 57 | + assertThat(deserialized).isNotNull(); |
| 58 | + assertThat(deserialized.getAuthority()).isEqualTo("switched"); |
| 59 | + assertThat(deserialized.getSource()).isEqualTo(this.source); |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments