org.springframework.security.config.annotation.web.builders.httpsecurity Java Examples

The following examples show how to use org.springframework.security.config.annotation.web.builders.httpsecurity. 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 testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 7 votes vote down vote up
@Override
protected void configure(HttpSecurity http) {
    try {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/", "/index.jsf", "/signup.jsf", "/assets/**").permitAll()
                .antMatchers("/javax.faces.resource/**").permitAll()
                .antMatchers("/ui/**").authenticated()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.jsf")
                .permitAll()
                .failureUrl("/login.jsf?error=true")
                .defaultSuccessUrl("/index.jsf")
                .and()
                .logout()
                .logoutSuccessUrl("/index.jsf");
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #2
Source File: MultiHttpSecurityConfig.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
   // http.antMatcher("/home/**").
    //为了在product页面获取到用户信息,进行了url修改.2019.4.12
    http.antMatcher("/**").
            //指定登录认证的Controller
                    formLogin().usernameParameter("uname").passwordParameter("pwd").loginPage("/home/login").successHandler(
            MemberAuthenticationSuccessHandler).failureHandler(MemberAuthenticationFailHandler)
            .and()
            .authorizeRequests()
            //登录相关
            .antMatchers("/home/login", "/home/register/mobile", "/home/register/email").permitAll()
            .antMatchers("/home/**").hasRole("USER")
            //限制购物车必须登录
            .antMatchers("/cart/","/cart").hasRole("USER");


    //rabc相关

    http.logout().logoutUrl("/home/logout").permitAll();
    http.rememberMe().rememberMeParameter("rememberme");//记住我功能
    http.headers().frameOptions().sameOrigin();//解决X-Frame-Options deny 造成的页面空白,不然后台不能用frame
}
 
Example #3
Source File: SecurityConfiguration.java    From spring-security-saml-dsl with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http
		.authorizeRequests()
			.antMatchers("/saml/**").permitAll()
			.anyRequest().authenticated()
			.and()
		.apply(saml())
			.serviceProvider()
				.keyStore()
					.storeFilePath("saml/keystore.jks")
					.password("secret")
					.keyname("spring")
					.keyPassword("secret")
					.and()
				.protocol("https")
				.hostname("localhost:8443")
				.basePath("/")
				.and()
			.identityProvider()
				.metadataFilePath(metadataUrl)
				.and();
}
 
Example #4
Source File: SecurityConfig.java    From spring-oauth2-jwt-jdbc with MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().ignoringAntMatchers("/login");

    http.authorizeRequests()
            .antMatchers("/login")
            .permitAll()
            .antMatchers("/oauth/token")
            .authenticated()
            .antMatchers("/oauth/authorize")
            .hasAuthority("ROLE_USER")
            .and()
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
            .exceptionHandling()
            .authenticationEntryPoint(jwtAuthEndPoint);
}
 
Example #5
Source File: WebSecurityConfig.java    From cf-SpringBootTrader with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/", "/registration","/hystrix.stream").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .loginProcessingUrl("/login")
            .permitAll()
            .and()
        .logout()
        .logoutSuccessHandler(logoutSuccessHandler)
            .permitAll();
}
 
Example #6
Source File: SecurityConfig.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http
		.authorizeRequests(authorizeRequests ->
			authorizeRequests
				.anyRequest().authenticated())
		.oauth2Login(oauth2Login ->
			oauth2Login
				.loginPage("/oauth2/authorization/login-client")
				.failureUrl("/login?error")
				.permitAll())
		.logout(logout ->
			logout
				.logoutSuccessUrl("http://localhost:8090/uaa/logout.do?client_id=login-client&redirect=http://localhost:8080"))
		.oauth2Client();
}
 
Example #7
Source File: SecurityConfig.java    From spring-security-oauth2-demo with GNU General Public License v3.0 6 votes vote down vote up
@Override
    protected void configure(HttpSecurity http) throws Exception {

//        静态登录页面的配置
        http.formLogin()
                // 登录页面名称,他会去寻找 resources 下的 resources 和 static 目录
                // 静态页面
                //.loginPage("/login.html")
                // 模板引擎
                .loginPage("/oauth/login")
                // 登录表单提交的路径
                // 静态页面
                // .loginProcessingUrl("/authorization/form")
                // 模板引擎
                .loginProcessingUrl(securityProperties.getLoginProcessingUrl());
                // 关闭 csrf 防护,因为对于我们的所有请求来说,都是需要携带身份信息的
                // .and()
                // .csrf().disable();

//        http.httpBasic();
    }
 
Example #8
Source File: ResourceConfig.java    From Using-Spring-Oauth2-to-secure-REST with MIT License 6 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http

            .requestMatcher(new OAuthRequestedMatcher())
            .csrf().disable()
            .anonymous().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS).permitAll()
            // when restricting access to 'Roles' you must remove the "ROLE_" part role
            // for "ROLE_USER" use only "USER"
            .antMatchers("/api/hello").access("hasAnyRole('USER')")
            .antMatchers("/api/me").hasAnyRole("USER", "ADMIN")
            .antMatchers("/api/admin").hasRole("ADMIN")
            // use the full name when specifying authority access
            .antMatchers("/api/registerUser").hasAuthority("ROLE_REGISTER")
            // restricting all access to /api/** to authenticated users
            .antMatchers("/api/**").authenticated();
}
 
Example #9
Source File: WebSecurityConfig.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable() // We don't need CSRF for JWT based authentication
    .exceptionHandling()
    .authenticationEntryPoint(this.authenticationEntryPoint)
    
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

    .and()
        .authorizeRequests()
            .antMatchers(ADMIN_LOGIN_ENTRY_POINT).permitAll()
            .antMatchers(FORM_BASED_LOGIN_ENTRY_POINT).permitAll() // Login end-point
            .antMatchers(TOKEN_REFRESH_ENTRY_POINT).permitAll() // Token refresh end-point
    .and()
        .authorizeRequests()
            .antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() // Protected API End-points
    .and()
        .addFilterBefore(buildAjaxLoginProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
        .addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
}
 
Example #10
Source File: WebSecurityConfigration.java    From Taroco with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry =
            http
                    // 默认的用户名密码认证器
                    .authenticationProvider(daoAuthenticationProvider())
                    .apply(mobileTokenAuthenticationSecurityConfigration)
                    .and()
                    .apply(smsCodeAuthenticationSecurityConfigration)
                    .and()
                    .addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                    .formLogin().loginPage("/").permitAll()
                    .loginProcessingUrl("/login").permitAll()
                    .and().logout().logoutUrl("/logout").permitAll().logoutSuccessHandler(logoutSuccessHandler)
                    // 异常处理filter: ExceptionTranslationFilter
                    .and().exceptionHandling()
                    // 匿名用户访问无权限资源时的异常
                    //.authenticationEntryPoint(exceptionEntryPoint)
                    // 认证过的用户访问无权限资源时的异常
                    .accessDeniedHandler(accessDeniedHandler)
                    // 开启RememberMe
                    .and().rememberMe().key(RM_KEY).rememberMeServices(rememberMeServices())
                    .and().authorizeRequests();

    final List<String> urlPermitAll = oauth2Properties.getUrlPermitAll();
    urlPermitAll.forEach(url -> registry.antMatchers(url).permitAll());
    registry.anyRequest().authenticated().and().cors().and().csrf().disable();
}
 
Example #11
Source File: SecurityConfigurer.java    From spring-oauth2-keycloak-connector with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(final HttpSecurity http) throws Exception {

  http.cors()
      .configurationSource(corsConfigurationSource())
      .and()
      .headers()
      .frameOptions()
      .disable()
      .and()
      .csrf()
      .disable()
      .authorizeRequests()
      .antMatchers(securityProperties.getApiMatcher())
      .authenticated();

}
 
Example #12
Source File: ResSvrApplication.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Bean
public ResourceServerConfigurer resourceServerConfigurer() {
	return new ResourceServerConfigurer() {
		@Override
		public void configure(HttpSecurity http) throws Exception {
			http.authorizeRequests()
			    .antMatchers(HttpMethod.GET, "/hello").access("#oauth2.hasAnyScope('account', 'message', 'email')");
		}

		@Override
		public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
			resources.resourceId("resource");
		}
		
	};
}
 
Example #13
Source File: SecurityConfig.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
/**
 * This is the equivalent to:
 * <pre>
 *     <http pattern="/resources/**" security="none"/>
 *     <http pattern="/css/**" security="none"/>
 *     <http pattern="/webjars/**" security="none"/>
 * </pre>
 *
 * @param web
 * @throws Exception
 */
@Override
public void configure(final WebSecurity web) throws Exception {

    // Ignore static resources and webjars from Spring Security
    web.ignoring()
            .antMatchers("/resources/**")
            .antMatchers("/css/**")
            .antMatchers("/webjars/**")
    ;

    // Thymeleaf needs to use the Thymeleaf configured FilterSecurityInterceptor
    // and not the default Filter from AutoConfiguration.
    final HttpSecurity http = getHttp();
    web.postBuildAction(() -> {
        web.securityInterceptor(http.getSharedObject(FilterSecurityInterceptor.class));
    });
}
 
Example #14
Source File: SecurityConfig.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
/**
 * This is the equivalent to:
 * <pre>
 *     <http pattern="/resources/**" security="none"/>
 *     <http pattern="/css/**" security="none"/>
 *     <http pattern="/webjars/**" security="none"/>
 * </pre>
 *
 * @param web
 * @throws Exception
 */
@Override
public void configure(final WebSecurity web) throws Exception {

    // Ignore static resources and webjars from Spring Security
    web.ignoring()
            .antMatchers("/resources/**")
            .antMatchers("/css/**")
            .antMatchers("/webjars/**")
    ;

    // Thymeleaf needs to use the Thymeleaf configured FilterSecurityInterceptor
    // and not the default Filter from AutoConfiguration.
    final HttpSecurity http = getHttp();
    web.postBuildAction(() -> {
        web.securityInterceptor(http.getSharedObject(FilterSecurityInterceptor.class));
    });
}
 
Example #15
Source File: SecurityConfiguration.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
protected void configure(HttpSecurity http) throws Exception {
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .addFilter(requestHeaderAuthenticationFilter())
        .addFilter(new AnonymousAuthenticationFilter("anonymous"))
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS).permitAll()
        .antMatchers(COMMON_NON_SECURED_PATHS).permitAll()
        .antMatchers(HttpMethod.GET, "/api/v1/credentials/callback").permitAll()
        .antMatchers("/api/v1/**").hasRole("AUTHENTICATED")
        .anyRequest().permitAll();

    http.csrf()
        .ignoringAntMatchers(COMMON_NON_SECURED_PATHS)
        .ignoringAntMatchers("/api/v1/credentials/callback")
        .ignoringAntMatchers("/api/v1/atlas/**")
        .csrfTokenRepository(new SyndesisCsrfRepository());
}
 
Example #16
Source File: APISecurityConfig.java    From ReCiter with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    APIKeyAuthFilter filter = new APIKeyAuthFilter(principalRequestHeader);
    filter.setAuthenticationManager(new AuthenticationManager() {
	
        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            String principal = (String) authentication.getPrincipal();
            if (!principalRequestValue.equals(principal))
            {
                throw new BadCredentialsException("The API key was not found or not the expected value.");
            }
            authentication.setAuthenticated(true);
            return authentication;
        }
    });
    if(securityEnabled) {
     httpSecurity.
         antMatcher("/reciter/**").
         csrf().disable().
         sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
         and().addFilter(filter).authorizeRequests().anyRequest().authenticated();
    }
}
 
