org.springframework.http.HttpHeaders.AUTHORIZATION

Here are the examples of the java api org.springframework.http.HttpHeaders.AUTHORIZATION taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

435 Examples 7

@Test
public void okResponseWithBasicAuthCredentialsForKnownUser() throws Exception {
    this.mockMvc.perform(get("/").header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))).andExpect(status().isOk());
}

19 View Source File : ReactiveCloudFoundrySecurityServiceTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() throws Exception {
    prepareResponse((response) -> response.setResponseCode(500));
    StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")).consumeErrorWith((throwable) -> {
        replacedertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.clreplaced);
        replacedertThat(((CloudFoundryAuthorizationException) throwable).getReason()).isEqualTo(Reason.SERVICE_UNAVAILABLE);
    }).verify();
    expectRequest((request) -> {
        replacedertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token");
        replacedertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS);
    });
}

19 View Source File : ReactiveCloudFoundrySecurityServiceTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getAccessLevelWhenTokenIsNotValidShouldThrowException() throws Exception {
    prepareResponse((response) -> response.setResponseCode(401));
    StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")).consumeErrorWith((throwable) -> {
        replacedertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.clreplaced);
        replacedertThat(((CloudFoundryAuthorizationException) throwable).getReason()).isEqualTo(Reason.INVALID_TOKEN);
    }).verify();
    expectRequest((request) -> {
        replacedertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token");
        replacedertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS);
    });
}

19 View Source File : ReactiveCloudFoundrySecurityServiceTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getAccessLevelWhenForbiddenShouldThrowException() throws Exception {
    prepareResponse((response) -> response.setResponseCode(403));
    StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")).consumeErrorWith((throwable) -> {
        replacedertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.clreplaced);
        replacedertThat(((CloudFoundryAuthorizationException) throwable).getReason()).isEqualTo(Reason.ACCESS_DENIED);
    }).verify();
    expectRequest((request) -> {
        replacedertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token");
        replacedertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS);
    });
}

