org.springframework.security.core.context.ReactiveSecurityContextHolder Java Examples

The following examples show how to use org.springframework.security.core.context.ReactiveSecurityContextHolder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(HttpHeaders requestHeaders, int productId, int delay, int faultPercent) {

    HttpHeaders headers = getHeaders(requestHeaders, "X-group");

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(headers, productId, delay, faultPercent)
                .onErrorMap(RetryExceptionWrapper.class, retryException -> retryException.getCause())
                .onErrorReturn(CircuitBreakerOpenException.class, getProductFallbackValue(productId)),
            integration.getRecommendations(headers, productId).collectList(),
            integration.getReviews(headers, productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log();
}
 
Example #2
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(HttpHeaders requestHeaders, int productId, int delay, int faultPercent) {

    LOG.info("Will get composite product info for product.id={}", productId);

    HttpHeaders headers = getHeaders(requestHeaders, "X-group");

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(headers, productId, delay, faultPercent)
                .onErrorMap(RetryExceptionWrapper.class, retryException -> retryException.getCause())
                .onErrorReturn(CircuitBreakerOpenException.class, getProductFallbackValue(productId)),
            integration.getRecommendations(headers, productId).collectList(),
            integration.getReviews(headers, productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log(null, FINE);
}
 
Example #3
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(HttpHeaders requestHeaders, int productId, int delay, int faultPercent) {

    LOG.info("Will get composite product info for product.id={}", productId);

    HttpHeaders headers = getHeaders(requestHeaders, "X-group");

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(headers, productId, delay, faultPercent)
                .onErrorMap(RetryExceptionWrapper.class, retryException -> retryException.getCause())
                .onErrorReturn(CircuitBreakerOpenException.class, getProductFallbackValue(productId)),
            integration.getRecommendations(headers, productId).collectList(),
            integration.getReviews(headers, productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log(null, FINE);
}
 
Example #4
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(int productId, int delay, int faultPercent) {

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(productId, delay, faultPercent)
                .onErrorMap(RetryExceptionWrapper.class, retryException -> retryException.getCause())
                .onErrorReturn(CircuitBreakerOpenException.class, getProductFallbackValue(productId)),
            integration.getRecommendations(productId).collectList(),
            integration.getReviews(productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log();
}
 
Example #5
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(int productId, int delay, int faultPercent) {

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(productId, delay, faultPercent)
                .onErrorMap(RetryExceptionWrapper.class, retryException -> retryException.getCause())
                .onErrorReturn(CircuitBreakerOpenException.class, getProductFallbackValue(productId)),
            integration.getRecommendations(productId).collectList(),
            integration.getReviews(productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log();
}
 
Example #6
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(int productId, int delay, int faultPercent) {

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(productId, delay, faultPercent)
                .onErrorMap(RetryExceptionWrapper.class, retryException -> retryException.getCause())
                .onErrorReturn(CircuitBreakerOpenException.class, getProductFallbackValue(productId)),
            integration.getRecommendations(productId).collectList(),
            integration.getReviews(productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log();
}
 
Example #7
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(int productId, int delay, int faultPercent) {

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(productId, delay, faultPercent)
                .onErrorMap(RetryExceptionWrapper.class, retryException -> retryException.getCause())
                .onErrorReturn(CircuitBreakerOpenException.class, getProductFallbackValue(productId)),
            integration.getRecommendations(productId).collectList(),
            integration.getReviews(productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log();
}
 
Example #8
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(int productId, int delay, int faultPercent) {

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(productId, delay, faultPercent)
                .onErrorMap(RetryExceptionWrapper.class, retryException -> retryException.getCause())
                .onErrorReturn(CircuitBreakerOpenException.class, getProductFallbackValue(productId)),
            integration.getRecommendations(productId).collectList(),
            integration.getReviews(productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log();
}
 
Example #9
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(int productId) {

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(productId),
            integration.getRecommendations(productId).collectList(),
            integration.getReviews(productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log();
}
 
Example #10
Source File: ReactiveSecurityContext.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
/**
 * Obtain the Token object from the Spring Reactive SecurityContext
 *
 * @return Mono object of type token or error of class
 *         {@link AccessDeniedException} in case there is no token, user is not
 *         authenticated.
 */
static public Mono<XsuaaToken> getToken() {
	return ReactiveSecurityContextHolder.getContext()
			.switchIfEmpty(Mono.error(new AccessDeniedException("Access forbidden: not authenticated")))
			.map(SecurityContext::getAuthentication)
			.map(Authentication::getCredentials)
			.map(credentials -> new XsuaaToken((Jwt) credentials))
			.doOnSuccess(token -> logger.info("Got Jwt token: {}", token))
			.doOnError(throwable -> logger.error("ERROR to getToken", throwable));
}
 
Example #11
Source File: ReactiveSecurityContextTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void unauthenticated() {
	SecurityContext expectedContext = new SecurityContextImpl();
	ReactiveSecurityContextHolder.withSecurityContext(Mono.just(expectedContext));
	Mono<XsuaaToken> tokenMono = ReactiveSecurityContext.getToken();

	StepVerifier.create(tokenMono)
			.expectError(AccessDeniedException.class)
			.verify();
}
 
Example #12
Source File: ReactiveSecurityContextTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void authenticated() {
	XsuaaToken jwt = new XsuaaToken(new JwtGenerator().setUserName("user").getToken());
	SecurityContext expectedContext = new SecurityContextImpl(
			new TestingAuthenticationToken("user", jwt, "ROLE_USER"));
	ReactiveSecurityContextHolder.withSecurityContext(Mono.just(expectedContext));
	Mono<XsuaaToken> tokenMono = ReactiveSecurityContext.getToken();

	StepVerifier.create(tokenMono)
			.expectNext(jwt)
			.verifyComplete();
}
 
Example #13
Source File: DefaultPaymentService.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Override
public Mono<String> send(Mono<Payment> payment) {
	return payment.zipWith(
					ReactiveSecurityContextHolder.getContext(),
					(p, c) -> p.withUser(c.getAuthentication().getName())
				  )
	              .flatMap(p -> client.post()
	                                  .syncBody(p)
	                                  .retrieve()
	                                  .bodyToMono(String.class)
	                                  .then(paymentRepository.save(p)))
	              .map(Payment::getId);
}
 
Example #14
Source File: DefaultPaymentService.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Override
public Flux<Payment> list() {
	return ReactiveSecurityContextHolder
			.getContext()
			.map(SecurityContext::getAuthentication)
			.map(Principal::getName)
			.flatMapMany(paymentRepository::findAllByUser);
}
 
Example #15
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
@Override
public Mono<ProductAggregate> getCompositeProduct(int productId) {

    return Mono.zip(
            values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()),
            ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC),
            integration.getProduct(productId),
            integration.getRecommendations(productId).collectList(),
            integration.getReviews(productId).collectList())
        .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString()))
        .log();
}
 
Example #16
Source File: SecuredProfileController.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@GetMapping("/profiles")
public Mono<Profile> getProfile() {
    return ReactiveSecurityContextHolder
        .getContext()
        .map(SecurityContext::getAuthentication)
        .flatMap(auth -> profileService.getByUser(auth.getName()));
}
 
Example #17
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> deleteCompositeProduct(int productId) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalDeleteCompositeProduct(sc, productId)).then();
}
 
Example #18
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> deleteCompositeProduct(int productId) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalDeleteCompositeProduct(sc, productId)).then();
}
 
Example #19
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> createCompositeProduct(ProductAggregate body) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalCreateCompositeProduct(sc, body)).then();
}
 
