Search in sources :

Example 16 with Converter

use of org.springframework.core.convert.converter.Converter in project spring-security by spring-projects.

the class WebClientReactivePasswordTokenResponseClientTests method getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent.

@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
    // @formatter:off
    String accessTokenSuccessResponse = "{\n" + "   \"access_token\": \"access-token-1234\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
    // @formatter:off
    ClientRegistration clientRegistration = this.clientRegistrationBuilder.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).build();
    // @formatter:on
    // Configure Jwt client authentication converter
    JWK jwk = TestJwks.DEFAULT_RSA_JWK;
    Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
    configureJwtClientAuthenticationConverter(jwkResolver);
    OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, this.username, this.password);
    this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block();
    RecordedRequest actualRequest = this.server.takeRequest();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=password", "client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer", "client_assertion=");
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Function(java.util.function.Function) BDDMockito.given(org.mockito.BDDMockito.given) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) MockWebServer(okhttp3.mockwebserver.MockWebServer) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) Converter(org.springframework.core.convert.converter.Converter) TestOAuth2AccessTokenResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses) TestKeys(org.springframework.security.oauth2.jose.TestKeys) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HttpHeaders(org.springframework.http.HttpHeaders) TestJwks(org.springframework.security.oauth2.jose.TestJwks) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor) Instant(java.time.Instant) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) JWK(com.nimbusds.jose.jwk.JWK) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) MockResponse(okhttp3.mockwebserver.MockResponse) Collections(java.util.Collections) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Mockito.mock(org.mockito.Mockito.mock) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test)

Example 17 with Converter

use of org.springframework.core.convert.converter.Converter in project spring-security by spring-projects.

the class Saml2AuthenticationTokenConverterTests method convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException.

@Test
public void convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException() {
    Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(this.relyingPartyRegistrationResolver);
    given(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))).willReturn(this.relyingPartyRegistration);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    byte[] invalidDeflated = "invalid".getBytes();
    String encoded = Saml2Utils.samlEncode(invalidDeflated);
    request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
    assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withCauseInstanceOf(IOException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Mock(org.mockito.Mock) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ClassPathResource(org.springframework.core.io.ClassPathResource) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) AbstractSaml2AuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Converter(org.springframework.core.convert.converter.Converter) Saml2ErrorCodes(org.springframework.security.saml2.core.Saml2ErrorCodes) StreamUtils(org.springframework.util.StreamUtils) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) Saml2AuthenticationToken(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken) Saml2Utils(org.springframework.security.saml2.core.Saml2Utils) IOException(java.io.IOException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) Saml2ParameterNames(org.springframework.security.saml2.core.Saml2ParameterNames) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) UriUtils(org.springframework.web.util.UriUtils) Saml2AuthenticationException(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException) TestRelyingPartyRegistrations(org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations) Mockito.mock(org.mockito.Mockito.mock) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Test(org.junit.jupiter.api.Test)

Example 18 with Converter

use of org.springframework.core.convert.converter.Converter in project spring-security by spring-projects.

the class Saml2AuthenticationTokenConverterTests method convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException.

@Test
public void convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException() {
    Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(this.relyingPartyRegistrationResolver);
    given(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))).willReturn(this.relyingPartyRegistration);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "invalid");
    assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withCauseInstanceOf(IllegalArgumentException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Failed to decode SAMLResponse"));
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Mock(org.mockito.Mock) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ClassPathResource(org.springframework.core.io.ClassPathResource) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) AbstractSaml2AuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Converter(org.springframework.core.convert.converter.Converter) Saml2ErrorCodes(org.springframework.security.saml2.core.Saml2ErrorCodes) StreamUtils(org.springframework.util.StreamUtils) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) Saml2AuthenticationToken(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken) Saml2Utils(org.springframework.security.saml2.core.Saml2Utils) IOException(java.io.IOException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) Saml2ParameterNames(org.springframework.security.saml2.core.Saml2ParameterNames) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) UriUtils(org.springframework.web.util.UriUtils) Saml2AuthenticationException(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException) TestRelyingPartyRegistrations(org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations) Mockito.mock(org.mockito.Mockito.mock) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Test(org.junit.jupiter.api.Test)

Example 19 with Converter

use of org.springframework.core.convert.converter.Converter in project spring-data-mongodb by spring-projects.

the class MappingMongoConverterUnitTests method mappingConsidersCustomConvertersNotWritingTypeInformation.

