Java Code Examples for org.springframework.security.web.util.matcher.AntPathRequestMatcher

The following examples show how to use org.springframework.security.web.util.matcher.AntPathRequestMatcher. These examples are extracted from open source projects. 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 Project: codenjoy   Source File: SecurityConfig.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    securityHeaders(http, xFrameAllowedHosts)
                .authorizeRequests()
                    .antMatchers(UNAUTHORIZED_URIS)
                        .permitAll()
                    .anyRequest()
                        .hasRole("USER")
            .and()
                .oauth2Login()
                    .userInfoEndpoint()
                        .userService(oAuth2MappingUserService)
                .and()
            .and()
                .httpBasic()
            .and()
                .logout()
                    .logoutUrl(LOGOUT_PROCESSING_URI)
                    .logoutRequestMatcher(new AntPathRequestMatcher(LOGOUT_PROCESSING_URI))
                    .logoutSuccessHandler(logoutSuccessHandler)
                    .invalidateHttpSession(true);
    // @formatter:on
}
 
Example 2
Source Project: jcart   Source File: WebSecurityConfig.java    License: MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    	.csrf().disable()
        .authorizeRequests()
        	.antMatchers("/resources/**", "/webjars/**","/assets/**").permitAll()
            .antMatchers("/", "/register", "/forgotPwd","/resetPwd").permitAll()
            .antMatchers("/myAccount","/checkout","/orders").authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/home")
            .failureUrl("/login?error")
            .permitAll()
            .and()
        .logout()
        	.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        	.permitAll()
            .and()
        .exceptionHandling().accessDeniedPage("/403");
}
 
Example 3
Source Project: JavaSecurity   Source File: WebSecurityConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .authorizeRequests()
            .antMatchers("/*", "/h2-console/**").permitAll()
            .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
            .antMatchers("/admin/**").hasRole("ADMIN")
        .and()
        .csrf()
            .ignoringAntMatchers("/h2-console/*")
        .and()
        .headers()
            .frameOptions().sameOrigin()
        .and()
        .formLogin()
        .and()
        .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/");
    // @formatter:on
}
 
Example 4
Source Project: FEBS-Cloud   Source File: ValidateCodeFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(@Nonnull HttpServletRequest httpServletRequest, @Nonnull HttpServletResponse httpServletResponse,
                                @Nonnull FilterChain filterChain) throws ServletException, IOException {
    String header = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);

    RequestMatcher matcher = new AntPathRequestMatcher(EndpointConstant.OAUTH_TOKEN, HttpMethod.POST.toString());
    if (matcher.matches(httpServletRequest)
            && StringUtils.equalsIgnoreCase(httpServletRequest.getParameter(ParamsConstant.GRANT_TYPE), GrantTypeConstant.PASSWORD)) {
        try {
            validateCode(httpServletRequest);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } catch (Exception e) {
            FebsResponse febsResponse = new FebsResponse();
            FebsUtil.makeFailureResponse(httpServletResponse, febsResponse.message(e.getMessage()));
            log.error(e.getMessage(), e);
        }
    } else {
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
 
Example 5
/**
* Define the security filter chain in order to support SSO Auth by using SAML 2.0
* 
* @return Filter chain proxy
* @throws Exception
*/
  @Bean
  public FilterChainProxy samlFilter() throws Exception {
      List<SecurityFilterChain> chains = new ArrayList<SecurityFilterChain>();
      chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"),
              samlEntryPoint()));
      chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"),
              samlLogoutFilter()));
      chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/metadata/**"),
              metadataDisplayFilter()));
      chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
              samlWebSSOProcessingFilter()));
      chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSOHoK/**"),
              samlWebSSOHoKProcessingFilter()));
      chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"),
              samlLogoutProcessingFilter()));
      chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
              samlIDPDiscovery()));
      return new FilterChainProxy(chains);
  }
 
Example 6
public OpenIdCallbackLoginFilter(OpenIdAuthenticationManager openIdAuthenticationManager,
                                 AntPathRequestMatcher requestMatcher,
                                 AuthenticationManager authenticationManager,
                                 UserRepository userRepository,
                                 AuthorityRepository authorityRepository,
                                 PasswordEncoder passwordEncoder,
                                 UserManager userManager,
                                 UserOrganizationRepository userOrganizationRepository,
                                 OrganizationRepository organizationRepository) {
    super(requestMatcher);
    this.setAuthenticationManager(authenticationManager);
    this.userRepository = userRepository;
    this.authorityRepository = authorityRepository;
    this.passwordEncoder = passwordEncoder;
    this.userManager = userManager;
    this.userOrganizationRepository = userOrganizationRepository;
    this.organizationRepository = organizationRepository;
    this.requestMatcher = requestMatcher;
    this.openIdAuthenticationManager = openIdAuthenticationManager;
}
 
Example 7
Source Project: spring-boot-plus   Source File: SecuritySecureConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
    successHandler.setTargetUrlParameter("redirectTo");
    successHandler.setDefaultTargetUrl(this.adminServer.path("/"));

    http.authorizeRequests(
            (authorizeRequests) -> authorizeRequests
                    .antMatchers(this.adminServer.path("/assets/**")).permitAll()
                    .antMatchers(this.adminServer.path("/static/**")).permitAll()
                    .antMatchers(this.adminServer.path("/login")).permitAll()
                    .anyRequest().authenticated()
    ).formLogin(
            (formLogin) -> formLogin.loginPage(this.adminServer.path("/login")).successHandler(successHandler).and()
    ).logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout"))).httpBasic(Customizer.withDefaults())
            .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                    .ignoringRequestMatchers(
                            new AntPathRequestMatcher(this.adminServer.path("/instances"),
                                    HttpMethod.POST.toString()),
                            new AntPathRequestMatcher(this.adminServer.path("/instances/*"),
                                    HttpMethod.DELETE.toString()),
                            new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))
                    ))
            .rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
}
 
Example 8
Source Project: spring-boot-demo   Source File: RbacAuthorityService.java    License: MIT License 6 votes vote down vote up
/**
 * 校验请求是否存在
 *
 * @param request 请求
 */