Example #20
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> deleteCompositeProduct(int productId) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalDeleteCompositeProduct(sc, productId)).then();
}
 
Example #21
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> createCompositeProduct(ProductAggregate body) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalCreateCompositeProduct(sc, body)).then();
}
 
Example #22
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> deleteCompositeProduct(int productId) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalDeleteCompositeProduct(sc, productId)).then();
}
 
Example #23
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> createCompositeProduct(ProductAggregate body) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalCreateCompositeProduct(sc, body)).then();
}
 
Example #24
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> deleteCompositeProduct(int productId) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalDeleteCompositeProduct(sc, productId)).then();
}
 
Example #25
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> createCompositeProduct(ProductAggregate body) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalCreateCompositeProduct(sc, body)).then();
}
 
Example #26
Source File: ResourceServerConfiguration.java    From open-cloud with MIT License 4 votes vote down vote up
@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
    // 自定义oauth2 认证, 使用redis读取token,而非jwt方式
    JsonAuthenticationEntryPoint entryPoint = new JsonAuthenticationEntryPoint(accessLogService);
    JsonAccessDeniedHandler accessDeniedHandler = new JsonAccessDeniedHandler(accessLogService);
    AccessManager accessManager = new AccessManager(apiresourceLocator, apiProperties);
    AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(new RedisAuthenticationManager(new RedisTokenStore(redisConnectionFactory)));
    oauth2.setServerAuthenticationConverter(new ServerBearerTokenAuthenticationConverter());
    oauth2.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(entryPoint));
    oauth2.setAuthenticationSuccessHandler(new ServerAuthenticationSuccessHandler() {
        @Override
        public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
            ServerWebExchange exchange = webFilterExchange.getExchange();
            SecurityContextServerWebExchange securityContextServerWebExchange = new SecurityContextServerWebExchange(exchange, ReactiveSecurityContextHolder.getContext().subscriberContext(
                    ReactiveSecurityContextHolder.withAuthentication(authentication)
            ));
            return webFilterExchange.getChain().filter(securityContextServerWebExchange);
        }
    });
    http
            .httpBasic().disable()
            .csrf().disable()
            .authorizeExchange()
            .pathMatchers("/").permitAll()
            // 动态权限验证
            .anyExchange().access(accessManager)
            .and().exceptionHandling()
            .accessDeniedHandler(accessDeniedHandler)
            .authenticationEntryPoint(entryPoint).and()
            // 日志前置过滤器
            .addFilterAt(new PreRequestFilter(), SecurityWebFiltersOrder.FIRST)
            // 跨域过滤器
            .addFilterAt(corsFilter(), SecurityWebFiltersOrder.CORS)
            // 签名验证过滤器
            .addFilterAt(new PreSignatureFilter(baseAppServiceClient,apiProperties, new JsonSignatureDeniedHandler(accessLogService)), SecurityWebFiltersOrder.CSRF)
            // 访问验证前置过滤器
            .addFilterAt(new PreCheckFilter(accessManager, accessDeniedHandler), SecurityWebFiltersOrder.CSRF)
            // oauth2认证过滤器
            .addFilterAt(oauth2, SecurityWebFiltersOrder.AUTHENTICATION)
            // 日志过滤器
            .addFilterAt(new AccessLogFilter(accessLogService), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);
    return http.build();
}
 
Example #27
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> createCompositeProduct(ProductAggregate body) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalCreateCompositeProduct(sc, body)).then();
}
 
Example #28
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> deleteCompositeProduct(int productId) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalDeleteCompositeProduct(sc, productId)).then();
}
 
Example #29
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> createCompositeProduct(ProductAggregate body) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalCreateCompositeProduct(sc, body)).then();
}
 
Example #30
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> deleteCompositeProduct(int productId) {
    return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalDeleteCompositeProduct(sc, productId)).then();
}