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

The following examples show how to use org.springframework.security.config.annotation.web.builders.HttpSecurity#authorizeRequests() . 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: SpringWebConfig.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
    if (securityProperties.isEnabled()) {
        registry = configureWhiteListAuthentication(registry, true);
        if (AuthenticationType.lOCAL.getCode().equalsIgnoreCase(securityProperties.getAuthenticationProvider())) {
            configureLocalAuthentication(registry);
        } else if (AuthenticationType.CAS.getCode().equalsIgnoreCase(securityProperties.getAuthenticationProvider())) {
            configureCasAuthentication(registry);
        } else if (AuthenticationType.PLATFORM_AUTH.getCode().equalsIgnoreCase(securityProperties.getAuthenticationProvider())) {
            configurePlatformAuthentication(registry);
        } else {
            throw new CmdbException("Unsupported authentication-provider: " + securityProperties.getAuthenticationProvider());
        }
    } else {
        registry = configureWhiteListAuthentication(registry, false);
        configurePrivacyFreeAuthentication(registry);
    }
}
 
Example 2
Source File: SophiaResourceServerConfig.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
@Override
@SneakyThrows
public void configure(HttpSecurity httpSecurity) {
    //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
    httpSecurity.headers().frameOptions().disable();
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>
            .ExpressionInterceptUrlRegistry registry = httpSecurity
            .authorizeRequests();

    registry.antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
    //对配置的url放行 不进行验证
    ignorePropertiesConfig.getUrls()
            .forEach(url -> registry.antMatchers(url).permitAll());
    registry.anyRequest().authenticated()
            .and().csrf().disable();
}
 
Example 3
Source File: SophiaResourceServerConfig.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
@Override
@SneakyThrows
public void configure(HttpSecurity httpSecurity) {
    //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
    httpSecurity.headers().frameOptions().disable();
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>
            .ExpressionInterceptUrlRegistry registry = httpSecurity
            .authorizeRequests();

    registry.antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
    //对配置的url放行 不进行验证
    ignorePropertiesConfig.getUrls()
            .forEach(url -> registry.antMatchers(url).permitAll());
    registry.anyRequest().authenticated()
            .and().csrf().disable();
}
 
Example 4
Source File: WebSecurityConfig.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * 主配置
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
	//开启https
	if (serverProperties.getSsl().isEnabled()) {
		http.requiresChannel().anyRequest().requiresSecure();
	}
	// 开启跨域共享,  跨域伪造请求限制=无效
	http.cors().and().csrf().disable();
	// 禁止缓存
	http.headers().cacheControl();
	// 无权限时处理
	http.exceptionHandling().authenticationEntryPoint(authentication);
	http.exceptionHandling().accessDeniedHandler(accessDenied);
	// 不创建session
	http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
	// 配置token验证过滤器
	http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
	//地址配置
	var registry = http.authorizeRequests();
	// 不控制的地址
	registry.antMatchers(permitAllPathList()).permitAll();
	registry.antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
	// 在密码验证过滤器前执行jwt过滤器
	registry.anyRequest().authenticated();
}
 
Example 5
Source File: SecurityConfig.java    From lolibox with Apache License 2.0 6 votes vote down vote up
@Override
    protected void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        registry.antMatchers("/admin/**").hasAuthority(Role.ADMIN.toString())
                .antMatchers("/image/**").permitAll()
//                .antMatchers("/webjars/**").permitAll()
//                .antMatchers("/js/**").permitAll()
//                .antMatchers("/css/**").permitAll()
//                .antMatchers("/img/**").permitAll()

                .and().formLogin().loginPage("/signin").defaultSuccessUrl("/").permitAll()
                .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
                .and().csrf().ignoringAntMatchers("/admin/**"/*,"/oauth*//**"*/);

        http.headers().frameOptions().disable().and()
                .rememberMe().tokenRepository(reMemberMeRepository);

    }
 
Example 6
Source File: BaseResourceServerConfigurerAdapter.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 默认的配置,对外暴露
 *
 * @param http
 * @throws Exception
 */
