org.springframework.security.web.csrf.CsrfFilter Java Examples

The following examples show how to use org.springframework.security.web.csrf.CsrfFilter. 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: SecurityConfiguration.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .ignoringAntMatchers("/h2-console/**")
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    .and()
        .addFilterBefore(corsFilter, CsrfFilter.class)
        .headers()
        .frameOptions()
        .disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
        .authorizeRequests()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/info").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
}
 
Example #2
Source File: MicroserviceSecurityConfiguration.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .ignoringAntMatchers("/h2-console/**")
        .ignoringAntMatchers("/umu/api/ueditor")
        .ignoringAntMatchers("/ability/model/**")
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    .and()
        .addFilterBefore(corsFilter, CsrfFilter.class)
        .headers()
        .frameOptions()
        .disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
        .authorizeRequests()
        .antMatchers("/api/profile-info").permitAll()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/swagger-resources/configuration/ui").permitAll();
}
 
Example #3
Source File: OAuth2SsoConfiguration.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
        .addFilterBefore(corsFilter, CsrfFilter.class)
        .headers()
        .frameOptions()
        .disable()
    .and()
        .logout()
        .logoutUrl("/api/logout")
        .logoutSuccessHandler(ajaxLogoutSuccessHandler())
    .and()
        .authorizeRequests()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .anyRequest().permitAll()
    .and()
        .requiresChannel()
        .requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null)
        .requiresSecure();
}
 
Example #4
Source File: WebSecurityConfig.java    From spring-boot-security-saml-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Defines the web based security configuration.
 * 
 * @param   http It allows configuring web based security for specific http requests.
 * @throws  Exception 
 */
@Override  
protected void configure(HttpSecurity http) throws Exception {
    http
        .httpBasic()
            .authenticationEntryPoint(samlEntryPoint());      
    http
    		.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
    		.addFilterAfter(samlFilter(), BasicAuthenticationFilter.class)
    		.addFilterBefore(samlFilter(), CsrfFilter.class);
    http        
        .authorizeRequests()
       		.antMatchers("/").permitAll()
       		.antMatchers("/saml/**").permitAll()
       		.antMatchers("/css/**").permitAll()
       		.antMatchers("/img/**").permitAll()
       		.antMatchers("/js/**").permitAll()
       		.anyRequest().authenticated();
    http
    		.logout()
    			.disable();	// The logout procedure is already handled by SAML filters.
}
 
Example #5
Source File: SecurityConfiguration.java    From demo-spring-security-cas with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http.addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class).exceptionHandling()
			.authenticationEntryPoint(casAuthenticationEntryPoint()).and().addFilter(casAuthenticationFilter())
			.addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class)
			.addFilterBefore(requestCasGlobalLogoutFilter(), LogoutFilter.class);

	http.headers().frameOptions().disable().authorizeRequests().antMatchers("/").permitAll()
			.antMatchers("/login", "/logout", "/secure").authenticated().antMatchers("/filtered")
			.hasAuthority(AuthoritiesConstants.ADMIN).anyRequest().authenticated();

	/**
	 * <logout invalidate-session="true" delete-cookies="JSESSIONID" />
	 */
	http.logout().logoutUrl("/logout").logoutSuccessUrl("/").invalidateHttpSession(true)
			.deleteCookies("JSESSIONID");

	// http.csrf();
}
 
Example #6
Source File: OAuthConfiguration.java    From spring-boot-microservices with Apache License 2.0 6 votes vote down vote up
/**
 * Define the security that applies to the proxy
 */