private void checkRequest(HttpServletRequest request) {
    // 获取当前 request 的方法
    String currentMethod = request.getMethod();
    Multimap<String, String> urlMapping = allUrlMapping();

    for (String uri : urlMapping.keySet()) {
        // 通过 AntPathRequestMatcher 匹配 url
        // 可以通过 2 种方式创建 AntPathRequestMatcher
        // 1:new AntPathRequestMatcher(uri,method) 这种方式可以直接判断方法是否匹配,因为这里我们把 方法不匹配 自定义抛出,所以,我们使用第2种方式创建
        // 2:new AntPathRequestMatcher(uri) 这种方式不校验请求方法,只校验请求路径
        AntPathRequestMatcher antPathMatcher = new AntPathRequestMatcher(uri);
        if (antPathMatcher.matches(request)) {
            if (!urlMapping.get(uri)
                    .contains(currentMethod)) {
                throw new SecurityException(Status.HTTP_BAD_METHOD);
            } else {
                return;
            }
        }
    }

    throw new SecurityException(Status.REQUEST_NOT_FOUND);
}
 
Example 9
@Override
protected void configure(HttpSecurity http) throws Exception {
	SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
	successHandler.setTargetUrlParameter("redirectTo");
	successHandler.setDefaultTargetUrl(this.adminContextPath + "/");

	http.authorizeRequests((authorizeRequests) -> authorizeRequests
			.antMatchers(this.adminContextPath + "/assets/**").permitAll()
			.antMatchers(this.adminContextPath + "/login").permitAll().anyRequest().authenticated())
			.formLogin((formLogin) -> formLogin.loginPage(this.adminContextPath + "/login")
					.successHandler(successHandler))
			.logout((logout) -> logout.logoutUrl(this.adminContextPath + "/logout"))
			.httpBasic(Customizer.withDefaults())
			.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
					.ignoringRequestMatchers(
							new AntPathRequestMatcher(this.adminContextPath + "/instances",
									HttpMethod.POST.toString()),
							new AntPathRequestMatcher(this.adminContextPath + "/instances/*",
									HttpMethod.DELETE.toString()),
							new AntPathRequestMatcher(this.adminContextPath + "/actuator/**")));
}
 