@Override
public void configure(HttpSecurity http) throws Exception{
	//允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
	http.headers().frameOptions().disable();
	ExpressionUrlAuthorizationConfigurer<HttpSecurity>
		.ExpressionInterceptUrlRegistry registry = http
		.authorizeRequests();
	filterIgnorePropertiesConfig.getUrls()
		.forEach(url -> registry.antMatchers(url).permitAll());
	registry.anyRequest().authenticated()
		.and().csrf().disable();
}
 
Example 7
Source File: SecurityConfig.java    From mall-swarm with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity
            .authorizeRequests();
    //不需要保护的资源路径允许访问
    for (String url : ignoreUrlsConfig().getUrls()) {
        registry.antMatchers(url).permitAll();
    }
    //允许跨域请求的OPTIONS请求
    registry.antMatchers(HttpMethod.OPTIONS)
            .permitAll();
    // 任何请求需要身份认证
    registry.and()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
            // 关闭跨站请求防护及不使用session
            .and()
            .csrf()
            .disable()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            // 自定义权限拒绝处理类
            .and()
            .exceptionHandling()
            .accessDeniedHandler(restfulAccessDeniedHandler())
            .authenticationEntryPoint(restAuthenticationEntryPoint())
            // 自定义权限拦截器JWT过滤器
            .and()
            .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    //有动态权限配置时添加动态权限校验过滤器
    if(dynamicSecurityService!=null){
        registry.and().addFilterBefore(dynamicSecurityFilter(), FilterSecurityInterceptor.class);
    }
}
 
Example 8
Source File: SophiaResourceServerConfig.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@Override
@SneakyThrows
public void configure(HttpSecurity httpSecurity) {
    //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
    httpSecurity.headers().frameOptions().disable();
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>
            .ExpressionInterceptUrlRegistry registry = httpSecurity
            .authorizeRequests();
    //对配置的url放行 不进行验证
    ignorePropertiesConfig.getUrls()
            .forEach(url -> registry.antMatchers(url).permitAll());
    registry.anyRequest().authenticated()
            .and().csrf().disable();
}
 
Example 9
Source File: BlackResourceServerConfigurerAdapter.java    From black-shop with Apache License 2.0 5 votes vote down vote up
/**
 * 默认资源服务器的配置
 * @param httpSecurity
 */
@Override
@SneakyThrows
public void configure(HttpSecurity httpSecurity) {
	httpSecurity.headers().frameOptions().disable();
	ExpressionUrlAuthorizationConfigurer<HttpSecurity>
			.ExpressionInterceptUrlRegistry registry = httpSecurity
			.authorizeRequests();
	//registry.antMatchers("/user/test").permitAll();
	permitAllUrlProperties.getIgnoreUrls()
			.forEach(url -> registry.antMatchers(url).permitAll());
	registry.anyRequest().authenticated()
			.and().csrf().disable();
}
 
Example 10
Source File: SecurityConfig.java    From mall with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity
            .authorizeRequests();
    //不需要保护的资源路径允许访问
    for (String url : ignoreUrlsConfig().getUrls()) {
        registry.antMatchers(url).permitAll();
    }
    //允许跨域请求的OPTIONS请求
    registry.antMatchers(HttpMethod.OPTIONS)
            .permitAll();
    // 任何请求需要身份认证
    registry.and()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
            // 关闭跨站请求防护及不使用session
            .and()
            .csrf()
            .disable()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            // 自定义权限拒绝处理类
            .and()
            .exceptionHandling()
            .accessDeniedHandler(restfulAccessDeniedHandler())
            .authenticationEntryPoint(restAuthenticationEntryPoint())
            // 自定义权限拦截器JWT过滤器
            .and()
            .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    //有动态权限配置时添加动态权限校验过滤器
    if(dynamicSecurityService!=null){
        registry.and().addFilterBefore(dynamicSecurityFilter(), FilterSecurityInterceptor.class);
    }
}
 
Example 11
Source File: ResourceServerConfiguration.java    From Taroco with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
    http.headers().frameOptions().disable();
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
            .authorizeRequests();
    oauth2Properties.getUrlPermitAll().forEach(url -> registry.antMatchers(url).permitAll());
    // 角色和权限的验证交给拦截器去做, 这里只判断是否登录
    registry.anyRequest()
            .access("@permissionService.hasPermission(request, authentication)");
}
 
