Java Code Examples for org.springframework.security.config.annotation.web.builders.HttpSecurity#apply()

The following examples show how to use org.springframework.security.config.annotation.web.builders.HttpSecurity#apply() . 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: WebSecurityConfig.java    From spring-boot-jwt with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {

  // Disable CSRF (cross site request forgery)
  http.csrf().disable();

  // No session will be created or used by spring security
  http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

  // Entry points
  http.authorizeRequests()//
      .antMatchers("/users/signin").permitAll()//
      .antMatchers("/users/signup").permitAll()//
      .antMatchers("/h2-console/**/**").permitAll()
      // Disallow everything else..
      .anyRequest().authenticated();

  // If a user try to access a resource without having enough permissions
  http.exceptionHandling().accessDeniedPage("/login");

  // Apply JWT
  http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));

  // Optional, if you want to test the API from a browser
  // http.httpBasic();
}
 
Example 2
Source File: FwResourceServerConfiguration.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
	ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.formLogin()
			// 可以通过授权登录进行访问
			.loginPage("/auth/login")
			.loginProcessingUrl("/auth/signin")
			.and()
			.authorizeRequests();

	for (String url : fwUrlsConfiguration.getCollects()) {
		registry.antMatchers(url)
				.permitAll();
	}

	registry.anyRequest()
			.authenticated()
			.and()
			.csrf()
			.disable();
	http.apply(ajaxSecurityConfigurer);
}
 
Example 3
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 4
Source File: Application.java    From boot-examples with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    String[] restEndpointsToSecure = { "news"};
    for (String endpoint : restEndpointsToSecure) {
        http.authorizeRequests().antMatchers("/" + endpoint + "/**").hasRole(CustomUserDetailsService.ROLE_USER);
    }

    SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> securityConfigurerAdapter = new XAuthTokenConfigurer(userDetailsServiceBean());
    http.apply(securityConfigurerAdapter);
}
 
Example 5
Source File: SecurityConfiguration.java    From spring-security-saml-dsl with MIT License 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    SecurityConfigurer securityConfigurerAdapter =
        saml()
            .identityProvider()
                .metadataFilePath(metadataPath)
                .and()
            .serviceProvider()
            .keyStore()
                .storeFilePath("saml/keystore.jks")
                .password("secret")
                .keyname("spring")
                .keyPassword("secret")
                .and()
            .protocol("https")
            .hostname("localhost:8443")
            .basePath("/")
            .entityId("com:example")
            .and();

    http.apply(securityConfigurerAdapter);

    http
        .requiresChannel()
        .anyRequest().requiresSecure();

    http
        .authorizeRequests()
        .antMatchers("/saml/**").permitAll()
        .antMatchers("/health").permitAll()
        .antMatchers("/error").permitAll()
        .anyRequest().authenticated();
}
 
Example 6
Source File: SsoSecurityConfigurer.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
public void configure(HttpSecurity http) throws Exception {
	OAuth2SsoProperties sso = this.applicationContext.getBean(OAuth2SsoProperties.class);
	// Delay the processing of the filter until we know the
	// SessionAuthenticationStrategy is available:
	http.apply(new OAuth2ClientAuthenticationConfigurer(oauth2SsoFilter(sso)));
	addAuthenticationEntryPoint(http, sso);
}
 
Example 7
Source File: SecurityConfig.java    From oauth-boot with MIT License 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {

    BootBaseLoginProperties base = properties.getBaseLogin();
    BootSmsLoginProperties sms = properties.getSmsLogin();
    http
            // http security 要拦截的url,这里这拦截,oauth2相关和登录登录相关的url,其他的交给资源服务处理
            .requestMatchers()
            .antMatchers( "/oauth/**",properties.getLoginPage(),
                    base.getLoginProcessUrl(),sms.getLoginProcessUrl())
            .and()
            .authorizeRequests()
            // 自定义页面或处理url是,如果不配置全局允许,浏览器会提示服务器将页面转发多次
            .antMatchers(properties.getLoginPage(),base.getLoginProcessUrl(),sms.getLoginProcessUrl())
            .permitAll()
            .anyRequest()
            .authenticated();

    // 表单登录
    http.formLogin()
            .failureHandler(handler)
            // 请求 {用户名} 参数名称
            .usernameParameter(base.getUsernameParameterName())
            // 请求 {密码} 参数名
            .passwordParameter(base.getPasswordParameterName())
            // 登录页面
            .loginPage(properties.getLoginPage())
            // 登录处理url
            .loginProcessingUrl(base.getLoginProcessUrl());

    http.httpBasic().disable();

    http.apply(this.smsSecurityConfig);

    // 用户密码验证之前校验验证码
    http.addFilterBefore(pictureCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

}
 
Example 8
Source File: PigSecurityConfigurerAdapter.java    From pig with MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry =
            http.formLogin().loginPage("/authentication/require")
                    .loginProcessingUrl("/authentication/form")
                    .and()
                    .authorizeRequests();
    filterIgnorePropertiesConfig.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
    registry.anyRequest().authenticated()
            .and()
            .csrf().disable();
    http.apply(mobileSecurityConfigurer);
}
 