Example 10
Source Project: tutorials   Source File: MultipleEntryPointsSecurityConfig.java    License: MIT License 6 votes vote down vote up
protected void configure(HttpSecurity http) throws Exception {
    
    //@formatter:off
    http.antMatcher("/user/**")
        .authorizeRequests().anyRequest().hasRole("USER")              
        .and().formLogin().loginProcessingUrl("/user/login")
        .failureUrl("/userLogin?error=loginError").defaultSuccessUrl("/user/myUserPage")
        .and().logout().logoutUrl("/user/logout").logoutSuccessUrl("/multipleHttpLinks")
        .deleteCookies("JSESSIONID")
        .and().exceptionHandling()
        .defaultAuthenticationEntryPointFor(loginUrlauthenticationEntryPointWithWarning(),  new AntPathRequestMatcher("/user/private/**"))
        .defaultAuthenticationEntryPointFor(loginUrlauthenticationEntryPoint(), new AntPathRequestMatcher("/user/general/**"))
        .accessDeniedPage("/403")
        .and().csrf().disable();
    //@formatter:on
}
 
Example 11
Source Project: spring-security-saml-dsl   Source File: SAMLConfigurer.java    License: MIT License 6 votes vote down vote up
private FilterChainProxy samlFilter(SAMLEntryPoint samlEntryPoint, SAMLLogoutFilter samlLogoutFilter,
									SAMLLogoutProcessingFilter samlLogoutProcessingFilter, SAMLContextProvider contextProvider) {
	List<SecurityFilterChain> chains = new ArrayList<>();
	chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"),
		samlEntryPoint));
	chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"),
		samlLogoutFilter));
	chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/metadata/**"),
		metadataDisplayFilter(contextProvider)));
	try {
		chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
			samlWebSSOProcessingFilter(samlAuthenticationProvider, contextProvider, samlProcessor)));
	} catch (Exception e) {
		e.printStackTrace();
	}
	chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"),
			samlLogoutProcessingFilter));
	SAMLDiscovery samlDiscovery = new SAMLDiscovery();
	samlDiscovery.setMetadata(cachingMetadataManager);
	samlDiscovery.setContextProvider(contextProvider);
	chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
		samlDiscovery));
	return new FilterChainProxy(chains);
}
 
Example 12
@Override
protected void configure(HttpSecurity http) throws Exception {
	SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
	successHandler.setTargetUrlParameter("redirectTo");
	successHandler.setDefaultTargetUrl(this.adminContextPath + "/");

	http.authorizeRequests((authorizeRequests) -> authorizeRequests
			.antMatchers(this.adminContextPath + "/assets/**").permitAll()
			.antMatchers(this.adminContextPath + "/login").permitAll().anyRequest().authenticated())
			.formLogin((formLogin) -> formLogin.loginPage(this.adminContextPath + "/login")
					.successHandler(successHandler))
			.logout((logout) -> logout.logoutUrl(this.adminContextPath + "/logout"))
			.httpBasic(Customizer.withDefaults())
			.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
					.ignoringRequestMatchers(
							new AntPathRequestMatcher(this.adminContextPath + "/instances",
									HttpMethod.POST.toString()),
							new AntPathRequestMatcher(this.adminContextPath + "/instances/*",
									HttpMethod.DELETE.toString()),
							new AntPathRequestMatcher(this.adminContextPath + "/actuator/**")));
}
 
Example 13
Source Project: JavaSecurity   Source File: WebSecurityConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .authorizeRequests()
            .antMatchers("/*", "/h2-console/**").permitAll()
            .antMatchers("/contacts/**").hasRole("USER")
         .and()
            .csrf()
            .ignoringAntMatchers("/h2-console/*")
        .and()
        .headers()
            .frameOptions().sameOrigin()
        .and()
        .formLogin()
            .defaultSuccessUrl("/contacts")
        .and()
        .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
    // @formatter:on
}
 
Example 14
Source Project: lemon   Source File: UrlResourcePopulator.java    License: Apache License 2.0 6 votes vote down vote up
public void execute(FilterSecurityInterceptor filterSecurityInterceptor,
        Map<String, String> resourceMap) {
    Assert.notNull(filterSecurityInterceptor);
    Assert.notNull(resourceMap);

    logger.info("refresh url resource");

    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = null;
    requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();

    for (Map.Entry<String, String> entry : resourceMap.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        requestMap.put(new AntPathRequestMatcher(key),
                SecurityConfig.createListFromCommaDelimitedString(value));
    }

    FilterInvocationSecurityMetadataSource source = new DefaultFilterInvocationSecurityMetadataSource(
            requestMap);
    filterSecurityInterceptor.setSecurityMetadataSource(source);
}
 
Example 15
Source Project: cxf-fediz   Source File: FederationLogoutFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean requiresLogout(HttpServletRequest request, HttpServletResponse response) {
    String wa = request.getParameter(FederationConstants.PARAM_ACTION);
    if (FederationConstants.ACTION_SIGNOUT.equals(wa) || FederationConstants.ACTION_SIGNOUT_CLEANUP.equals(wa)) {
        // Default WS-Federation logout action
        return true;
    }

    if (this.logoutUrl == null) {
        String contextName = request.getContextPath();
        if (contextName == null || contextName.isEmpty()) {
            contextName = "/";
        }
        this.logoutUrl = federationConfig.getFedizContext(contextName).getLogoutURL();
    }
    if (this.logoutUrl != null && !this.logoutUrl.isEmpty()) {
        super.setLogoutRequestMatcher(new AntPathRequestMatcher(logoutUrl));
        return super.requiresLogout(request, response);
    }
    return false;
}
 
Example 16
Source Project: tutorials   Source File: SecurityConfiguration.java    License: MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .permitAll()
        .successForwardUrl("/index")
        .and()
        .logout()
        .permitAll()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/login");
}
 
Example 17
Source Project: find   Source File: IdolSecurity.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("ProhibitedExceptionDeclared")
@Override
protected void configure(final HttpSecurity http) throws Exception {
    final LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>();
    entryPoints.put(new AntPathRequestMatcher("/api/**"), new Http403ForbiddenEntryPoint());
    entryPoints.put(AnyRequestMatcher.INSTANCE, new LoginUrlAuthenticationEntryPoint(FindController.DEFAULT_LOGIN_PAGE));
    final AuthenticationEntryPoint authenticationEntryPoint = new DelegatingAuthenticationEntryPoint(entryPoints);

    http
        .csrf()
            .disable()
        .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint)
            .accessDeniedPage("/authentication-error")
            .and()
        .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl(FindController.DEFAULT_LOGIN_PAGE)
            .and()
        .authorizeRequests()
            .antMatchers(FindController.APP_PATH + "/**").hasAnyRole(FindRole.USER.name())
            .antMatchers(FindController.CONFIG_PATH).hasRole(FindRole.CONFIG.name())
            .antMatchers("/api/public/**").hasRole(FindRole.USER.name())
            .antMatchers("/api/bi/**").hasRole(FindRole.BI.name())
            .antMatchers("/api/config/**").hasRole(FindRole.CONFIG.name())
            .antMatchers("/api/admin/**").hasRole(FindRole.ADMIN.name())
            .antMatchers(FindController.DEFAULT_LOGIN_PAGE).permitAll()
            .antMatchers(FindController.LOGIN_PATH).permitAll()
            .antMatchers("/").permitAll()
            .anyRequest().denyAll()
            .and()
        .headers()
            .defaultsDisabled()
            .frameOptions()
            .sameOrigin();

    idolSecurityCustomizer.customize(http, authenticationManager());
}
 
Example 18
Source Project: cerberus   Source File: AuditLoggingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
  List<RequestMatcher> blackListMatchers =
      LOGGING_NOT_TRIGGERED_BLACKLIST.stream()
          .map(AntPathRequestMatcher::new)
          .collect(Collectors.toList());
  var blackListMatcher = new OrRequestMatcher(blackListMatchers);
  return blackListMatcher.matches(request);
}
 
Example 19
Source Project: SpringSecurity-JWT-Vue-Deom   Source File: JwtLoginFilter.java    License: MIT License 5 votes vote down vote up
/**
 * @param defaultFilterProcessesUrl 配置要过滤的地址,即登陆地址
 * @param authenticationManager 认证管理器,校验身份时会用到
 * @param loginCountService */
public JwtLoginFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager,
                      VerifyCodeService verifyCodeService, LoginCountService loginCountService) {
    super(new AntPathRequestMatcher(defaultFilterProcessesUrl));
    this.loginCountService = loginCountService;
    // 为 AbstractAuthenticationProcessingFilter 中的属性赋值
    setAuthenticationManager(authenticationManager);
    this.verifyCodeService = verifyCodeService;
}
 
Example 20
Source Project: spring-boot-demo   Source File: SecurityConfig.java    License: MIT License 5 votes vote down vote up
/**
     * 密码生成器(默认为bcrypt模式)
     *
     * @return
     */
//    @Bean
//    PasswordEncoder passwordEncoder() {
//        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
//    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity.
                requestMatchers()
                // 必须登录过的用户才可以进行 oauth2 的授权码申请
                .antMatchers("/", "/home", "/login", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .and()
                .httpBasic()
                .disable()
                .exceptionHandling()
                .accessDeniedPage("/login?authorization_error=true")
                .and()
                // TODO: put CSRF protection back into this controller
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable();
    }
 
Example 21
Source Project: blackduck-alert   Source File: AuthenticationHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public FilterChainProxy samlFilter() throws Exception {
    List<SecurityFilterChain> chains = new ArrayList<>();

    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"), samlEntryPoint()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"), samlWebSSOProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"), samlLogoutFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"), samlLogoutProcessingFilter()));
    return new AlertFilterChainProxy(chains, samlContext());
}
 