// DATAMONGO-724
@Test
public void mappingConsidersCustomConvertersNotWritingTypeInformation() {
    Person person = new Person();
    person.firstname = "Dave";
    ClassWithMapProperty entity = new ClassWithMapProperty();
    entity.mapOfPersons = new HashMap<String, Person>();
    entity.mapOfPersons.put("foo", person);
    entity.mapOfObjects = new HashMap<String, Object>();
    entity.mapOfObjects.put("foo", person);
    CustomConversions conversions = new MongoCustomConversions(Arrays.asList(new Converter<Person, org.bson.Document>() {

        @Override
        public org.bson.Document convert(Person source) {
            return // 
            new org.bson.Document().append("firstname", source.firstname).append("_class", Person.class.getName());
        }
    }, new Converter<org.bson.Document, Person>() {

        @Override
        public Person convert(org.bson.Document source) {
            Person person = new Person();
            person.firstname = source.get("firstname").toString();
            person.lastname = "converter";
            return person;
        }
    }));
    MongoMappingContext context = new MongoMappingContext();
    context.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
    context.afterPropertiesSet();
    MappingMongoConverter mongoConverter = new MappingMongoConverter(resolver, context);
    mongoConverter.setCustomConversions(conversions);
    mongoConverter.afterPropertiesSet();
    org.bson.Document document = new org.bson.Document();
    mongoConverter.write(entity, document);
    ClassWithMapProperty result = mongoConverter.read(ClassWithMapProperty.class, document);
    assertThat(result.mapOfPersons, is(notNullValue()));
    Person personCandidate = result.mapOfPersons.get("foo");
    assertThat(personCandidate, is(notNullValue()));
    assertThat(personCandidate.firstname, is("Dave"));
    assertThat(result.mapOfObjects, is(notNullValue()));
    Object value = result.mapOfObjects.get("foo");
    assertThat(value, is(notNullValue()));
    assertThat(value, is(instanceOf(Person.class)));
    assertThat(((Person) value).firstname, is("Dave"));
    assertThat(((Person) value).lastname, is("converter"));
}
Also used : CustomConversions(org.springframework.data.convert.CustomConversions) Document(org.springframework.data.mongodb.core.mapping.Document) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) WritingConverter(org.springframework.data.convert.WritingConverter) Converter(org.springframework.core.convert.converter.Converter) ReadingConverter(org.springframework.data.convert.ReadingConverter) Test(org.junit.Test)

Example 20 with Converter

use of org.springframework.core.convert.converter.Converter in project spring-integration by spring-projects.

the class DatatypeChannelTests method conversionServiceBeanUsedByDefault.

@Test
public void conversionServiceBeanUsedByDefault() {
    GenericApplicationContext context = new GenericApplicationContext();
    Converter<Boolean, Integer> converter = new Converter<Boolean, Integer>() {

        @Override
        public Integer convert(Boolean source) {
            return source ? 1 : 0;
        }
    };
    BeanDefinitionBuilder conversionServiceBuilder = BeanDefinitionBuilder.genericBeanDefinition(ConversionServiceFactoryBean.class);
    conversionServiceBuilder.addPropertyValue("converters", Collections.singleton(converter));
    context.registerBeanDefinition(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME, conversionServiceBuilder.getBeanDefinition());
    BeanDefinition messageConverter = BeanDefinitionBuilder.genericBeanDefinition(DefaultDatatypeChannelMessageConverter.class).getBeanDefinition();
    context.registerBeanDefinition(IntegrationContextUtils.INTEGRATION_DATATYPE_CHANNEL_MESSAGE_CONVERTER_BEAN_NAME, messageConverter);
    BeanDefinitionBuilder channelBuilder = BeanDefinitionBuilder.genericBeanDefinition(QueueChannel.class);
    channelBuilder.addPropertyValue("datatypes", "java.lang.Integer, java.util.Date");
    context.registerBeanDefinition("testChannel", channelBuilder.getBeanDefinition());
    context.refresh();
    QueueChannel channel = context.getBean("testChannel", QueueChannel.class);
    assertSame(context.getBean(ConversionService.class), TestUtils.getPropertyValue(channel, "messageConverter.conversionService"));
    assertTrue(channel.send(new GenericMessage<Boolean>(Boolean.TRUE)));
    assertEquals(1, channel.receive().getPayload());
    context.close();
}
Also used : GenericMessage(org.springframework.messaging.support.GenericMessage) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) ConversionService(org.springframework.core.convert.ConversionService) GenericConversionService(org.springframework.core.convert.support.GenericConversionService) DefaultConversionService(org.springframework.core.convert.support.DefaultConversionService) DefaultDatatypeChannelMessageConverter(org.springframework.integration.support.converter.DefaultDatatypeChannelMessageConverter) GenericConverter(org.springframework.core.convert.converter.GenericConverter) Converter(org.springframework.core.convert.converter.Converter) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) DefaultDatatypeChannelMessageConverter(org.springframework.integration.support.converter.DefaultDatatypeChannelMessageConverter) Test(org.junit.Test)

Aggregations

Converter (org.springframework.core.convert.converter.Converter)33 Test (org.junit.jupiter.api.Test)25 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)15 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)13 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)12 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)12 StandardCharsets (java.nio.charset.StandardCharsets)10 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)10 BDDMockito.given (org.mockito.BDDMockito.given)10 Mockito.mock (org.mockito.Mockito.mock)10 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)9 JWK (com.nimbusds.jose.jwk.JWK)8 Collections (java.util.Collections)8 Function (java.util.function.Function)8 SecretKeySpec (javax.crypto.spec.SecretKeySpec)8 MockResponse (okhttp3.mockwebserver.MockResponse)8 MockWebServer (okhttp3.mockwebserver.MockWebServer)8 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)8 AfterEach (org.junit.jupiter.api.AfterEach)8 BeforeEach (org.junit.jupiter.api.BeforeEach)8