Example 9
Source File: WebAuthnAuthenticationProviderConfigurerSpringTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {

    // Authentication
    http.apply(WebAuthnLoginConfigurer.webAuthnLogin());

    // Authorization
    http.authorizeRequests()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated();
}
 
Example 10
Source File: WebAuthnLoginConfigurerSetterSpringTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {

    // Authentication
    http.apply(WebAuthnConfigurer.webAuthn());

    http.apply(WebAuthnLoginConfigurer.webAuthnLogin());

    // Authorization
    http.authorizeRequests()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated();
}
 
Example 11
Source File: OauthWebServerSecurityConfig.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
@Override
	public void configure(HttpSecurity http) throws Exception {

		http.httpBasic().and()
				//.addFilterAt(captchaAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
				.formLogin()
				.successHandler(customAuthenticationSuccessHandler)
				.failureHandler(customAuthenticationFailureHandler)
				//.failureHandler(customAuthenticationFailureHandler)
				.and()
				.authorizeRequests()
				.antMatchers(HttpMethod.OPTIONS).permitAll()
				.antMatchers("/v2/api-docs",
						"/configuration/ui",
						"/swagger-resources",
						"/configuration/security",
						"/webjars/**",
						"/swagger-resources/configuration/ui",
						"/swagger-ui.html",
						"/swagger-resources/configuration/security").permitAll()
//			.anyRequest().authenticated()
				.and()
				.csrf().disable();

		http.addFilterAfter(smsCodeAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
			.addFilterAt(captchaAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
			;	//添加过滤器,处理系统自定义异常
//			.addFilterAfter(new RewriteAccessDenyFilter(), ExceptionTranslationFilter.class);
		http.apply(validateCodeSecurityConfig);

		// 自定义配置
		/*http.apply(validateCodeSecurityConfig) // 全局配置,过滤器链第一个过滤器
				.and()
				.apply(smsCodeAuthenticationSecurityConfig);*/
	}
 
Example 12
Source File: AbstractChannelSecurityConfigurer.java    From cola with MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
	if (adapter != null) {
		http.apply(adapter);
	}
	config(http);
}
 
Example 13
Source File: CustomResourceServerConfig.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    String[] ignores = new String[filterIgnorePropertiesConfig.getUrls().size()];
    http
            .csrf().disable()
            .httpBasic().disable()
            .authorizeRequests()
            .antMatchers(filterIgnorePropertiesConfig.getUrls().toArray(ignores)).permitAll()
            .anyRequest().authenticated()
            .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    // 手机号登录
    http.apply(mobileSecurityConfigurer);
    // 微信登录
    http.apply(wxSecurityConfigurer);
}
 
