Java Code Examples for org.springframework.security.config.web.server.SecurityWebFiltersOrder

The following examples show how to use org.springframework.security.config.web.server.SecurityWebFiltersOrder. These examples are extracted from open source projects. 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 Project: webFluxTemplate   Source File: SecurityConfiguration.java    License: MIT License 6 votes vote down vote up
@Bean
public SecurityWebFilterChain springSecurityFilterChain(final ServerHttpSecurity http,
                                                        final JwtAuthenticationWebFilter authenticationWebFilter,
                                                        final UnauthorizedAuthenticationEntryPoint entryPoint) {
    // We must override AuthenticationEntryPoint because if AuthenticationWebFilter didn't kicked in
    // (i.e. there are no required headers) then default behavior is to display HttpBasicAuth,
    // so we just return unauthorized to override it.
    // Filter tries to authenticate each request if it contains required headers.
    // Finally, we disable all default security.
    http
            .exceptionHandling()
            .authenticationEntryPoint(entryPoint)
            .and()
            .addFilterAt(authenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION)
            .authorizeExchange()
            .pathMatchers(AUTH_WHITELIST).permitAll()
            .anyExchange().authenticated()
            .and()
            .httpBasic().disable()
            .formLogin().disable()
            .csrf().disable()
            .logout().disable();
    return http.build();
}
 
Example 2
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    //认证处理器
    ReactiveAuthenticationManager customAuthenticationManager = new CustomAuthenticationManager(tokenStore);
    JsonAuthenticationEntryPoint entryPoint = new JsonAuthenticationEntryPoint();
    //token转换器
    ServerBearerTokenAuthenticationConverter tokenAuthenticationConverter = new ServerBearerTokenAuthenticationConverter();
    tokenAuthenticationConverter.setAllowUriQueryParameter(true);
    //oauth2认证过滤器
    AuthenticationWebFilter oauth2Filter = new AuthenticationWebFilter(customAuthenticationManager);
    oauth2Filter.setServerAuthenticationConverter(tokenAuthenticationConverter);
    oauth2Filter.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(entryPoint));
    oauth2Filter.setAuthenticationSuccessHandler(new Oauth2AuthSuccessHandler());
    http.addFilterAt(oauth2Filter, SecurityWebFiltersOrder.AUTHENTICATION);

    ServerHttpSecurity.AuthorizeExchangeSpec authorizeExchange = http.authorizeExchange();
    if (securityProperties.getAuth().getHttpUrls().length > 0) {
        authorizeExchange.pathMatchers(securityProperties.getAuth().getHttpUrls()).authenticated();
    }
    if (securityProperties.getIgnore().getUrls().length > 0) {
        authorizeExchange.pathMatchers(securityProperties.getIgnore().getUrls()).permitAll();
    }
    authorizeExchange
            .pathMatchers(HttpMethod.OPTIONS).permitAll()
            .anyExchange()
                .access(permissionAuthManager)
            .and()
                .exceptionHandling()
                    .accessDeniedHandler(new JsonAccessDeniedHandler())
                    .authenticationEntryPoint(entryPoint)
            .and()
                .headers()
                    .frameOptions()
                    .disable()
            .and()
                .httpBasic().disable()
                .csrf().disable();
    return http.build();
}
 
Example 3
Source Project: syncope   Source File: OAuth2SecurityConfigUtils.java    License: 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 4
Source Project: syncope   Source File: OAuth2SecurityConfigUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void forLogout(
        final ServerHttpSecurity.AuthorizeExchangeSpec builder,
        final AMType amType,
        final CacheManager cacheManager,
        final LogoutRouteMatcher logoutRouteMatcher,
        final ConfigurableApplicationContext ctx) {

    builder.and().logout().disable();

    LogoutWebFilter logoutWebFilter = new LogoutWebFilter();
    logoutWebFilter.setRequiresLogoutMatcher(logoutRouteMatcher);
    logoutWebFilter.setLogoutHandler(new SessionRemovalServerLogoutHandler(cacheManager));

    if (AMType.OIDC == amType) {
        try {
            OidcClientInitiatedServerLogoutSuccessHandler handler = ApplicationContextUtils.getOrCreateBean(
                    ctx,
                    OidcClientInitiatedServerLogoutSuccessHandler.class.getName(),
                    OidcClientInitiatedServerLogoutSuccessHandler.class);
            logoutWebFilter.setLogoutSuccessHandler(handler);
        } catch (ClassNotFoundException e) {
            LOG.error("While creating instance of {}",
                    OidcClientInitiatedServerLogoutSuccessHandler.class.getName(), e);
        }
    }

    builder.and().addFilterAt(logoutWebFilter, SecurityWebFiltersOrder.LOGOUT);
}
 
Example 5
Source Project: tutorials   Source File: CustomWebSecurityConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    return http
      .authorizeExchange()
      .pathMatchers("/**")
      .authenticated()
      .and()
      .httpBasic()
      .disable()
      .addFilterAfter(authenticationWebFilter(), SecurityWebFiltersOrder.REACTOR_CONTEXT)
      .build();
}
 
Example 6
Source Project: open-cloud   Source File: ResourceServerConfiguration.java    License: 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();
}