Example #17
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 #18
Source File: SecurityConfig.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
/**
 * This is the equivalent to:
 * <pre>
 *     <http pattern="/resources/**" security="none"/>
 *     <http pattern="/css/**" security="none"/>
 *     <http pattern="/webjars/**" security="none"/>
 * </pre>
 *
 * @param web
 * @throws Exception
 */
@Override
public void configure(final WebSecurity web) throws Exception {

    // Ignore static resources and webjars from Spring Security
    web.ignoring()
            .antMatchers("/resources/**")
            .antMatchers("/css/**")
            .antMatchers("/webjars/**")
    ;

    // Thymeleaf needs to use the Thymeleaf configured FilterSecurityInterceptor
    // and not the default Filter from AutoConfiguration.
    final HttpSecurity http = getHttp();
    web.postBuildAction(() -> {
        web.securityInterceptor(http.getSharedObject(FilterSecurityInterceptor.class));
    });
}
 
Example #19
Source File: OpenIdAuthenticationSecurityConfig.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) {
    //openId provider
    OpenIdAuthenticationProvider provider = new OpenIdAuthenticationProvider();
    provider.setUserDetailsService(userDetailsService);
    http.authenticationProvider(provider);
}
 
Example #20
Source File: SecurityConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http
		.authorizeRequests()
			.mvcMatchers("/public", "/login").permitAll()
			.anyRequest().authenticated()
			.and()
		.formLogin()
			.loginPage("/login")
			.and()
		.sessionManagement()
			.sessionFixation().none()
			.enableSessionUrlRewriting(true);
}
 