19 View Source File : CertificationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler deleteById() {
    return doreplacedent("certification/delete", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더")), pathParameters(parameterWithName("id").description("인증 ID")));
}

19 View Source File : CalculationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler retrieveBadMember() {
    return doreplacedent("calculation/get-fail-by-member", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰")), pathParameters(parameterWithName("raceId").description("정산하고자 하는 레이스의 아이디")), getErrorResponseFields());
}

19 View Source File : CalculationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler createDuplicatedCalculation() {
    return doreplacedent("calculation/create-fail", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰")), pathParameters(parameterWithName("raceId").description("정산하고자 하는 레이스의 아이디")), getErrorResponseFields());
}

19 View Source File : CalculationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler retrieveNotFinishedRace() {
    return doreplacedent("calculation/get-fail-not-finished", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰")), pathParameters(parameterWithName("raceId").description("정산하고자 하는 레이스의 아이디")), getErrorResponseFields());
}

19 View Source File : CalculationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler create() {
    return doreplacedent("calculation/create-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰")), pathParameters(parameterWithName("raceId").description("정산하고자 하는 레이스의 아이디")), responseHeaders(headerWithName("Location").description("생성된 정산의 리소스")));
}

19 View Source File : CalculationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler retrieveNotFound() {
    return doreplacedent("calculation/get-fail-not-found", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰")), pathParameters(parameterWithName("raceId").description("정산하고자 하는 레이스의 아이디")), getErrorResponseFields());
}

19 View Source File : CalculationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler retrieve() {
    return doreplacedent("calculation/get-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰")), pathParameters(parameterWithName("raceId").description("정산하고자 하는 레이스의 아이디")), responseFields(fieldWithPath("calculationResponses").type(ARRAY).description("정산 결과"), fieldWithPath("calculationResponses[].rider_id").type(NUMBER).description("정산받은 라이더의 아이디"), fieldWithPath("calculationResponses[].race_id").type(NUMBER).description("정산된 레이스의 아이디"), fieldWithPath("calculationResponses[].prize").type(STRING).description("각 라이더별 정산 금액"), fieldWithPath("calculationResponses[].created_at").type(STRING).attributes(getDateTimeFormat()).description("정산 날짜"), fieldWithPath("calculationResponses[].calculated").type(BOOLEAN).description("정산 여부")));
}

19 View Source File : OpencpsRestFacade.java
License : GNU Affero General Public License v3.0
Project Creator : VietOpenCPS

/**
 * Default method for setting the HttpHeaders authorization token
 *
 * @param httpHeaders
 * @param authorizationField
 * @return
 */
protected HttpHeaders setHttpHeadersAuthorization(HttpHeaders httpHeaders, String authorizationField) {
    httpHeaders.add(HttpHeaders.AUTHORIZATION, authorizationField);
    return httpHeaders;
}

19 View Source File : OpencpsRestFacade.java
License : GNU Affero General Public License v3.0
Project Creator : VietOpenCPS

protected HttpHeaders setHttpHeadersAuthorization(HttpHeaders httpHeaders, String userName, String preplacedword) {
    String authString = userName + StringPool.COLON + preplacedword;
    String authStringEnc = new String(Base64.getEncoder().encodeToString(authString.getBytes()));
    httpHeaders.add(HttpHeaders.AUTHORIZATION, authStringEnc);
    return httpHeaders;
}

19 View Source File : HttpIT.java
License : Apache License 2.0
Project Creator : snowdrop

@Test
public void testBasicAuth() {
    startServer(SessionController.clreplaced, AuthConfiguration.clreplaced);
    getWebTestClient().get().exchange().expectStatus().isUnauthorized();
    String authHash = Base64Utils.encodeToString("user:preplacedword".getBytes(StandardCharsets.UTF_8));
    getWebTestClient().get().header(HttpHeaders.AUTHORIZATION, "Basic " + authHash).exchange().expectStatus().isOk().expectBody(String.clreplaced).value(not(emptyOrNullString()));
}

19 View Source File : OAuthMockKit.java
License : Apache License 2.0
Project Creator : pig-mesh

/**
 * mock 请求增加统一请求头
 * @return RequestPostProcessor 类似于拦截器
 */
public static RequestPostProcessor token() {
    return mockRequest -> {
        OAuth2ClientContext clientContext = SpringContextHolder.getBean(OAuth2ClientContext.clreplaced);
        String token = clientContext.getAccessToken().getValue();
        mockRequest.addHeader(HttpHeaders.AUTHORIZATION, String.format("Bearer: %s", token));
        return mockRequest;
    };
}

19 View Source File : SpringHttpRequestSignerTest.java
License : MIT License
Project Creator : Mastercard

@Test
public void testSignShouldAddOAuth1HeaderToGetRequestEmptyBody() {
    // GIVEN
    request = new HttpRequest() {

        @Override
        public HttpMethod getMethod() {
            return GET_METHOD;
        }

        @Override
        public String getMethodValue() {
            return getMethod().toString();
        }

        @Override
        public URI getURI() {
            return uri;
        }

        @Override
        public HttpHeaders getHeaders() {
            return headers;
        }
    };
    // WHEN
    SpringHttpRequestSigner instanceUnderTest = new SpringHttpRequestSigner(DEFAULT_CONSUMER_KEY, signingKey);
    instanceUnderTest.sign(request, "".getBytes());
    // THEN
    String authorizationHeaderValue = headers.getFirst(HttpHeaders.AUTHORIZATION);
    replacedert.replacedertNotNull(authorizationHeaderValue);
}

19 View Source File : SpringHttpRequestSignerTest.java
License : MIT License
Project Creator : Mastercard

@Test
public void testSignShouldAddOAuth1HeaderToGetRequestNullBody() {
    // GIVEN
    request = new HttpRequest() {

        @Override
        public HttpMethod getMethod() {
            return GET_METHOD;
        }

        @Override
        public String getMethodValue() {
            return getMethod().toString();
        }

        @Override
        public URI getURI() {
            return uri;
        }

        @Override
        public HttpHeaders getHeaders() {
            return headers;
        }
    };
    // WHEN
    SpringHttpRequestSigner instanceUnderTest = new SpringHttpRequestSigner(DEFAULT_CONSUMER_KEY, signingKey);
    instanceUnderTest.sign(request, null);
    // THEN
    String authorizationHeaderValue = headers.getFirst(HttpHeaders.AUTHORIZATION);
    replacedert.replacedertNotNull(authorizationHeaderValue);
}

19 View Source File : SpringHttpRequestSignerTest.java
License : MIT License
Project Creator : Mastercard

@Test
public void testSignShouldAddOAuth1HeaderToPostRequest() {
    // WHEN
    SpringHttpRequestSigner instanceUnderTest = new SpringHttpRequestSigner(DEFAULT_CONSUMER_KEY, signingKey);
    instanceUnderTest.sign(request, DEFAULT_BODY.getBytes());
    // THEN
    String authorizationHeaderValue = headers.getFirst(HttpHeaders.AUTHORIZATION);
    replacedert.replacedertNotNull(authorizationHeaderValue);
}

19 View Source File : JwtTokenAuthenticationFilter.java
License : GNU General Public License v3.0
Project Creator : hantsy

private String resolveToken(ServerHttpRequest request) {
    String bearerToken = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(HEADER_PREFIX)) {
        return bearerToken.substring(7);
    }
    return null;
}