Example 14
Source File: OauthWebServerSecurityConfig.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
@Override
	public void configure(HttpSecurity http) throws Exception {

		http.httpBasic().and()
				//.addFilterAt(captchaAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
				.formLogin()
				.successHandler(customAuthenticationSuccessHandler)
				.failureHandler(customAuthenticationFailureHandler)
				//.failureHandler(customAuthenticationFailureHandler)
				.and()
				.authorizeRequests()
				.antMatchers(HttpMethod.OPTIONS).permitAll()
				.antMatchers("/v2/api-docs",
						"/configuration/ui",
						"/swagger-resources",
						"/configuration/security",
						"/webjars/**",
						"/swagger-resources/configuration/ui",
						"/swagger-ui.html",
						"/swagger-resources/configuration/security").permitAll()
//			.anyRequest().authenticated()
				.and()
				.csrf().disable();

		http.addFilterAfter(smsCodeAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
			.addFilterAt(captchaAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
			;	//添加过滤器,处理系统自定义异常
//			.addFilterAfter(new RewriteAccessDenyFilter(), ExceptionTranslationFilter.class);
		http.apply(validateCodeSecurityConfig);

		// 自定义配置
		/*http.apply(validateCodeSecurityConfig) // 全局配置,过滤器链第一个过滤器
				.and()
				.apply(smsCodeAuthenticationSecurityConfig);*/
	}
 
Example 15
Source File: SecurityConfiguration.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Override
	    protected void configure(HttpSecurity http) throws Exception {
	        http
	            .exceptionHandling()
	                .authenticationEntryPoint(authenticationEntryPoint)
	                .and()
	            .sessionManagement()
					.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // stateless
	                .and()
	            .rememberMe()
	                .rememberMeServices(rememberMeServices())
	                .key(env.getProperty("appconf.security.rememberme.key"))
	                .and()
	            .logout()
	                .logoutUrl("/app/logout")
	                .logoutSuccessHandler(ajaxLogoutSuccessHandler)
	                .deleteCookies("JSESSIONID")
	                .permitAll()
	                .and()
	            .csrf()
	                .disable() // Disabled, cause enabling it will cause sessions
	            .headers()
	                .frameOptions()
	                	.sameOrigin()
	                	.addHeaderWriter(new XXssProtectionHeaderWriter())
	                .and()
	            .authorizeRequests()
	                .antMatchers("/*").permitAll()
	                .antMatchers("/app/rest/authenticate").permitAll()
	                .antMatchers("/app/rest/integration/login").permitAll()
	                .antMatchers("/app/rest/temporary/example-options").permitAll()
	                .antMatchers("/app/rest/idm/email-actions/*").permitAll()
	                .antMatchers("/app/rest/idm/signups").permitAll()
	                .antMatchers("/app/rest/idm/passwords").permitAll()

//					.antMatchers("/druid/**").authenticated()
//	        		.antMatchers("/actuator/**").authenticated()
//					.antMatchers("/manage/**").authenticated()
	                .antMatchers("/app/**").authenticated();

	        // Custom login form configurer to allow for non-standard HTTP-methods (eg. LOCK)
	        CustomFormLoginConfig<HttpSecurity> loginConfig = new CustomFormLoginConfig<HttpSecurity>();
	        loginConfig.loginProcessingUrl("/app/authentication")
	            .successHandler(ajaxAuthenticationSuccessHandler)
	            .failureHandler(ajaxAuthenticationFailureHandler)
	            .usernameParameter("j_username")
	            .passwordParameter("j_password")
	            .permitAll();

	        http.apply(loginConfig);
	    }
 
Example 16
Source File: SecurityConfiguration.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .rememberMe()
            .rememberMeServices(rememberMeServices)
            .key(idmAppProperties.getSecurity().getRememberMeKey())
            .and()
            .logout()
            .logoutUrl("/app/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler)
            .addLogoutHandler(new ClearFlowableCookieLogoutHandler())
            .permitAll()
            .and()
            .csrf()
            .disable() // Disabled, cause enabling it will cause sessions
            .headers()
            .frameOptions()
            .sameOrigin()
            .addHeaderWriter(new XXssProtectionHeaderWriter())
            .and()
            .authorizeRequests()
            .antMatchers("/*").permitAll()
            .antMatchers("/app/rest/authenticate").permitAll()
            .antMatchers("/app/**").hasAuthority(DefaultPrivileges.ACCESS_IDM);

    // Custom login form configurer to allow for non-standard HTTP-methods (eg. LOCK)
    CustomFormLoginConfig<HttpSecurity> loginConfig = new CustomFormLoginConfig<>();
    loginConfig.loginProcessingUrl("/app/authentication")
            .successHandler(ajaxAuthenticationSuccessHandler)
            .failureHandler(ajaxAuthenticationFailureHandler)
            .usernameParameter("j_username")
            .passwordParameter("j_password")
            .permitAll();

    http.apply(loginConfig);
}
 
Example 17
Source File: SecurityConfiguration.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    HttpSecurity httpSecurity = http.authenticationProvider(authenticationProvider())
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .csrf().disable();

    if (restAppProperties.getCors().isEnabled()) {
        httpSecurity.apply(new PropertyBasedCorsFilter(restAppProperties));
    }

    // Swagger docs
    if (isSwaggerDocsEnabled()) {
        httpSecurity
            .authorizeRequests()
            .antMatchers("/docs/**").permitAll();

    } else {
        httpSecurity
            .authorizeRequests()
            .antMatchers("/docs/**").denyAll();
        
    }

    httpSecurity
        .authorizeRequests()
        .requestMatchers(EndpointRequest.to(InfoEndpoint.class, HealthEndpoint.class)).authenticated()
        .requestMatchers(EndpointRequest.toAnyEndpoint()).hasAnyAuthority(SecurityConstants.ACCESS_ADMIN);

    // Rest API access
    if (isVerifyRestApiPrivilege()) {
        httpSecurity
            .authorizeRequests()
            .anyRequest()
            .hasAuthority(SecurityConstants.PRIVILEGE_ACCESS_REST_API).and ().httpBasic();
        
    } else {
        httpSecurity
        .authorizeRequests()
        .anyRequest()
        .authenticated().and().httpBasic();
    }
}
 
Example 18
Source File: SecurityConfiguration.java    From tutorials with MIT License 4 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http.apply(stormpath());
}