Example #21
Source File: WebSecurityConfig.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
/**
 * @Description: 高版本的丢弃了
 * security:
 *   basic:
 *     enabled: true 配置,应该使用以下方式开启
 * @Param: [http]
 * @Return: void
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    // Configure HttpSecurity as needed (e.g. enable http basic).
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    //注意:为了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 这种方式登录,所以必须是httpBasic,
    // 如果是form方式,不能使用url格式登录
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/actuator/**").permitAll()
            .anyRequest()
            .authenticated().and().httpBasic();
}
 
Example #22
Source File: OAuth2ResourceServer.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    //@formatter:off
    http
        .authorizeRequests()
            .anyRequest().authenticated().and()
        .requestMatchers()
            .antMatchers("/api/**");
  //@formatter:on
}
 
Example #23
Source File: SecurityConfig.java    From botanic-ng with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {

	http
	//.addFilterBefore(sessionRepositoryFilter, ChannelProcessingFilter.class)
	.csrf().disable();
	//http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
	http.authorizeRequests().antMatchers(HttpMethod.POST, "/api/info/**").hasRole(DefaultUserDetailsService.ROLE_USER);
	http.authorizeRequests().antMatchers(HttpMethod.POST, "/api/plants/**").hasRole(DefaultUserDetailsService.ROLE_ADMIN);
	http.authorizeRequests().antMatchers(HttpMethod.DELETE, "/api/plants/**").hasRole(DefaultUserDetailsService.ROLE_ADMIN);
}
 
Example #24
Source File: WebSecurityConfiguration.java    From spring-boot-2-oauth2-authorization-jwt with MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
	http.csrf().disable().exceptionHandling()
			.authenticationEntryPoint(
					(request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
			.and().authorizeRequests().antMatchers("/**").authenticated().and().httpBasic();
}
 
Example #25
Source File: WebApiWebSecurityConfig.java    From syhthems-platform with MIT License 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
            .configurationSource(webApiCorsConfigurationSource())
        .and()
            .authorizeRequests()
                .antMatchers("/error", "/web/api/oauth/token").permitAll()
                .anyRequest().authenticated()
        .and()
            .oauth2ResourceServer().jwt().jwtAuthenticationConverter(webApiCustomJwtAuthenticationConverter())
        .and().and()
            .csrf().disable();
}
 
Example #26
Source File: SecurityConfiguration.java    From kubernetes-crash-course with MIT License 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
  http
      .authorizeRequests().anyRequest().permitAll()
      .and()
      .httpBasic().disable()
      .csrf().disable();
}
 
Example #27
Source File: ResourceServerConfig.java    From microservice-integration with MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .requestMatchers().antMatchers("/**")
            .and()
            .authorizeRequests()
            .antMatchers(permitAllUrlProperties.getPermitallPatterns()).permitAll()
            .anyRequest().authenticated();
}
 
Example #28
Source File: WebSecurityConfig.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
/**
 * @Description: 高版本的丢弃了
 * security:
 *   basic:
 *     enabled: true 配置,应该使用以下方式开启
 * @Param: [http]
 * @Return: void
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    // Configure HttpSecurity as needed (e.g. enable http basic).
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    //注意:为了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 这种方式登录,所以必须是httpBasic,
    // 如果是form方式,不能使用url格式登录
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/actuator/**").permitAll()
            .anyRequest()
            .authenticated().and().httpBasic();
}
 
Example #29
Source File: SecurityConfiguration.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin().
            and().authorizeRequests()
            .antMatchers("/index.html").permitAll()
            .and()
            .authorizeRequests().
            anyRequest().
            authenticated();

}
 
Example #30
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);
}