19 View Source File : ApplicationConfig.java
License : MIT License
Project Creator : gzmuSoft

/**
 * 暴露所有实体id.
 */
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration restConfiguration) {
    enreplacedyManagerFactory.getMetamodel().getManagedTypes().stream().filter(managedType -> managedType.getJavaType().isAnnotationPresent(Enreplacedy.clreplaced)).map(ManagedType::getJavaType).forEach(restConfiguration::exposeIdsFor);
    restConfiguration.getExposureConfiguration().disablePutForCreation().disablePutOnItemResources();
    restConfiguration.getCorsRegistry().addMapping("/**").allowedOrigins("*").allowedMethods("GET", "PATCH", "DELETE", "OPTIONS").allowedHeaders(HttpHeaders.AUTHORIZATION, HttpHeaders.ORIGIN).allowCredentials(true).maxAge(3600);
}

19 View Source File : RestApiSecurityApplicationTest.java
License : Apache License 2.0
Project Creator : flowable

protected static HttpHeaders createHeaders(String username, String preplacedword) {
    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.AUTHORIZATION, base64Authentication(username, preplacedword));
    return headers;
}

19 View Source File : FlowableRestApplicationSecurityTest.java
License : Apache License 2.0
Project Creator : flowable

protected static HttpHeaders createHeaders(String username, String preplacedword) {
    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.AUTHORIZATION, base64Auhentication(username, preplacedword));
    return headers;
}

19 View Source File : NotFoundTest.java
License : MIT License
Project Creator : FAIRDataTeam

public static <T> void createUserNotFoundTestPut(TestRestTemplate client, URI url, T object) {
    createNotFoundTest(client, RequestEnreplacedy.put(url).header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN).body(object));
}

19 View Source File : NotFoundTest.java
License : MIT License
Project Creator : FAIRDataTeam

public static <T> void createUserNotFoundTestGet(TestRestTemplate client, URI url) {
    createNotFoundTest(client, RequestEnreplacedy.get(url).header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN).build());
}

19 View Source File : NotFoundTest.java
License : MIT License
Project Creator : FAIRDataTeam

public static <T> void createAdminNotFoundTestPut(TestRestTemplate client, URI url, T object) {
    createNotFoundTest(client, RequestEnreplacedy.put(url).header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN).body(object));
}

19 View Source File : ForbiddenTest.java
License : MIT License
Project Creator : FAIRDataTeam

public static <T> void createUserForbiddenTestDelete(TestRestTemplate client, URI url) {
    createForbiddenTest(client, RequestEnreplacedy.delete(url).header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN).build());
}

19 View Source File : ForbiddenTest.java
License : MIT License
Project Creator : FAIRDataTeam

public static <T> void createUserForbiddenTestPut(TestRestTemplate client, URI url, T object) {
    createForbiddenTest(client, RequestEnreplacedy.put(url).header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN).body(object));
}

19 View Source File : ForbiddenTest.java
License : MIT License
Project Creator : FAIRDataTeam

public static void createUserForbiddenTestGet(TestRestTemplate client, URI url) {
    createForbiddenTest(client, RequestEnreplacedy.get(url).header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN).build());
}