@Override
   public void configure(HttpSecurity http) throws Exception {
       http
       	.authorizeRequests()
       	//Allow access to all static resources without authentication
       	.antMatchers("/","/**/*.html").permitAll()
       	.anyRequest().authenticated()
       	.antMatchers(HttpMethod.GET, "/api/user/**","/api/task/**").access("#oauth2.hasScope('read')")
           .antMatchers(HttpMethod.OPTIONS, "/api/user/**","/api/task/**").access("#oauth2.hasScope('read')")
           .antMatchers(HttpMethod.POST, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')")
           .antMatchers(HttpMethod.PUT, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')")
           .antMatchers(HttpMethod.PATCH, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')")
           .antMatchers(HttpMethod.DELETE, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')")
           .and().csrf().csrfTokenRepository(this.getCSRFTokenRepository())
           .and().addFilterAfter(this.createCSRFHeaderFilter(), CsrfFilter.class);
   }
 
Example #7
Source File: InsightsSecurityConfigurationAdapterSAML.java    From Insights with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	LOG.debug("message Inside InsightsSecurityConfigurationAdapterSAML,HttpSecurity **** {} ",
			ApplicationConfigProvider.getInstance().getAutheticationProtocol());
	if (AUTH_TYPE.equalsIgnoreCase(ApplicationConfigProvider.getInstance().getAutheticationProtocol())) {
		LOG.debug("message Inside SAMLAuthConfig, check http security **** ");

		http.cors();
		http.csrf().ignoringAntMatchers(AuthenticationUtils.CSRF_IGNORE)
				.csrfTokenRepository(authenticationUtils.csrfTokenRepository())
				.and().addFilterAfter(new InsightsCustomCsrfFilter(), CsrfFilter.class);

		http.exceptionHandling().authenticationEntryPoint(samlEntryPoint());
		http.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class).addFilterAfter(samlFilter(),
				BasicAuthenticationFilter.class);

		http.anonymous().disable().authorizeRequests().antMatchers("/error").permitAll().antMatchers("/admin/**")
				.access("hasAuthority('Admin')").antMatchers("/saml/**").permitAll()
				// .antMatchers("/user/insightsso/**").permitAll() ///logout
				.anyRequest().authenticated();

		http.logout().logoutSuccessUrl("/");
	}
}
 
Example #8
Source File: InsightsSecurityConfigurationAdapterKerberos.java    From Insights with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	LOG.debug("message Inside InsightsSecurityConfigurationAdapterKerberos,HttpSecurity **** {} ",
			ApplicationConfigProvider.getInstance().getAutheticationProtocol());
	if (AUTH_TYPE.equalsIgnoreCase(ApplicationConfigProvider.getInstance().getAutheticationProtocol())) {
		LOG.debug("message Inside SAMLAuthConfig, check http security **** ");

		http.cors();
		http.csrf().ignoringAntMatchers(AuthenticationUtils.CSRF_IGNORE)
				.csrfTokenRepository(authenticationUtils.csrfTokenRepository())
				.and().addFilterAfter(new InsightsCustomCsrfFilter(), CsrfFilter.class);

		http.exceptionHandling().authenticationEntryPoint(spnegoEntryPoint());
		http.addFilterAfter(kerberosFilter(),
				BasicAuthenticationFilter.class);

		http.anonymous().disable().authorizeRequests().antMatchers("/error").permitAll().antMatchers("/admin/**")
				.access("hasAuthority('Admin')").antMatchers("/saml/**").permitAll()
				//.antMatchers("/user/insightsso/**").permitAll() ///logout
				.anyRequest().authenticated();

		http.logout().logoutSuccessUrl("/");
	}
}
 
Example #9
Source File: SecurityConfiguration.java    From ServiceCutter with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(final HttpSecurity http) throws Exception {
	http.csrf().ignoringAntMatchers("/websocket/**").and().addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class).exceptionHandling()
			.authenticationEntryPoint(authenticationEntryPoint).and().rememberMe().rememberMeServices(rememberMeServices).rememberMeParameter("remember-me")
			.key(env.getProperty("jhipster.security.rememberme.key")).and().formLogin().loginProcessingUrl("/api/authentication")
			.successHandler(ajaxAuthenticationSuccessHandler).failureHandler(ajaxAuthenticationFailureHandler).usernameParameter("j_username").passwordParameter("j_password")
			.permitAll().and().logout().logoutUrl("/api/logout").logoutSuccessHandler(ajaxLogoutSuccessHandler).deleteCookies("JSESSIONID").permitAll().and().headers()
			.frameOptions().disable().and().authorizeRequests().antMatchers("/api/register").permitAll().antMatchers("/api/activate").permitAll()
			.antMatchers("/api/authenticate").permitAll().antMatchers("/api/account/reset_password/init").permitAll().antMatchers("/api/account/reset_password/finish")
			.permitAll().antMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/api/audits/**").hasAuthority(AuthoritiesConstants.ADMIN)
			.antMatchers("/api/**").authenticated().antMatchers("/websocket/tracker").hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/websocket/**").permitAll()
			.antMatchers("/metrics/**").hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/health/**").hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/trace/**")
			.hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/dump/**").hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/shutdown/**")
			.hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/beans/**").hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/configprops/**")
			.hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/info/**").hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/autoconfig/**")
			.hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/env/**").hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/trace/**")
			.hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/mappings/**").hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/v2/api-docs/**").permitAll()
			.antMatchers("/configuration/security").permitAll().antMatchers("/configuration/ui").permitAll().antMatchers("/swagger-ui/index.html")
			.hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/protected/**").authenticated();

}
 
Example #10
Source File: SsoUiApplication.java    From building-microservices with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	// @formatter:off
	http
		.authorizeRequests()
			.antMatchers("/index.html", "/home.html", "/")
				.permitAll()
				.anyRequest()
					.authenticated()
		.and()
			.csrf()
			.csrfTokenRepository(csrfTokenRepository())
		.and()
			.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
	// @formatter:on
}
 
Example #11
Source File: BasicSecurityConfigurerAdapter.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private HttpSecurity csrf(HttpSecurity security) throws Exception {

        if(environment.getProperty("http.csrf.enabled", Boolean.class, false)) {
            return security.csrf()
                    .csrfTokenRepository(cookieCsrfSignedTokenRepository())
                    .requireCsrfProtectionMatcher(new CsrfRequestMatcher())
                    .and()
                    .addFilterAfter(new CsrfIncludeFilter(), CsrfFilter.class);
        }else {
            return security.csrf().disable();
        }
    }
 
Example #12
Source File: WebSecurityConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
        .csrf()
        .csrfTokenRepository(jwtCsrfTokenRepository)
        .ignoringAntMatchers(ignoreCsrfAntMatchers)
        .and()
        .authorizeRequests()
        .antMatchers("/**")
        .permitAll();
}
 
Example #13
Source File: PolymerDemoOAuthConfig.java    From spring-polymer-demo with Artistic License 2.0 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests().antMatchers("/index.html", "/home.html", "/", "/bower_components/**", "/elements/*")
			.permitAll().anyRequest().authenticated().and().csrf()
			.csrfTokenRepository(csrfTokenRepository()).and()
			.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}
 
Example #14
Source File: ApplicationSecurity.java    From secure-rest-spring-tut with MIT License 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests()
		.antMatchers(HttpMethod.OPTIONS, "/*/**").permitAll()
		.antMatchers("/login", "/rest/open/**").permitAll()
		.antMatchers("/logout", "/rest/**").authenticated();

	// Handlers and entry points
	http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
	http.formLogin().successHandler(authenticationSuccessHandler);
	http.formLogin().failureHandler(authenticationFailureHandler);

	// Logout
	http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);

	// CORS
	http.addFilterBefore(corsFilter, ChannelProcessingFilter.class);

	// CSRF
	http.csrf().requireCsrfProtectionMatcher(
		new AndRequestMatcher(
			// Apply CSRF protection to all paths that do NOT match the ones below

			// We disable CSRF at login/logout, but only for OPTIONS methods
			new NegatedRequestMatcher(new AntPathRequestMatcher("/login*/**", HttpMethod.OPTIONS.toString())),
			new NegatedRequestMatcher(new AntPathRequestMatcher("/logout*/**", HttpMethod.OPTIONS.toString())),

			new NegatedRequestMatcher(new AntPathRequestMatcher("/rest*/**", HttpMethod.GET.toString())),
			new NegatedRequestMatcher(new AntPathRequestMatcher("/rest*/**", HttpMethod.HEAD.toString())),
			new NegatedRequestMatcher(new AntPathRequestMatcher("/rest*/**", HttpMethod.OPTIONS.toString())),
			new NegatedRequestMatcher(new AntPathRequestMatcher("/rest*/**", HttpMethod.TRACE.toString())),
			new NegatedRequestMatcher(new AntPathRequestMatcher("/rest/open*/**"))
		)
	);
	http.addFilterAfter(new CsrfTokenResponseCookieBindingFilter(), CsrfFilter.class); // CSRF tokens handling
}
 
