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

The following examples show how to use org.springframework.security.web.util.matcher.AntPathRequestMatcher. 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: SecuritySecureConfig.java    From spring-boot-plus with Apache License 2.0 7 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 #2
Source File: WebSecurityConfig.java    From spring-boot-security-saml-sample with Apache License 2.0 6 votes vote down vote up
/**
* 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 #3
Source File: WebSecurityConfig.java    From jcart with 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 #4
Source File: SecurityConfiguration.java    From tutorials with 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 #5
Source File: FederationLogoutFilter.java    From cxf-fediz with 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 #6
Source File: WebSecurityConfig.java    From JavaSecurity with 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 #7
Source File: SecurityConfig.java    From codenjoy with 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 #8
Source File: UrlResourcePopulator.java    From lemon with 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 #9
Source File: ValidateCodeFilter.java    From FEBS-Cloud with 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 #10
Source File: WebSecurityConfig.java    From JavaSecurity with 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 #11
Source File: SpringBootAdminConsulApplication.java    From spring-boot-admin with 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.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 #12
Source File: SAMLConfigurer.java    From spring-security-saml-dsl with 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 #13
Source File: OpenIdCallbackLoginFilter.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
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 #14
Source File: MultipleEntryPointsSecurityConfig.java    From tutorials with 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 #15
Source File: RbacAuthorityService.java    From spring-boot-demo with 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 #16
Source File: SpringBootAdminEurekaApplication.java    From spring-boot-admin with 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.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 #17
Source File: OpenIdConnectFilter.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
public OpenIdConnectFilter(
    @Value("${openid.callback-uri}") String callbackUri,
    @Value("${openid.api-base-uri}") String apiBaseUri) {
    super(new OrRequestMatcher(
        new AntPathRequestMatcher(callbackUri),
        new AntPathRequestMatcher(apiBaseUri)));
    this.localMatcher = new AntPathRequestMatcher(apiBaseUri);
    setAuthenticationManager(new NoopAuthenticationManager());
}
 
Example #18
Source File: SpringBootAdminHazelcastApplication.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests((authorizeRequests) -> authorizeRequests.anyRequest().permitAll())
			.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
					.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 #19
Source File: MatcherUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static MutipleRequestMatcher matchAntPaths(String...paths){
	List<RequestMatcher> matchers = Stream.of(paths).map(path->{
		if(path.contains("|")){
			String[] strs = GuavaUtils.split(path, "|");
			return new AntPathRequestMatcher(strs[1], strs[0]);
		}else{
			return new AntPathRequestMatcher(path);
		}
	})
	.collect(Collectors.toList());
	MutipleRequestMatcher m = new MutipleRequestMatcher(matchers);
	return m;
}
 
Example #20
Source File: OAuth2ServerConfiguration.java    From angularjs-springboot-bookstore with MIT License 5 votes vote down vote up
@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .exceptionHandling()
        .authenticationEntryPoint(authenticationEntryPoint)
    .and()
        .logout()
        .logoutUrl("/api/logout")
        .logoutSuccessHandler(ajaxLogoutSuccessHandler)
    .and()
        .csrf()
        .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
        .disable()
        .headers()
        .frameOptions().disable()
    .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
        .authorizeRequests()
        .antMatchers("/api/authenticate").permitAll()
        .antMatchers("/api/register").permitAll()
        .antMatchers("/api/logs/**").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("/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .antMatchers("/protected/**").authenticated();

}
 
Example #21
Source File: InceptionSecurity.java    From inception with 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 #22
Source File: IdolSecurity.java    From find with 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 #23
Source File: WebSecurityConfiguration.java    From cola with 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 #24
Source File: SecurityConfig.java    From codenjoy with 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 #25
Source File: SecurityConfiguration.java    From OAuth-2.0-Cookbook with 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 #26
Source File: SecurityConfig.java    From codenjoy with 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 File: SecurityPermitAllConfig.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests((authorizeRequest) -> authorizeRequest.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 #28
Source File: BaseWebSecurityConfig.java    From jump-the-queue with Apache License 2.0 5 votes vote down vote up
/**
 * Create a simple authentication filter for REST logins that reads user-credentials from a json-parameter and returns
 * status 200 instead of redirect after login.
 *
 * @return the {@link JsonUsernamePasswordAuthenticationFilter}.
 * @throws Exception if something goes wrong.
 */
protected JsonUsernamePasswordAuthenticationFilter getSimpleRestAuthenticationFilter() throws Exception {

  JsonUsernamePasswordAuthenticationFilter jsonFilter = new JsonUsernamePasswordAuthenticationFilter(
      new AntPathRequestMatcher("/services/rest/login"));
  jsonFilter.setPasswordParameter("j_password");
  jsonFilter.setUsernameParameter("j_username");
  jsonFilter.setAuthenticationManager(authenticationManager());
  // set failurehandler that uses no redirect in case of login failure; just HTTP-status: 401
  jsonFilter.setAuthenticationManager(authenticationManagerBean());
  jsonFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler());
  // set successhandler that uses no redirect in case of login success; just HTTP-status: 200
  jsonFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandlerSendingOkHttpStatusCode());
  return jsonFilter;
}
 
Example #29
Source File: WebSecurityConfiguration.java    From cola with 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 #30
Source File: GrozaSecurityConfiguration.java    From Groza with Apache License 2.0 5 votes vote down vote up
@Bean
protected JwtTokenAuthenticationProcessingFilter buildWsJwtTokenAuthenticationProcessingFilter() throws Exception {
    AntPathRequestMatcher matcher = new AntPathRequestMatcher(WS_TOKEN_BASED_AUTH_ENTRY_POINT);
    JwtTokenAuthenticationProcessingFilter filter
            = new JwtTokenAuthenticationProcessingFilter(failureHandler, jwtQueryTokenExtractor, matcher);
    filter.setAuthenticationManager(this.authenticationManager);
    return filter;
}