19 View Source File : FirebaseApplicationService.java
License : MIT License
Project Creator : fabiomaffioletti

public MultiValueMap<String, String> headers() throws IOException {
    LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token());
    return headers;
}

19 View Source File : HttpHeadersBuilder.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2

public HttpHeadersBuilder withBasicAuth(String username, String preplacedword) {
    this.headers.set(HttpHeaders.AUTHORIZATION, CodecUtils.getBasicAuthString(username, preplacedword));
    return this;
}

19 View Source File : CloudxCloudSecurityAutoConfig.java
License : Apache License 2.0
Project Creator : chachae

/**
 * Feign 远程调用请求拦截,加入GatewayToken 和 当前用户的 Authorization Token
 *
 * @return RequestInterceptor
 */
@Bean
public RequestInterceptor oauth2FeignRequestInterceptor() {
    return requestTemplate -> {
        String gatewayToken = new String(Base64Utils.encode(GatewayConstant.TOKEN_VALUE.getBytes()));
        requestTemplate.header(GatewayConstant.TOKEN_HEADER, gatewayToken).header(HttpHeaders.AUTHORIZATION, SystemConstant.OAUTH2_TOKEN_TYPE + SecurityUtil.getCurrentTokenValue());
    };
}

19 View Source File : SecurityContextRepository.java
License : Apache License 2.0
Project Creator : ard333

@Override
public Mono<SecurityContext> load(ServerWebExchange swe) {
    ServerHttpRequest request = swe.getRequest();
    String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    if (authHeader != null && authHeader.startsWith("Bearer ")) {
        String authToken = authHeader.substring(7);
        Authentication auth = new UsernamePreplacedwordAuthenticationToken(authToken, authToken);
        return this.authenticationManager.authenticate(auth).map((authentication) -> {
            return new SecurityContextImpl(authentication);
        });
    } else {
        return Mono.empty();
    }
}

18 View Source File : ReactiveCloudFoundrySecurityServiceTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getAccessLevelWhenSpaceDeveloperShouldReturnFull() throws Exception {
    String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}";
    prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json"));
    StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")).consumeNextWith((accessLevel) -> replacedertThat(accessLevel).isEqualTo(AccessLevel.FULL)).expectComplete().verify();
    expectRequest((request) -> {
        replacedertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token");
        replacedertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS);
    });
}

18 View Source File : ReactiveCloudFoundrySecurityServiceTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() throws Exception {
    String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}";
    prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json"));
    StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")).consumeNextWith((accessLevel) -> replacedertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED)).expectComplete().verify();
    expectRequest((request) -> {
        replacedertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token");
        replacedertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS);
    });
}

18 View Source File : RequestUtils.java
License : Apache License 2.0
Project Creator : xm-online

public static HttpHeaders createAuthHeaders(MediaType mediaType) {
    HttpHeaders headers = createHeaders(mediaType);
    headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + TokenUtils.extractCurrentToken());
    return headers;
}