Example 22
Source Project: webanno   Source File: WebAnnoSecurity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity aHttp) throws Exception
{
    aHttp
        .rememberMe()
        .and()
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/login.html*").permitAll()
            // Resources need to be publicly accessible so they don't trigger the login
            // page. Otherwise it could happen that the user is redirected to a resource
            // upon login instead of being forwarded to a proper application page.
            .antMatchers("/favicon.ico").permitAll()
            .antMatchers("/favicon.png").permitAll()
            .antMatchers("/assets/**").permitAll()
            .antMatchers("/images/**").permitAll()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/wicket/resource/**").permitAll()
            .antMatchers("/swagger-ui.html").access("hasAnyRole('ROLE_REMOTE')")
            .antMatchers("/admin/**").access("hasAnyRole('ROLE_ADMIN')")
            .antMatchers("/doc/**").access("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
            .antMatchers("/**").access("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
            .anyRequest().denyAll()
        .and()
        .exceptionHandling()
            .defaultAuthenticationEntryPointFor(
                    new LoginUrlAuthenticationEntryPoint("/login.html"), 
                    new AntPathRequestMatcher("/**"))
        .and()
            .headers().frameOptions().sameOrigin();
}
 
Example 23
@Override
protected void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests((authorizeRequests) -> authorizeRequests.anyRequest().permitAll())
			.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
					.ignoringRequestMatchers(
							new AntPathRequestMatcher(this.adminServer.path("/instances"),
									HttpMethod.POST.toString()),
							new AntPathRequestMatcher(this.adminServer.path("/instances/*"),
									HttpMethod.DELETE.toString()),
							new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))));
}
 
Example 24
Source Project: POC   Source File: WebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests().antMatchers(HttpMethod.GET, "/").permitAll()
			.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll().antMatchers("/login")
			.permitAll().antMatchers("/signup").permitAll().antMatchers("/dashboard/**").hasAuthority("ADMIN")
			.anyRequest().authenticated().and().csrf().disable().formLogin()
			.successHandler(this.customizeAuthenticationSuccessHandler).loginPage("/login")
			.failureUrl("/login?error=true").usernameParameter("email").passwordParameter("password").and().logout()
			.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/").and()
			.exceptionHandling();
}
 
Example 25
Source Project: cola   Source File: WebSecurityConfiguration.java    License: MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
	http
			.antMatcher("/**")
			.authorizeRequests()
			.antMatchers("/login**", "/webjars/**", "/error**")
			.permitAll()
			.anyRequest()
			.authenticated().and()
			.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("https://www.honvay.com/logout").permitAll();
}
 
Example 26
Source Project: codenjoy   Source File: SecurityConfig.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    securityHeaders(http,xFrameAllowedHosts)
                .antMatcher(AdminController.URI + "*")
                    .authorizeRequests()
                        .anyRequest()
                            .hasRole("ADMIN")
            .and()
                .formLogin()
                    .loginPage(LoginController.ADMIN_URI)
                        .usernameParameter(USERNAME_FORM_PARAMETER)
                        .passwordParameter(PASSWORD_FORM_PARAMETER)
                    .permitAll()
                    .defaultSuccessUrl(AdminController.URI)
                        .permitAll()
            .and()
                .logout()
                    .logoutUrl(LOGOUT_PROCESSING_URI)
                    .logoutRequestMatcher(new AntPathRequestMatcher(LOGOUT_PROCESSING_URI))
                    .logoutSuccessHandler(logoutSuccessHandler)
                    .invalidateHttpSession(true)
            .and()
                .exceptionHandling()
                    .accessDeniedHandler((request, response, accessDeniedException) ->
                            response.sendRedirect(request.getContextPath()
                                    + "/error?message=Page access is restricted"));
    // @formatter:on
}
 
Example 27
Source Project: OAuth-2.0-Cookbook   Source File: SecurityConfiguration.java    License: MIT License 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {

    http
        .authorizeRequests()
        .antMatchers("/oauth/**")
        .authenticated()
    .and()
        .csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable()
        .formLogin().permitAll().and()
        .logout().permitAll().and()
        ;


}
 
Example 28
Source Project: codenjoy   Source File: SecurityConfig.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    securityHeaders(http, xFrameAllowedHosts)
                .authorizeRequests()
                    .antMatchers(UNAUTHORIZED_URIS)
                        .permitAll()
                    .regexMatchers(UNAUTHORIZED_URIS_PATTERNS)
                        .permitAll()
                    .anyRequest()
                        .hasRole("USER") 
            .and()
                .formLogin()
                    .loginPage(LoginController.URI)
                        .loginProcessingUrl(LOGIN_PROCESSING_URI)
                            .permitAll()
                        .usernameParameter(USERNAME_FORM_PARAMETER)
                        .passwordParameter(PASSWORD_FORM_PARAMETER)
                        .successHandler(authenticationSuccessHandler)
                        .failureUrl(LoginController.URI + "?failed=true")
                    .permitAll()
            .and()
                .httpBasic()
            .and()
                .logout()
                    .logoutUrl(LOGOUT_PROCESSING_URI)
                    .logoutRequestMatcher(new AntPathRequestMatcher(LOGOUT_PROCESSING_URI))
                    .logoutSuccessHandler(logoutSuccessHandler)
                    .invalidateHttpSession(true);
    // @formatter:on
}
 
Example 29
Source Project: cola   Source File: WebSecurityConfiguration.java    License: MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {


	captchaAuthenticationFilter.addRequestMatcher(new AntPathRequestMatcher("/login", HttpMethod.POST.name()), this.failureHandler());

	http.setSharedObject(CaptchaAuthenticationFilter.class, captchaAuthenticationFilter);

	http.authorizeRequests()
			.antMatchers("/login", "/logout", "/error").permitAll()
			.antMatchers("/captcha", "/session-invalid").permitAll()
			.and()
			.formLogin()
			.loginProcessingUrl("/login")
			.loginPage("/login")
			.failureHandler(this.failureHandler())
			.successHandler(this.successHandler())
			//.failureHandler(new WebAuthenticationFailureHandler())
			.and()
			.logout()
			.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
			.logoutSuccessUrl("/login?logout")
			.invalidateHttpSession(false)
			.and()
			.addFilterBefore(captchaAuthenticationFilter, AbstractPreAuthenticatedProcessingFilter.class)
			.sessionManagement()
			.invalidSessionUrl("/session-invalid")
			.maximumSessions(1)
			.expiredUrl("/session-invalid")
			.sessionRegistry(sessionRegistry)
			.and()
			.sessionFixation()
			.migrateSession()
			.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
			.sessionAuthenticationStrategy(sessionAuthenticationStrategy);
}
 
Example 30
@Bean
public LogoutFilter requestCasGlobalLogoutFilter() {
	LogoutFilter logoutFilter = new LogoutFilter(env.getRequiredProperty(CAS_URL_LOGOUT) + "?service="
			+ env.getRequiredProperty(APP_SERVICE_HOME), new SecurityContextLogoutHandler());
	// logoutFilter.setFilterProcessesUrl("/logout");
	// logoutFilter.setFilterProcessesUrl("/j_spring_cas_security_logout");
	logoutFilter.setLogoutRequestMatcher(new AntPathRequestMatcher("/logout", "POST"));
	return logoutFilter;
}