Example 12
Source File: ResourceServerConfiguration.java    From pig with MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
    http.headers().frameOptions().disable();
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
            .authorizeRequests();
    filterIgnorePropertiesConfig.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
    registry.anyRequest()
            .access("@permissionService.hasPermission(request,authentication)");
}
 
Example 13
Source File: ResourceServerConfiguration.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
	// 首先进行验证码过滤逻辑
	http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class);
	// 允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
	http.headers().frameOptions().disable();
	ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
			.authorizeRequests();
	// 排除无需认证的请求
	for (String url : urlsConfiguration.getCollects()) {
		registry.antMatchers(url).permitAll();
	}
	// 通过切面进行验证 { @link PermissionService.hasPermission }
	registry.anyRequest().access("@permissionService.hasPermission(request,authentication)");
}
 
Example 14
Source File: SecurityConfigurer.java    From ywh-frame with GNU General Public License v3.0 4 votes vote down vote up
/**
     * 配置如何通过拦截器保护我们的请求,哪些能通过哪些不能通过,允许对特定的http请求基于安全考虑进行配置
     * @param httpSecurity http
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity
                // 暂时禁用csrc否则无法提交
                .csrf().disable()
                // session管理
                .sessionManagement()
                // 我们使用SessionCreationPolicy.STATELESS无状态的Session机制(即Spring不使用HTTPSession),对于所有的请求都做权限校验,
                // 这样Spring Security的拦截器会判断所有请求的Header上有没有”X-Auth-Token”。
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 设置最多一个用户登录,如果第二个用户登陆则第一用户被踢出,并跳转到登陆页面
                .maximumSessions(1).expiredUrl("/login.html");
        httpSecurity
                // 开始认证
                .authorizeRequests()
                // 对静态文件和登陆页面放行
                .antMatchers("/static/**").permitAll()
                .antMatchers("/auth/**").permitAll()
                .antMatchers("/login.html").permitAll()
                // 其他请求需要认证登陆
                .anyRequest().authenticated();

        // 注入我们刚才写好的 jwt过滤器,添加在UsernamePasswordAuthenticationFilter过滤器之前
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 这块是配置跨域请求的
         ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
        // 让Spring security放行所有preflight request
        registry.requestMatchers(CorsUtils::isPreFlightRequest).permitAll();

        /**
         * 以下注释内容有需要可以解开,再整合vue后以下注释解开也没什么用
         */


        // 开启缓存控制头,不缓存任何内容是安全的,但是也是视情况而定,配置disable是关闭缓存控制头
//        httpSecurity
//                .headers()
//                .cacheControl()
//                .disable();
//        httpSecurity
//                // 表单登陆
//                .formLogin()
//                // 设置跳转的登陆页面
//                .loginPage("/login.html")
//                //.failureUrl("/auth/login?error") 设置如果登陆失败跳转到哪个页面
////                .successHandler((request, response, authentication) -> {
////                    System.out.println("登陆成功");
////                })
//                // security默认使用的就是login路径认证,如果想使用自定义自行修改就可以了
//                .loginProcessingUrl("/login")
//                // 如果直接访问登录页面,则登录成功后重定向到这个页面,否则跳转到之前想要访问的页面
//                .defaultSuccessUrl("/index.html");
//        httpSecurity
//                // 登出
//                .logout()
//                // 登出处理,使用security默认的logout,也可以自定义路径,实现即可
//                .logoutUrl("/logout")
//                // 登出成功后跳转到哪个页面
//                .logoutSuccessUrl("/login.html")
//                .logoutSuccessHandler((request, response, authentication) -> {
//                    //登出成功处理函数
//                    System.out.println("logout success");
//                    response.sendRedirect("/core/login.html");
//                })
//                .addLogoutHandler((request, response, authentication) ->{
//                    //登出处理函数
//                    System.out.println("logout------");
//                })
//                // 清理Session
//                .invalidateHttpSession(true);
    }