18 View Source File : CertificationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler createCertification() {
    return doreplacedent("certification/create-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestParts(partWithName("certification_image").description("인증 사진")), requestParameters(parameterWithName("status").description("인증 성공 여부"), parameterWithName("description").description("인증 세부내용").optional(), parameterWithName("riderId").description("인증 라이더 ID"), parameterWithName("missionId").description("미션 ID")), responseHeaders(headerWithName("Location").description("생성된 리소스 정보")));
}

18 View Source File : CertificationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler createDuplicatedCertification() {
    return doreplacedent("certification/create-duplicated", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestParts(partWithName("certification_image").description("인증 사진")), requestParameters(parameterWithName("status").description("인증 성공 여부"), parameterWithName("description").description("인증 세부내용").optional(), parameterWithName("riderId").description("인증 라이더 ID"), parameterWithName("missionId").description("인증 대상 미션 ID")), getErrorResponseFields());
}

18 View Source File : CertificationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler updateStatus() {
    return doreplacedent("certification/update-status", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-type")), pathParameters(parameterWithName("id").description("라이더 ID")), requestFields(fieldWithPath("status").description("변경될 인증 상태값").attributes(getCertificationStatus())), responseHeaders(headerWithName("Location").description("수정이 완료된 리소스 값")));
}

18 View Source File : CertificationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler updateDescription() {
    return doreplacedent("certification/update-description", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-type")), pathParameters(parameterWithName("id").description("인증 ID")), requestFields(fieldWithPath("description").description("변경될 인증 상세 설명")), responseHeaders(headerWithName("Location").description("수정이 완료된 리소스 값")));
}

18 View Source File : CertificationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler updateCertification() {
    return doreplacedent("certification/update-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestParts(partWithName("certification_image").description("인증 사진")), pathParameters(parameterWithName("id").description("인증 ID")), requestParameters(parameterWithName("status").description("인증 성공 여부"), parameterWithName("description").description("인증 세부내용").optional(), parameterWithName("riderId").description("인증 라이더 ID"), parameterWithName("missionId").description("미션 ID")), responseHeaders(headerWithName("Location").description("생성된 리소스 정보")));
}

18 View Source File : CertificationDocumentation.java
License : MIT License
Project Creator : woowacourse-teams

public static RestDoreplacedentationResultHandler createBadCertification() {
    return doreplacedent("certification/create-fail", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더"), headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 토큰")), requestParts(partWithName("certification_image").description("인증 사진")), requestParameters(parameterWithName("status").description("인증 성공 여부"), parameterWithName("description").description("인증 세부내용").optional(), parameterWithName("riderId").description("인증 라이더 ID")), responseHeaders(headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), getErrorResponseFieldsWithFieldErrors());
}

18 View Source File : OAuth2Requester.java
License : GNU Affero General Public License v3.0
Project Creator : wolfiabot

/**
 * See https://discord.com/developers/docs/resources/user#get-current-user
 *
 * @return the id of the user who the preplaceded in accessToken belongs to
 */
@CheckReturnValue
public CompletionStage<Long> identifyUser(String accessToken) {
    Request userInfoRequest = new Request.Builder().url(GET_USER_URL).header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken).get().build();
    CompletableFuture<Response> userInfoCallback = new CompletableFuture<>();
    this.httpClient.newCall(userInfoRequest).enqueue(asCallback(userInfoCallback));
    return userInfoCallback.thenApply(this::extractUserId);
}

@Override
protected ServiceInfoResponse makeServiceCall(CommonRequest payload) throws UpstreamServiceTimedOutException, UpstreamServiceFailedException {
    MultiValueMap<String, String> urlQueryParams = new LinkedMultiValueMap<>();
    String endPoint = Validator.isNotNull(payload.getEndpoint()) ? payload.getEndpoint() : DossierStatisticConfig.get(DossierStatisticConstants.SERVICE_INFO_ENDPOINT);
    // get the params for EE
    HashMap<String, String> urlPathSegments = new HashMap<>();
    // urlPathSegments.put("s", payload.getKeyword());
    // build the url
    String url = buildUrl(endPoint, urlPathSegments, urlQueryParams) + StringPool.FORWARD_SLASH + payload.getKeyword();
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(DossierStatisticConstants.GROUP_ID, Long.toString(payload.getGroupId()));
    // if (Validator.isNotNull(PropsUtil.get(ServerConfigContants.SERVER_SYNC_KEY))
    // && Validator.isNotNull(PropsUtil.get(ServerConfigContants.SERVER_SYNC_SECRET))) {
    // setHttpHeadersAuthorization(httpHeaders, PropsUtil.get(ServerConfigContants.SERVER_SYNC_KEY), PropsUtil.get(ServerConfigContants.SERVER_SYNC_SECRET));
    // }
    // else {
    // httpHeaders.add("Authorization", "Basic " + DossierStatisticConfig.get(DossierStatisticConstants.OPENCPS_AUTHENCATION));
    // }
    if (Validator.isNotNull(payload.getUsername()) && Validator.isNotNull(payload.getPreplacedword())) {
        httpHeaders.add(HttpHeaders.AUTHORIZATION, HttpAuthorizationHeader.SCHEME_BASIC + StringPool.SPACE + Base64.getEncoder().encodeToString((payload.getUsername() + StringPool.COLON + payload.getPreplacedword()).getBytes()));
    }
    return executeGenericRestCall(url, HttpMethod.GET, httpHeaders, payload, ServiceInfoResponse.clreplaced).getBody();
}

@Override
protected ServiceDomainResponse makeServiceCall(ServiceDomainRequest payload) throws UpstreamServiceTimedOutException, UpstreamServiceFailedException {
    MultiValueMap<String, String> urlQueryParams = new LinkedMultiValueMap<>();
    String endPoint = Validator.isNotNull(payload.getEndpoint()) ? payload.getEndpoint() : DossierStatisticConfig.get(DossierStatisticConstants.SERVICE_DOMAIN_ENDPOINT);
    // LOG.info(endPoint);
    // get the params for EE
    HashMap<String, String> urlPathSegments = new HashMap<>();
    // build the url
    String url = buildUrl(endPoint, urlPathSegments, urlQueryParams);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(DossierStatisticConstants.GROUP_ID, Long.toString(payload.getGroupId()));
    // if (Validator.isNotNull(PropsUtil.get(ServerConfigContants.SERVER_SYNC_KEY))
    // && Validator.isNotNull(PropsUtil.get(ServerConfigContants.SERVER_SYNC_SECRET))) {
    // setHttpHeadersAuthorization(httpHeaders, PropsUtil.get(ServerConfigContants.SERVER_SYNC_KEY), PropsUtil.get(ServerConfigContants.SERVER_SYNC_SECRET));
    // }
    // else {
    // httpHeaders.add("Authorization", "Basic " + DossierStatisticConfig.get(DossierStatisticConstants.OPENCPS_AUTHENCATION));
    // }
    if (Validator.isNotNull(payload.getUsername()) && Validator.isNotNull(payload.getPreplacedword())) {
        httpHeaders.add(HttpHeaders.AUTHORIZATION, HttpAuthorizationHeader.SCHEME_BASIC + StringPool.SPACE + Base64.getEncoder().encodeToString((payload.getUsername() + StringPool.COLON + payload.getPreplacedword()).getBytes()));
        System.out.println("HTTP BASIC: " + "Basic " + Base64.getEncoder().encodeToString((payload.getUsername() + ":" + payload.getPreplacedword()).getBytes()));
    }
    System.out.println("END POINT: " + endPoint);
    return executeGenericRestCall(url, HttpMethod.GET, httpHeaders, payload, ServiceDomainResponse.clreplaced).getBody();
}

18 View Source File : BaseITCase.java
License : Apache License 2.0
Project Creator : syndesisio

private static void prepareHeaders(Object body, HttpHeaders headers, String token) {
    if (body != null && !headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
        headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
    }
    if (token != null) {
        headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + token);
    }
    headers.set("X-Forwarded-User", "someone_important");
    headers.set("X-Forwarded-Access-Token", token);
    headers.set("SYNDESIS-XSRF-TOKEN", "awesome");
}