Example #15
Source File: OAuthConfiguration.java    From moserp with Apache License 2.0 5 votes vote down vote up
/**
 * Define the security that applies to the proxy
 */
public void configure(HttpSecurity http) throws Exception {
    http.logout().and()
            .antMatcher("/**").authorizeRequests()
            .antMatchers("/index.html", "/home.html", "/web/**", "/uaa/oauth/**").permitAll()
            .anyRequest().authenticated().and()
            .csrf().csrfTokenRepository(getCSRFTokenRepository()).ignoringAntMatchers("/uaa/oauth/token").and()
            .addFilterAfter(createCSRFHeaderFilter(), CsrfFilter.class);
}
 
Example #16
Source File: BasicSecurityConfigurerAdapter.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private HttpSecurity csrf(HttpSecurity security) throws Exception {

        if(environment.getProperty("http.csrf.enabled", Boolean.class, false)) {
            return security.csrf()
                    .csrfTokenRepository(cookieCsrfSignedTokenRepository())
                    .requireCsrfProtectionMatcher(new CsrfRequestMatcher())
                    .and()
                    .addFilterAfter(new CsrfIncludeFilter(), CsrfFilter.class);
        }else {
            return security.csrf().disable();
        }
    }
 
Example #17
Source File: UnieapSecurityConfig.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
	http.antMatcher("/dashboard/**").authorizeRequests().anyRequest()
			.authenticated().and().csrf()
			.csrfTokenRepository(csrfTokenRepository()).and()
			.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
			.logout().logoutUrl("/dashboard/logout").permitAll()
			.logoutSuccessUrl("/");
}
 
