org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository Java Examples

The following examples show how to use org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository. 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: SecurityConfig.java    From spring-reactive-sample with GNU General Public License v3.0 5 votes vote down vote up
@Bean
 SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
    return http
         .csrf().disable()
             //.and()
.authorizeExchange()
	.anyExchange().authenticated()
	.and()
.httpBasic().securityContextRepository(new WebSessionServerSecurityContextRepository())
	.and()
.formLogin()
	.and()
         .build();
 }
 
Example #2
Source File: OAuth2SecurityConfigUtils.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static void forLogin(
        final ServerHttpSecurity http,
        final AMType amType,
        final ApplicationContext ctx) {

    ReactiveClientRegistrationRepository clientRegistrationRepository =
            ctx.getBean(ReactiveClientRegistrationRepository.class);

    ReactiveOAuth2AuthorizedClientService authorizedClientService =
            new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);
    ServerOAuth2AuthorizedClientRepository authorizedClientRepository =
            new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);

    OAuth2AuthorizationRequestRedirectWebFilter authRequestRedirectFilter =
            new OAuth2AuthorizationRequestRedirectWebFilter(clientRegistrationRepository);

    AuthenticationWebFilter authenticationFilter =
            new OAuth2LoginAuthenticationWebFilter(authenticationManager(amType), authorizedClientRepository);
    authenticationFilter.setRequiresAuthenticationMatcher(
            new PathPatternParserServerWebExchangeMatcher("/login/oauth2/code/{registrationId}"));
    authenticationFilter.setServerAuthenticationConverter(
            new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(clientRegistrationRepository));
    authenticationFilter.setAuthenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler());
    authenticationFilter.setAuthenticationFailureHandler((exchange, ex) -> Mono.error(ex));
    authenticationFilter.setSecurityContextRepository(new WebSessionServerSecurityContextRepository());

    MediaTypeServerWebExchangeMatcher htmlMatcher = new MediaTypeServerWebExchangeMatcher(MediaType.TEXT_HTML);
    htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
    ServerAuthenticationEntryPoint entrypoint =
            new RedirectServerAuthenticationEntryPoint("/oauth2/authorization/" + amType.name());
    http.exceptionHandling().authenticationEntryPoint(new DelegateEntry(htmlMatcher, entrypoint).getEntryPoint());

    http.addFilterAt(authRequestRedirectFilter, SecurityWebFiltersOrder.HTTP_BASIC);
    http.addFilterAt(authenticationFilter, SecurityWebFiltersOrder.AUTHENTICATION);
}
 
Example #3
Source File: PrincipalToRequestHeaderFilterFactory.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(final NameConfig config) {
    return (exchange, chain) -> exchange.getSession().
            flatMap(session -> Mono.justOrEmpty(Optional.ofNullable(
            cacheManager.getCache(SessionConfig.DEFAULT_CACHE).get(session.getId(), Session.class)).
            map(cachedSession -> {
                String principal = null;

                SecurityContext ctx = cachedSession.getAttribute(
                        WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME);
                if (ctx != null && ctx.getAuthentication() != null) {
                    if (ctx.getAuthentication().getPrincipal() instanceof OidcUser) {
                        principal = ((OidcUser) ctx.getAuthentication().getPrincipal()).
                                getIdToken().getTokenValue();
                    } else if (ctx.getAuthentication().getPrincipal() instanceof OAuth2User) {
                        principal = Objects.toString(((OAuth2User) ctx.getAuthentication().getPrincipal()).
                                getAttributes().get(StandardClaimNames.PREFERRED_USERNAME), null);
                    } else {
                        principal = ctx.getAuthentication().getName();
                    }
                }

                return principal;
            }))).
            transform(principal -> principal.flatMap(p -> StringUtils.isEmpty(p)
            ? chain.filter(exchange)
            : chain.filter(exchange.mutate().
                    request(exchange.getRequest().mutate().
                            headers(headers -> headers.add(config.getName(), p)).build()).
                    build()))).
            switchIfEmpty(chain.filter(exchange));
}
 
Example #4
Source File: WebFluxSecurityConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public SecurityWebFilterChain webSessionSpringSecurityFilterChain(ServerHttpSecurity http) {
    http.authorizeExchange()
            .anyExchange().authenticated()
            .and()
            .httpBasic()
            .securityContextRepository(new WebSessionServerSecurityContextRepository())
            .and()
            .formLogin();

    http.csrf().disable();

    return http.build();

}
 
Example #5
Source File: SecurityConfiguration.java    From webFluxTemplate with MIT License 4 votes vote down vote up
@Bean
public WebSessionServerSecurityContextRepository securityContextRepository() {
    return new WebSessionServerSecurityContextRepository();
}
 
Example #6
Source File: RouteProviderTest.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void principalToRequestHeader() throws IllegalArgumentException, IllegalAccessException {
    // first mock...
    OidcIdToken oidcIdToken = mock(OidcIdToken.class);
    when(oidcIdToken.getTokenValue()).thenReturn("john.doe");

    OidcUser user = mock(OidcUser.class);
    when(user.getIdToken()).thenReturn(oidcIdToken);

    Authentication authentication = mock(Authentication.class);
    when(authentication.getPrincipal()).thenReturn(user);

    MapSession session = new MapSession();
    session.setAttribute(
            WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME,
            new SecurityContextImpl(authentication));

    Cache cache = mock(Cache.class);
    when(cache.get(anyString(), eq(Session.class))).thenReturn(session);

    CacheManager cacheManager = mock(CacheManager.class);
    when(cacheManager.getCache(eq(SessionConfig.DEFAULT_CACHE))).thenReturn(cache);

    PrincipalToRequestHeaderFilterFactory factory = new PrincipalToRequestHeaderFilterFactory();
    ReflectionTestUtils.setField(factory, "cacheManager", cacheManager);
    ctx.getBeanFactory().registerSingleton(PrincipalToRequestHeaderFilterFactory.class.getName(), factory);

    // ...then test
    stubFor(get(urlEqualTo("/principalToRequestHeader")).willReturn(aResponse()));

    SRARouteTO route = new SRARouteTO();
    route.setKey("principalToRequestHeader");
    route.setTarget(URI.create("http://localhost:" + wiremockPort));
    route.setType(SRARouteType.PROTECTED);
    route.getFilters().add(new SRARouteFilter.Builder().
            factory(SRARouteFilterFactory.PRINCIPAL_TO_REQUEST_HEADER).args("HTTP_REMOTE_USER").build());

    SyncopeCoreTestingServer.ROUTES.put(route.getKey(), route);
    routeRefresher.refresh();

    webClient.get().uri("/principalToRequestHeader").exchange().
            expectStatus().isOk();

    verify(getRequestedFor(urlEqualTo("/principalToRequestHeader")).
            withHeader("HTTP_REMOTE_USER", equalTo("john.doe")));
}