@Test
public void login() throws Exception {
    String name = "ben", pw = "benspreplacedword";
    this.mockMvc.perform(MockMvcRequestBuilders.get("/greet").header(HttpHeaders.AUTHORIZATION, basicAuthorizationHeader(name, pw))).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(result -> {
        String body = result.getResponse().getContentreplacedtring();
        replacedert.replacedertEquals(body, "hello, " + name + "!");
    });
}

@Test
public void login() throws Exception {
    String name = USER, pw = PW;
    this.mockMvc.perform(MockMvcRequestBuilders.get("/greet").header(HttpHeaders.AUTHORIZATION, basicAuthorizationHeader(name, pw))).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(result -> {
        String body = result.getResponse().getContentreplacedtring();
        replacedert.replacedertEquals(body, "hello, " + name + "!");
    });
}

18 View Source File : OAuth2TokenRevocationTests.java
License : Apache License 2.0
Project Creator : spring-projects-experimental

@Test
public void requestWhenRevokeRefreshTokenThenRevoked() throws Exception {
    this.spring.register(AuthorizationServerConfiguration.clreplaced).autowire();
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
    when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))).thenReturn(registeredClient);
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
    OAuth2RefreshToken token = authorization.getRefreshToken().getToken();
    OAuth2TokenType tokenType = OAuth2TokenType.REFRESH_TOKEN;
    when(authorizationService.findByToken(eq(token.getTokenValue()), isNull())).thenReturn(authorization);
    this.mvc.perform(post(OAuth2TokenRevocationEndpointFilter.DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI).params(getTokenRevocationRequestParameters(token, tokenType)).header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(registeredClient.getClientId(), registeredClient.getClientSecret()))).andExpect(status().isOk());
    verify(registeredClientRepository).findByClientId(eq(registeredClient.getClientId()));
    verify(authorizationService).findByToken(eq(token.getTokenValue()), isNull());
    ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClreplaced(OAuth2Authorization.clreplaced);
    verify(authorizationService).save(authorizationCaptor.capture());
    OAuth2Authorization updatedAuthorization = authorizationCaptor.getValue();
    OAuth2Authorization.Token<OAuth2RefreshToken> refreshToken = updatedAuthorization.getRefreshToken();
    replacedertThat(refreshToken.isInvalidated()).isTrue();
    OAuth2Authorization.Token<OAuth2AccessToken> accessToken = updatedAuthorization.getAccessToken();
    replacedertThat(accessToken.isInvalidated()).isTrue();
}