Example #18
Source File: SecurityConfiguration.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private HttpSecurity csrf(HttpSecurity security) throws Exception {

        if(environment.getProperty("http.csrf.enabled", Boolean.class, true)) {
            return security.csrf()
                    .csrfTokenRepository(cookieCsrfSignedTokenRepository())
                    .requireCsrfProtectionMatcher(new CsrfRequestMatcher(environment.getProperty("jwt.cookie-name", "Auth-Graviteeio-AM")))
                    .and()
                    .addFilterAfter(new CsrfIncludeFilter(), CsrfFilter.class);
        }else {
            return security.csrf().disable();
        }
    }
 
Example #19
Source File: BaseWebSecurityConfig.java    From jump-the-queue with Apache License 2.0 5 votes vote down vote up
/**
 * Configure spring security to enable a simple webform-login + a simple rest login.
 */
@Override
public void configure(HttpSecurity http) throws Exception {

  String[] unsecuredResources = new String[] { "/login", "/security/**", "/services/rest/login",
  "/services/rest/logout" };

  /**http
      //
      .userDetailsService(this.userDetailsService)
      // define all urls that are not to be secured
      .authorizeRequests().antMatchers(unsecuredResources).permitAll().anyRequest().authenticated().and()

      // activate crsf check for a selection of urls (but not for login & logout)
      .csrf().requireCsrfProtectionMatcher(new CsrfRequestMatcher()).and()

      // configure parameters for simple form login (and logout)
      .formLogin().successHandler(new SimpleUrlAuthenticationSuccessHandler()).defaultSuccessUrl("/")
      .failureUrl("/login.html?error").loginProcessingUrl("/j_spring_security_login").usernameParameter("username")
      .passwordParameter("password").and()
      // logout via POST is possible
      .logout().logoutSuccessUrl("/login.html").and()

      // register login and logout filter that handles rest logins
      .addFilterAfter(getSimpleRestAuthenticationFilter(), BasicAuthenticationFilter.class)
      .addFilterAfter(getSimpleRestLogoutFilter(), LogoutFilter.class);*/

  http.authorizeRequests().anyRequest().permitAll().and().csrf().disable();

  if (this.corsEnabled) {
    http.addFilterBefore(getCorsFilter(), CsrfFilter.class);
  }
}
 
