org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler Java Examples

The following examples show how to use org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler. 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 pizzeria with MIT License 6 votes vote down vote up
@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
    ContentNegotiationStrategy contentNegotiationStrategy = new HeaderContentNegotiationStrategy();

    MediaTypeRequestMatcher jsonMediaTypeRequestMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy, MediaType.APPLICATION_JSON);
    jsonMediaTypeRequestMatcher.setUseEquals(true);

    LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler = new LinkedHashMap<>();
    matcherToHandler.put(jsonMediaTypeRequestMatcher, new HttpStatusReturningLogoutSuccessHandler());

    DelegatingLogoutSuccessHandler delegatingLogoutSuccessHandler = new DelegatingLogoutSuccessHandler(matcherToHandler);

    SimpleUrlLogoutSuccessHandler simpleUrlLogoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
    simpleUrlLogoutSuccessHandler.setUseReferer(true);
    simpleUrlLogoutSuccessHandler.setDefaultTargetUrl("/");

    delegatingLogoutSuccessHandler.setDefaultLogoutSuccessHandler(simpleUrlLogoutSuccessHandler);

    return delegatingLogoutSuccessHandler;
}
 
Example #2
Source File: WebSecurityConfig.java    From Auth-service with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {


    http.csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .and()
            .requestMatchers().antMatchers("/**")
            .and().authorizeRequests()
            .antMatchers("/**").permitAll()
            .anyRequest().authenticated()
            .and().formLogin().permitAll()
            .and().logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
            .addLogoutHandler(customLogoutHandler());
}
 
Example #3
Source File: SecurityConfig.java    From microservice-integration with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .requestMatchers().antMatchers("/**")
            .and().authorizeRequests()
            .antMatchers("/**").permitAll()
            .anyRequest().authenticated()
            .and().logout()
            .logoutUrl("/logout")
            .clearAuthentication(true)
            .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
            .addLogoutHandler(customLogoutHandler());


}
 