18 View Source File : OAuth2TokenRevocationTests.java
License : Apache License 2.0
Project Creator : spring-projects-experimental

private void replacedertRevokeAccessTokenThenRevoked(String tokenRevocationEndpointUri) throws Exception {
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
    when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))).thenReturn(registeredClient);
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
    OAuth2AccessToken token = authorization.getAccessToken().getToken();
    OAuth2TokenType tokenType = OAuth2TokenType.ACCESS_TOKEN;
    when(authorizationService.findByToken(eq(token.getTokenValue()), isNull())).thenReturn(authorization);
    this.mvc.perform(post(tokenRevocationEndpointUri).params(getTokenRevocationRequestParameters(token, tokenType)).header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth(registeredClient.getClientId(), registeredClient.getClientSecret()))).andExpect(status().isOk());
    verify(registeredClientRepository).findByClientId(eq(registeredClient.getClientId()));
    verify(authorizationService).findByToken(eq(token.getTokenValue()), isNull());
    ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClreplaced(OAuth2Authorization.clreplaced);
    verify(authorizationService).save(authorizationCaptor.capture());
    OAuth2Authorization updatedAuthorization = authorizationCaptor.getValue();
    OAuth2Authorization.Token<OAuth2AccessToken> accessToken = updatedAuthorization.getAccessToken();
    replacedertThat(accessToken.isInvalidated()).isTrue();
    OAuth2Authorization.Token<OAuth2RefreshToken> refreshToken = updatedAuthorization.getRefreshToken();
    replacedertThat(refreshToken.isInvalidated()).isFalse();
}

@Override
public Authentication convert(HttpServletRequest request) {
    String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (header == null) {
        return null;
    }
    String[] parts = header.split("\\s");
    if (!parts[0].equalsIgnoreCase("Basic")) {
        return null;
    }
    if (parts.length != 2) {
        throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST));
    }
    byte[] decodedCredentials;
    try {
        decodedCredentials = Base64.getDecoder().decode(parts[1].getBytes(StandardCharsets.UTF_8));
    } catch (IllegalArgumentException ex) {
        throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST), ex);
    }
    String credentialsString = new String(decodedCredentials, StandardCharsets.UTF_8);
    String[] credentials = credentialsString.split(":", 2);
    if (credentials.length != 2 || !StringUtils.hasText(credentials[0]) || !StringUtils.hasText(credentials[1])) {
        throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST));
    }
    String clientID;
    String clientSecret;
    try {
        clientID = URLDecoder.decode(credentials[0], StandardCharsets.UTF_8.name());
        clientSecret = URLDecoder.decode(credentials[1], StandardCharsets.UTF_8.name());
    } catch (Exception ex) {
        throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST), ex);
    }
    return new OAuth2ClientAuthenticationToken(clientID, clientSecret, ClientAuthenticationMethod.BASIC, extractAdditionalParameters(request));
}

See More Examples