Example #20
Source File: SpringSecurityConfig.java    From springboot_security_restful_api with Apache License 2.0 5 votes vote down vote up
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/api/admin/**").hasRole("ADMIN")
        .antMatchers("/api/basic/**").hasRole("BASIC")
        .antMatchers("/api/session").permitAll()
        .antMatchers(HttpMethod.GET).permitAll()
        .antMatchers("/api/**").hasRole("BASIC");

    http.formLogin();

    http.logout()
        .logoutUrl("/api/session/logout")
        .addLogoutHandler(customLogoutHandler)
        .logoutSuccessHandler(customLogoutHandler);

    http.exceptionHandling()
        .accessDeniedHandler(customAccessDeniedHandler)
        .authenticationEntryPoint(customAccessDeniedHandler);

    http.csrf()
        .ignoringAntMatchers("/api/session/**");

    http.addFilterBefore(new AcceptHeaderLocaleFilter(), UsernamePasswordAuthenticationFilter.class);

    http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

    http.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class);
}
 
Example #21
Source File: SecurityConfiguration.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .csrf()
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    .and()
        .addFilterBefore(corsFilter, CsrfFilter.class)
        .exceptionHandling()
        .accessDeniedHandler(problemSupport)
    .and()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .authorizeRequests()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/api/auth-info").permitAll()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/info").permitAll()
        .antMatchers("/management/prometheus").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
    .and()
        .oauth2Login()
    .and()
        .oauth2ResourceServer().jwt();
    // @formatter:on
}
 
Example #22
Source File: SecurityAutoConfiguration.java    From albedo with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 搜寻匿名标记 url: @AnonymousAccess
		Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
		// 获取匿名标记
		Map<String, Set<String>> anonymousUrls = getAnonymousUrl(handlerMethodMap);
		http
			.csrf()
			.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
			.and()
			.addFilterBefore(validateCodeFilter(), UsernamePasswordAuthenticationFilter.class)
			.addFilterBefore(passwordDecoderFilter(), CsrfFilter.class)
			.addFilterBefore(corsFilter, CsrfFilter.class)
			.exceptionHandling()
			.authenticationEntryPoint(authenticationEntryPoint())
			.and()
			.rememberMe()
			.rememberMeServices(rememberMeServices)
			.key(applicationProperties.getSecurity().getRememberMe().getKey())
			.and()
			.formLogin()
			.loginProcessingUrl(applicationProperties.getAdminPath(SecurityConstants.AUTHENTICATE_URL))
			.successHandler(ajaxAuthenticationSuccessHandler())
			.failureHandler(ajaxAuthenticationFailureHandler())
			.permitAll()
			.and()
			.logout()
			.logoutUrl(applicationProperties.getAdminPath("/logout"))
			.logoutSuccessHandler(ajaxLogoutSuccessHandler())
			.permitAll()
			.and()
			.headers()
//			.contentSecurityPolicy("default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:")
//			.and()
//			.referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
//			.and()
//			.featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'")
//			.and()
			.frameOptions().disable()
			.and()
			.authorizeRequests()
			// 自定义匿名访问所有url放行:允许匿名和带Token访问,细腻化到每个 Request 类型
			// GET
			.antMatchers(HttpMethod.GET, anonymousUrls.get(RequestMethodEnum.GET.getType()).toArray(new String[0])).permitAll()
			// POST
			.antMatchers(HttpMethod.POST, anonymousUrls.get(RequestMethodEnum.POST.getType()).toArray(new String[0])).permitAll()
			// PUT
			.antMatchers(HttpMethod.PUT, anonymousUrls.get(RequestMethodEnum.PUT.getType()).toArray(new String[0])).permitAll()
			// PATCH
			.antMatchers(HttpMethod.PATCH, anonymousUrls.get(RequestMethodEnum.PATCH.getType()).toArray(new String[0])).permitAll()
			// DELETE
			.antMatchers(HttpMethod.DELETE, anonymousUrls.get(RequestMethodEnum.DELETE.getType()).toArray(new String[0])).permitAll()
			// 所有类型的接口都放行
			.antMatchers(anonymousUrls.get(RequestMethodEnum.ALL.getType()).toArray(new String[0])).permitAll()
			.antMatchers(ArrayUtil.toArray(applicationProperties.getSecurity().getAuthorizePermitAll(), String.class)).permitAll()
			.antMatchers(ArrayUtil.toArray(applicationProperties.getSecurity().getAuthorize(), String.class)).authenticated()
			.and()
			.sessionManagement()
			.maximumSessions(1).sessionRegistry(sessionRegistry())

		;


	}
 
Example #23
Source File: SecurityConfiguration.java    From expper with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .ignoringAntMatchers("/websocket/**")
    .and()
        .addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
        .exceptionHandling()
        .authenticationEntryPoint(authenticationEntryPoint)
    .and()
        .rememberMe()
        .rememberMeServices(rememberMeServices)
        .rememberMeParameter("remember-me")
        .key(env.getProperty("jhipster.security.rememberme.key"))
    .and()
        .formLogin()
        .loginProcessingUrl("/api/authentication")
        .successHandler(ajaxAuthenticationSuccessHandler)
        .failureHandler(ajaxAuthenticationFailureHandler)
        .usernameParameter("j_username")
        .passwordParameter("j_password")
        .permitAll()
    .and()
        .logout()
        .logoutUrl("/api/logout")
        .logoutSuccessHandler(ajaxLogoutSuccessHandler)
        .deleteCookies("JSESSIONID")
        .permitAll()
    .and()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .authorizeRequests()
        .antMatchers("/me/messages").authenticated()
        .antMatchers("/me/tags/**").authenticated()
        .antMatchers("/me/**").permitAll()
        .antMatchers("/api/register").permitAll()
        .antMatchers("/api/activate").permitAll()
        .antMatchers("/api/authenticate").permitAll()
        .antMatchers("/api/account/reset_password/init").permitAll()
        .antMatchers("/api/account/reset_password/finish").permitAll()
        .antMatchers("/api/posts/*/replies/all").permitAll()
        .antMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/audits/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/topics/**").hasAnyAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/admin/**").hasAnyAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/users/**").hasAnyAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/contents/**").hasAnyAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/api/**").authenticated()
        .antMatchers("/metrics/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/health/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/dump/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/shutdown/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/beans/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/configprops/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/info/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/autoconfig/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/env/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/mappings/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/liquibase/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/v2/api-docs/**").permitAll()
        .antMatchers("/configuration/security").permitAll()
        .antMatchers("/configuration/ui").permitAll()
        .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/protected/**").authenticated()
    .and()
        .csrf()
        .ignoringAntMatchers("/api/posts");

}
 
Example #24
Source File: SecurityConfiguration.java    From Spring-5.0-Projects with MIT License 4 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    .and()
        .addFilterBefore(corsFilter, CsrfFilter.class)
        .exceptionHandling()
        .authenticationEntryPoint(problemSupport)
        .accessDeniedHandler(problemSupport)
    .and()
        .rememberMe()
        .rememberMeServices(rememberMeServices)
        .rememberMeParameter("remember-me")
        .key(jHipsterProperties.getSecurity().getRememberMe().getKey())
    .and()
        .formLogin()
        .loginProcessingUrl("/api/authentication")
        .successHandler(ajaxAuthenticationSuccessHandler())
        .failureHandler(ajaxAuthenticationFailureHandler())
        .usernameParameter("j_username")
        .passwordParameter("j_password")
        .permitAll()
    .and()
        .logout()
        .logoutUrl("/api/logout")
        .logoutSuccessHandler(ajaxLogoutSuccessHandler())
        .permitAll()
    .and()
        .headers()
        .frameOptions()
        .disable()
    .and()
        .authorizeRequests()
        .antMatchers("/api/register").permitAll()
        .antMatchers("/api/activate").permitAll()
        .antMatchers("/api/authenticate").permitAll()
        .antMatchers("/api/open/**").permitAll()
        .antMatchers("/api/account/reset-password/init").permitAll()
        .antMatchers("/api/account/reset-password/finish").permitAll()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/info").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);

}
 
Example #25
Source File: SecurityConfiguration.java    From TeamDojo with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
        .addFilterBefore(corsFilter, CsrfFilter.class)
        .exceptionHandling()
        .authenticationEntryPoint(problemSupport)
        .accessDeniedHandler(problemSupport)
        .and()
        .rememberMe()
        .rememberMeServices(rememberMeServices)
        .rememberMeParameter("remember-me")
        .key(jHipsterProperties.getSecurity().getRememberMe().getKey())
        .and()
        .formLogin()
        .loginProcessingUrl("/api/authentication")
        .successHandler(ajaxAuthenticationSuccessHandler())
        .failureHandler(ajaxAuthenticationFailureHandler())
        .usernameParameter("j_username")
        .passwordParameter("j_password")
        .permitAll()
        .and()
        .logout()
        .logoutUrl("/api/logout")
        .logoutSuccessHandler(ajaxLogoutSuccessHandler())
        .permitAll()
        .and()
        .headers()
        .frameOptions()
        .disable()
        .and()
        .authorizeRequests()
        .antMatchers(HttpMethod.GET, "/api/teams/**").permitAll()
        .antMatchers(HttpMethod.PUT, "/api/teams/*/achievable-skills/**").permitAll()
        .antMatchers(HttpMethod.GET, "/api/badges/**").permitAll()
        .antMatchers(HttpMethod.GET, "/api/dimensions/**").permitAll()
        .antMatchers(HttpMethod.GET, "/api/levels/**").permitAll()
        .antMatchers(HttpMethod.GET, "/api/skills/**").permitAll()
        .antMatchers(HttpMethod.POST, "/api/skills/*/vote/**").permitAll()
        .antMatchers(HttpMethod.GET, "/api/team-skills/**").permitAll()
        .antMatchers(HttpMethod.GET, "/api/level-skills/**").permitAll()
        .antMatchers(HttpMethod.GET, "/api/badge-skills/**").permitAll()
        .antMatchers(HttpMethod.POST, "/api/reports").permitAll()
        .antMatchers(HttpMethod.GET, "/api/comments/**").permitAll()
        .antMatchers(HttpMethod.POST, "/api/comments").permitAll()
        .antMatchers(HttpMethod.GET, "/api/organizations").permitAll()
        .antMatchers(HttpMethod.GET, "/api/activities/**").permitAll()
        .antMatchers(HttpMethod.GET, "/api/images/**").permitAll()
        .antMatchers("/api/register").permitAll()
        .antMatchers("/api/activate").permitAll()
        .antMatchers("/api/authenticate").permitAll()
        .antMatchers("/api/account/reset-password/init").permitAll()
        .antMatchers("/api/account/reset-password/finish").permitAll()
        .antMatchers("/api/profile-info").permitAll()
        .antMatchers("/api/**").authenticated()
        .antMatchers("/websocket/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/websocket/**").permitAll()
        .antMatchers("/management/health").permitAll()
        .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/v2/api-docs/**").permitAll()
        .antMatchers("/swagger-resources/configuration/ui").permitAll()
        .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN);
}