类org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository源码实例Demo

下面列出了怎么用org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: spring-reactive-sample   文件: SecurityConfig.java
@Bean
 SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
    return http
         .csrf().disable()
             //.and()
.authorizeExchange()
	.anyExchange().authenticated()
	.and()
.httpBasic().securityContextRepository(new WebSessionServerSecurityContextRepository())
	.and()
.formLogin()
	.and()
         .build();
 }
 
源代码2 项目: syncope   文件: OAuth2SecurityConfigUtils.java
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);
}
 
@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));
}
 
源代码4 项目: tutorials   文件: WebFluxSecurityConfig.java
@Bean
public SecurityWebFilterChain webSessionSpringSecurityFilterChain(ServerHttpSecurity http) {
    http.authorizeExchange()
            .anyExchange().authenticated()
            .and()
            .httpBasic()
            .securityContextRepository(new WebSessionServerSecurityContextRepository())
            .and()
            .formLogin();

    http.csrf().disable();

    return http.build();

}
 
源代码5 项目: webFluxTemplate   文件: SecurityConfiguration.java
@Bean
public WebSessionServerSecurityContextRepository securityContextRepository() {
    return new WebSessionServerSecurityContextRepository();
}
 
源代码6 项目: syncope   文件: RouteProviderTest.java
@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")));
}
 
 类方法
 同包方法