Example #4
Source File: MvcConfiguration.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic()
        .and()
            .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/user/**")
                .hasRole("USER")
        .and()
            .logout()
                .logoutUrl("/user/logout")
                .addLogoutHandler(logoutHandler)
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))
                .permitAll()
        .and()
            .csrf()
                .disable()
            .formLogin()
                .disable();
}
 
Example #5
Source File: SecurityConfig.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http.csrf().disable();

	http.authorizeRequests()
			.anyRequest().authenticated();
	http.formLogin().loginPage("/login.html").loginProcessingUrl("/user/login")
			.successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler);

	// 基于密码 等模式可以无session,不支持授权码模式
	if (authenticationEntryPoint != null) {
		http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
		http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

	} else {
		// 授权码模式单独处理,需要session的支持,此模式可以支持所有oauth2的认证
		http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
	}

	http.logout().logoutSuccessUrl("/login.html")
			.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
			.addLogoutHandler(oauthLogoutHandler).clearAuthentication(true);

	//增加验证码处理
	http.apply(validateCodeSecurityConfig) ;
	// http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
	// 解决不允许显示在iframe的问题
	http.headers().frameOptions().disable();
	http.headers().cacheControl();

}
 
Example #6
Source File: SecurityConfig.java    From eds-starter6-jpa with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	// @formatter:off
	http
	  //.headers()
	    //.frameOptions().sameOrigin()
	  //  .and()
	  .authorizeRequests()
	    .antMatchers("/index.html", "/csrf", "/", "/router").permitAll()
	    .antMatchers("/info", "/health").permitAll()
	    .anyRequest().authenticated()
	    .and()
	  .rememberMe()
           .rememberMeServices(this.rememberMeServices)
           .key(this.appProperties.getRemembermeCookieKey())
	    .and()
	  .formLogin()
           .successHandler(this.authenticationSuccessHandler)
           .failureHandler(new JsonAuthFailureHandler())
	    .permitAll()
	    .and()
	  .logout()
           .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
           .deleteCookies("JSESSIONID")
	    .permitAll()
	    .and()
	  .exceptionHandling()
           .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
	// @formatter:on
}
 
Example #7
Source File: ServerSecurityConfig.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@Override
	protected void configure(final HttpSecurity http) throws Exception {

		final String[] allowedUrls = new String[] {
				"/",
				"/index.html",
				"/static/**",
				"/locales/**",
				"/manifest.json",
				"/login",
				"/error",
				"/rest/user/loggedin",
				"/rest/attachment/**"
		};
		http
			.authorizeRequests(a -> a
				.antMatchers(allowedUrls).permitAll()
				.antMatchers(HttpMethod.PUT, "/rest/reports/**").permitAll()
				.antMatchers(HttpMethod.POST, "/rest/reports/**").permitAll()
				.anyRequest().authenticated()
			)
			.csrf(c -> c
//				.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
//				.ignoringAntMatchers("/login", "/logout")
				.disable()) // TODO - we probably want CSRF on, but it's failing PUT/POST requests atm for some reason.
			.logout(l -> l
				// No logout URL as the frontend provides the logout redirect.
				.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))
				.permitAll()
			);
		http.oauth2Login(a -> a.loginPage("/"));
		http.formLogin(a -> a.loginPage("/").loginProcessingUrl("/login"));
	}
 
Example #8
Source File: WebSecurityConfig.java    From metron with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/", "/home", "/login").permitAll()
            .antMatchers("/app/**").permitAll()
            .antMatchers("/vendor/**").permitAll()
            .antMatchers("/fonts/**").permitAll()
            .antMatchers("/assets/images/**").permitAll()
            .antMatchers("/*.js").permitAll()
            .antMatchers("/*.ttf").permitAll()
            .antMatchers("/*.woff2").permitAll()
            .anyRequest().authenticated()
            .and().httpBasic()
            .and()
            .logout()
            .logoutUrl("/api/v1/logout")
            .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
            .invalidateHttpSession(true)
            .deleteCookies("JSESSIONID", knoxCookie);

    List<String> activeProfiles = Arrays.asList(environment.getActiveProfiles());
    if (activeProfiles.contains(MetronRestConstants.CSRF_ENABLE_PROFILE)) {
        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    } else {
        http.csrf().disable();
    }
    if (activeProfiles.contains(MetronRestConstants.KNOX_PROFILE)) {
      http.addFilterAt(new KnoxSSOAuthenticationFilter(userSearchBase, knoxKeyFile, knoxKeyString,
              knoxCookie, ldapTemplate), UsernamePasswordAuthenticationFilter.class);
    }
}
 
Example #9
Source File: SecurityConfig.java    From springsecuritytotp with MIT License 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
  http.csrf(customizer -> customizer.disable()).authorizeRequests(customizer -> {
    customizer
        .antMatchers("/authenticate", "/signin", "/verify-totp",
            "/verify-totp-additional-security", "/signup", "/signup-confirm-secret")
        .permitAll().anyRequest().authenticated();
  }).logout(customizer -> customizer
      .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()));
}
 
Example #10
Source File: SecurityConfig.java    From ChengFeng1.5 with MIT License 4 votes vote down vote up
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/images/**").permitAll()//设置静态资源无权限限制
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("/configuration/ui").permitAll()
                .antMatchers("/configuration/security").permitAll()
                .antMatchers("/community/listall","/user/registry").permitAll()//指定可以直接访问的url
                .antMatchers("/file/upload","/file/uploads","/user/login").permitAll()//指定可以直接访问的url
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .requestMatchers(CorsUtils::isCorsRequest).permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin().disable()
                .sessionManagement().disable()
//                .headers().addHeaderWriter(new StaticHeadersWriter(Arrays.asList(
//                new Header("Access-control-Allow-Origin","*"),
//                new Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"),
//                new Header("Access-Control-Max-Age", "3600"),
//                new Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"),
//                new Header("Access-Control-Expose-Headers","Authorization"))))
//                .and()
                //登录请求的过滤
                .apply(new UserLoginConfigurer<>()).loginSuccessHandler(userLoginSuccessHandler())
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler())
                .and()
                //token请求的过滤
                .apply(new TokenLoginConfigurer<>())
                .tokenValidSuccessHandler(tokenRefreshSuccessHandler())
                .permissiveRequestUrls("/logout","/community/listall","/images/**","/user/registry","/swagger-resources/**","/swagger-ui.html")
                .permissiveRequestUrls("/webjars/**","/v2/api-docs","/configuration/ui","/configuration/security","/file/upload","/file/uploads","/user/login")
                .and()
                //登出的过滤器
                .logout()
                .addLogoutHandler(tokenClearLogoutHandler())
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
                .and()
                .sessionManagement().disable()
                .cors().and().exceptionHandling().accessDeniedHandler(accessDeniedHandler());
    }
 
Example #11
Source File: CrustConfigurerAdapter.java    From Milkomeda with MIT License 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .sessionManagement().sessionCreationPolicy(props.isStateless() ?
            SessionCreationPolicy.STATELESS : SessionCreationPolicy.IF_REQUIRED).and()
        .formLogin().disable()
        // 支持跨域,从CorsConfigurationSource中取跨域配置
        .cors()
            .and()
            // 禁用iframe跨域
            .headers()
            .frameOptions()
            .disable();

    // 配置预设置
    presetConfigure(http);

    // 如果是无状态方式
    if (props.isStateless()) {
        // 应用Token认证配置器,忽略登出请求
        http.apply(new CrustAuthenticationConfigurer<>(authFailureHandler())).permissiveRequestUrls(props.getLogoutUrl())
                .and()
                .logout()
                .logoutUrl(props.getLogoutUrl())
                .addLogoutHandler((req, res, auth) -> CrustContext.invalidate())
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
    } else {
        // 自定义session方式登录
        http.httpBasic().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint(props.getLoginUrl()))
                .and()
                .sessionManagement()
                .sessionFixation().changeSessionId()
                .sessionAuthenticationErrorUrl(props.getLoginUrl())
                .sessionAuthenticationFailureHandler(authFailureHandler().get()).and()
        .logout()
                .logoutUrl(props.getLogoutUrl())
                .addLogoutHandler((req, res, auth) -> CrustContext.invalidate())
                .logoutSuccessUrl(props.getLoginUrl())
                .invalidateHttpSession(true);
    }
}
 
Example #12
Source File: SecurityConfiguration.java    From api-layer with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors().and()
        .csrf().disable()
        .headers()
        .httpStrictTransportSecurity().disable()
        .frameOptions().disable()
        .and()
        .exceptionHandling().authenticationEntryPoint(handlerInitializer.getBasicAuthUnauthorizedHandler())

        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

        // login endpoint
        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, authConfigurationProperties.getGatewayLoginEndpoint()).permitAll()

        // ticket endpoint
        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, authConfigurationProperties.getGatewayTicketEndpoint()).authenticated()
        .and().x509()
        .userDetailsService(x509UserDetailsService())

        // logout endpoint
        .and()
        .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher(authConfigurationProperties.getGatewayLogoutEndpoint(), HttpMethod.POST.name()))
        .addLogoutHandler(logoutHandler())
        .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.NO_CONTENT))
        .permitAll()

        // endpoint protection
        .and()
        .authorizeRequests()
        .antMatchers("/application/health", "/application/info").permitAll()
        .antMatchers("/application/**").authenticated()

        // auth controller
        .and()
        .authorizeRequests()
        .antMatchers(
            AuthController.CONTROLLER_PATH + AuthController.ALL_PUBLIC_KEYS_PATH,
            AuthController.CONTROLLER_PATH + AuthController.CURRENT_PUBLIC_KEYS_PATH
        ).permitAll()
        .and()
        .authorizeRequests()
        .antMatchers(AuthController.CONTROLLER_PATH + AuthController.INVALIDATE_PATH, AuthController.CONTROLLER_PATH + AuthController.DISTRIBUTE_PATH).authenticated()
        .and().x509()
        .x509AuthenticationFilter(apimlX509AuthenticationFilter())
        .subjectPrincipalRegex(EXTRACT_USER_PRINCIPAL_FROM_COMMON_NAME)
        .userDetailsService(x509UserDetailsService())

        // cache controller
        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.DELETE, CacheServiceController.CONTROLLER_PATH, CacheServiceController.CONTROLLER_PATH + "/**").authenticated()
        .and().x509()
        .x509AuthenticationFilter(apimlX509AuthenticationFilter())
        .subjectPrincipalRegex(EXTRACT_USER_PRINCIPAL_FROM_COMMON_NAME)
        .userDetailsService(x509UserDetailsService())

        // add filters - login, query, ticket
        .and()
        .addFilterBefore(loginFilter(authConfigurationProperties.getGatewayLoginEndpoint()), UsernamePasswordAuthenticationFilter.class)
        .addFilterBefore(queryFilter(authConfigurationProperties.getGatewayQueryEndpoint()), UsernamePasswordAuthenticationFilter.class)
        .addFilterBefore(ticketFilter(authConfigurationProperties.getGatewayTicketEndpoint()), UsernamePasswordAuthenticationFilter.class)
        .addFilterBefore(basicFilter(), UsernamePasswordAuthenticationFilter.class)
        .addFilterBefore(cookieFilter(), UsernamePasswordAuthenticationFilter.class);
}
 
Example #13
Source File: BaseSecurityConfig.java    From spring-boot-doma2-sample with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    // CookieにCSRFトークンを保存する
    http.csrf()//
            .csrfTokenRepository(new CookieCsrfTokenRepository());

    String[] permittedUrls = { LOGIN_TIMEOUT_URL, FORBIDDEN_URL, ERROR_URL, RESET_PASSWORD_URL,
            CHANGE_PASSWORD_URL };

    http.authorizeRequests()
            // エラー画面は認証をかけない
            .antMatchers(permittedUrls).permitAll()
            // エラー画面以外は、認証をかける
            .anyRequest().authenticated()//
            .and()//
            .exceptionHandling()//
            .authenticationEntryPoint(authenticationEntryPoint())//
            .accessDeniedHandler(accessDeniedHandler());

    http.formLogin()
            // ログイン画面のURL
            .loginPage(LOGIN_URL)
            // 認可を処理するURL
            .loginProcessingUrl(LOGIN_PROCESSING_URL)
            // ログイン成功時の遷移先
            .successForwardUrl(LOGIN_SUCCESS_URL)
            // ログイン失敗時の遷移先
            .failureUrl(LOGIN_FAILURE_URL)
            // ログインIDのパラメータ名
            .usernameParameter("loginId")
            // パスワードのパラメータ名
            .passwordParameter("password").permitAll();

    // ログアウト設定
    http.logout()//
            .logoutRequestMatcher(new AntPathRequestMatcher(LOGOUT_URL))
            // Cookieを破棄する
            .deleteCookies("SESSION", "JSESSIONID", rememberMeCookieName)
            // ログアウト画面のURL
            .logoutUrl(LOGOUT_URL)
            // ログアウト後の遷移先
            .logoutSuccessUrl(LOGOUT_SUCCESS_URL)
            // ajaxの場合は、HTTPステータスを返す
            .defaultLogoutSuccessHandlerFor(new HttpStatusReturningLogoutSuccessHandler(),
                    RequestUtils::isAjaxRequest)
            // セッションを破棄する
            .invalidateHttpSession(true).permitAll();

    // RememberMe
    http.rememberMe().key(REMEMBER_ME_KEY)//
            .rememberMeServices(multiDeviceRememberMeServices());
}
 
Example #14
Source File: BasicAuthSecurityConfiguration.java    From spring-cloud-dashboard with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	final RequestMatcher textHtmlMatcher = new MediaTypeRequestMatcher(
			contentNegotiationStrategy,
			MediaType.TEXT_HTML);

	final String loginPage = dashboard("/#/login");

	final BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
	basicAuthenticationEntryPoint.setRealmName(securityProperties.getBasic().getRealm());
	basicAuthenticationEntryPoint.afterPropertiesSet();

	http
		.csrf()
		.disable()
		.authorizeRequests()
		.antMatchers("/")
		.authenticated()
		.antMatchers(
				dashboard("/**"),
				"/authenticate",
				"/security/info",
				"/features",
				"/assets/**").permitAll()
	.and()
		.formLogin().loginPage(loginPage)
		.loginProcessingUrl(dashboard("/login"))
		.defaultSuccessUrl(dashboard("/")).permitAll()
	.and()
		.logout().logoutUrl(dashboard("/logout"))
			.logoutSuccessUrl(dashboard("/logout-success.html"))
		.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()).permitAll()
	.and().httpBasic()
		.and().exceptionHandling()
		.defaultAuthenticationEntryPointFor(
				new LoginUrlAuthenticationEntryPoint(loginPage),
				textHtmlMatcher)
		.defaultAuthenticationEntryPointFor(basicAuthenticationEntryPoint,
				AnyRequestMatcher.INSTANCE)
	.and()
		.authorizeRequests()
		.anyRequest().authenticated();

	final SessionRepositoryFilter<ExpiringSession> sessionRepositoryFilter = new SessionRepositoryFilter<ExpiringSession>(
			sessionRepository());
	sessionRepositoryFilter
			.setHttpSessionStrategy(new HeaderHttpSessionStrategy());

	http.addFilterBefore(sessionRepositoryFilter,
			ChannelProcessingFilter.class).csrf().disable();
	http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
}