Example usage for org.springframework.security.config.annotation.web.builders HttpSecurity formLogin

List of usage examples for org.springframework.security.config.annotation.web.builders HttpSecurity formLogin

Introduction

In this page you can find the example usage for org.springframework.security.config.annotation.web.builders HttpSecurity formLogin.

Prototype

public FormLoginConfigurer<HttpSecurity> formLogin() throws Exception 

Source Link

Document

Specifies to support form based authentication.

Usage

From source file:org.smigo.user.authentication.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    /*//from  w ww .j ava  2s  .  co m
            HttpSessionSecurityContextRepository repository = new HttpSessionSecurityContextRepository();
            repository.setDisableUrlRewriting(false);
            http.securityContext().securityContextRepository(repository);
    */
    http.authorizeRequests().anyRequest().permitAll();

    FormLoginConfigurer<HttpSecurity> formLogin = http.formLogin();
    formLogin.loginPage("/login");
    formLogin.loginProcessingUrl("/login");
    formLogin.failureHandler(restAuthenticationFailureHandler);
    formLogin.successHandler(emptyAuthenticationSuccessHandler);

    final SpringSocialConfigurer springSocialConfigurer = new SpringSocialConfigurer();
    springSocialConfigurer.postLoginUrl("/garden-planner");
    http.apply(springSocialConfigurer);

    RememberMeConfigurer<HttpSecurity> rememberMe = http.rememberMe();
    rememberMe.userDetailsService(customUserDetailsService);
    rememberMe.tokenValiditySeconds(Integer.MAX_VALUE);
    rememberMe.tokenRepository(persistentTokenRepository());

    LogoutConfigurer<HttpSecurity> logout = http.logout();
    logout.invalidateHttpSession(true);
    logout.logoutUrl("/logout");
    logout.logoutSuccessUrl("/welcome-back");

    CsrfConfigurer<HttpSecurity> csrf = http.csrf();
    csrf.disable();

    OpenIDLoginConfigurer<HttpSecurity> openidLogin = http.openidLogin();
    openidLogin.loginPage("/login");
    openidLogin.loginProcessingUrl("/login-openid");
    openidLogin.authenticationUserDetailsService(openIdUserDetailsService);
    openidLogin.permitAll();
    openidLogin.defaultSuccessUrl("/garden-planner");
    //      openidLogin.attributeExchange("https://www.google.com/.*").attribute("axContactEmail").type("http://axschema.org/contact/email").required(true);
}

From source file:org.vaadin.spring.samples.mvp.security.config.HttpSecurityConfigurer.java

void configure(Environment env, ApplicationContext context, HttpSecurity http) throws Exception {
    // all requests are authenticated
    http.authorizeRequests().antMatchers("/VAADIN/**", "/PUSH/**", "/UIDL/**", "/login", "/login/**")
            .permitAll().antMatchers("/**").fullyAuthenticated().and()
            // Vaadin chokes if this filter is enabled, disable it!
            .csrf().disable();/*from   w w w.  ja v a 2  s.  c  o m*/

    // have UI peacefully coexist with Apache CXF web-services
    String id = env.getProperty("app.security.scheme", Scheme.BASIC.id());
    Scheme scheme = Scheme.fromValue(id);
    switch (scheme) {
    case FORM:
        http.formLogin().failureUrl("/login?error").defaultSuccessUrl("/ui").permitAll().and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
                .permitAll();
        break;
    case BASIC:
        http.httpBasic();
        break;
    case DIGEST:
        // @see http://java.dzone.com/articles/basic-and-digest
        http.httpBasic();
        http.addFilterAfter(context.getBean(DigestAuthenticationFilter.class), BasicAuthenticationFilter.class);
        break;
    }

    // TODO plumb custom HTTP 403 and 404 pages
    /* http.exceptionHandling().accessDeniedPage("/access?error"); */
}

From source file:sample.MyConfigurer.java

@SuppressWarnings("unchecked")
@Override/*w w  w . ja  v a  2s.  c om*/
public void init(HttpSecurity http) throws Exception {
    // autowire this bean
    ApplicationContext context = http.getSharedObject(ApplicationContext.class);
    context.getAutowireCapableBeanFactory().autowireBean(this);

    // Our DSL allows to grant access to URLs defined by permitAllPattern in a property
    // and then requires authentication for any other request
    http.authorizeRequests().antMatchers(permitAllPattern).permitAll().anyRequest().authenticated();

    if (http.getConfigurer(FormLoginConfigurer.class) == null) {
        // only apply if formLogin() was not invoked by the user
        // this is a way of providing a default, but allow users to override
        http.formLogin().loginPage(loginPage);
    }
}

From source file:com.devnexus.ting.web.config.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    HttpSecurity httpSecurity = http.csrf().disable() //TODO Refactor login form
            .authorizeRequests().antMatchers("/s/admin/cfp**").hasAnyAuthority("ADMIN", "CFP_REVIEWER").and()
            .authorizeRequests().antMatchers("/s/admin/index").hasAnyAuthority("ADMIN", "CFP_REVIEWER").and()
            .authorizeRequests().antMatchers("/s/admin/**").hasAuthority("ADMIN").and().authorizeRequests()
            .antMatchers("/**").permitAll().anyRequest().anonymous().and().logout().logoutSuccessUrl("/s/index")
            .logoutUrl("/s/logout").permitAll().and();

    if (httpsEnabled) {
        httpSecurity = httpSecurity.requiresChannel().antMatchers("/s/admin/**").requiresSecure().and();
    }/*from  www. j  av a  2 s. c  o  m*/

    httpSecurity.formLogin().loginProcessingUrl("/s/login").defaultSuccessUrl("/s/admin/index")
            .loginPage("/s/login").failureUrl("/s/login?status=error").permitAll();
}

From source file:org.drugis.addis.config.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    String[] whitelist = { "/", "/trialverse", "/trialverse/**", "/patavi", // allow POST mcda models anonymously
            "/favicon.ico", "/favicon.png", "/app/**", "/auth/**", "/signin", "/signup", "/**/modal/*.html",
            "/manual.html" };
    // Disable CSFR protection on the following urls:
    List<AntPathRequestMatcher> requestMatchers = Arrays.asList(whitelist).stream()
            .map(AntPathRequestMatcher::new).collect(Collectors.toList());
    CookieCsrfTokenRepository csrfTokenRepository = new CookieCsrfTokenRepository();
    csrfTokenRepository.setCookieHttpOnly(false);
    http.formLogin().loginPage("/signin").loginProcessingUrl("/signin/authenticate")
            .failureUrl("/signin?param.error=bad_credentials").and().authorizeRequests().antMatchers(whitelist)
            .permitAll().antMatchers(HttpMethod.GET, "/**").permitAll().antMatchers(HttpMethod.POST, "/**")
            .authenticated().antMatchers(HttpMethod.PUT, "/**").authenticated()
            .antMatchers(HttpMethod.DELETE, "/**").authenticated().and().rememberMe().and().exceptionHandling()
            .authenticationEntryPoint(new Http403ForbiddenEntryPoint()).and()
            .apply(new SpringSocialConfigurer().alwaysUsePostLoginUrl(false)).and().csrf()
            .csrfTokenRepository(csrfTokenRepository)
            .requireCsrfProtectionMatcher(
                    request -> !(requestMatchers.stream().anyMatch(matcher -> matcher.matches(request))
                            || Optional.fromNullable(request.getHeader("X-Auth-Application-Key")).isPresent()
                            || HttpMethod.GET.toString().equals(request.getMethod())))
            .and().setSharedObject(ApplicationContext.class, context);

    http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);

}

From source file:com.appspot.potlachkk.config.WebSecurityConfig.java

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

    // We don't want to cache requests during login
    http.requestCache().requestCache(new NullRequestCache());

    //I am not sure if this configuration is not a "work-aroud"
    //maybe there is a simpler/more elegant solution

    //Avoid CSRF token related problems with mobile clients
    http.csrf().disable();/*  ww w.  j  a v a 2  s  . com*/

    //if attempt to access protected URL without authentication
    //send the client HTTP code (instead of redirecting to login form)
    //now to login a POST to /login with password=pass1&username=user1 
    //Content-Type: application/x-www-form-urlencoded must be sent
    http.exceptionHandling().authenticationEntryPoint(JSON_AUTHENTICATION_ENTRY_POINT);

    http.formLogin().successHandler(NO_REDIRECT_SUCCESS_HANDLER).failureHandler(NO_REDIRECT_FAILURE_HANDLER)
            .permitAll().and().logout().logoutUrl("/logout").logoutSuccessHandler(JSON_LOGOUT_SUCCESS_HANDLER)
            .deleteCookies("JSESSIONID").invalidateHttpSession(true).permitAll();

    //GAE - specific localhost maintenance URL
    http.authorizeRequests().antMatchers("/_ah/**").permitAll();

    //configuration URL - should be disabled in production
    http.authorizeRequests().antMatchers("/config").permitAll();
    http.authorizeRequests().antMatchers("/delconfig").permitAll();

    //test
    http.authorizeRequests().antMatchers("/image/**").permitAll();
    //http.authorizeRequests().antMatchers("/chain/**").permitAll();
    //http.authorizeRequests().antMatchers("/gift/**").permitAll();

    http.authorizeRequests().anyRequest().authenticated();
}

From source file:eu.openanalytics.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http/*ww  w  . j a v a2s .  co  m*/
            // must disable or handle in proxy
            .csrf().disable()
            // disable X-Frame-Options
            .headers().frameOptions().sameOrigin();

    if (hasAuth(environment)) {
        // Limit access to the app pages
        http.authorizeRequests().antMatchers("/login").permitAll();
        for (ShinyApp app : appService.getApps()) {
            String[] appRoles = appService.getAppRoles(app.getName());
            if (appRoles != null && appRoles.length > 0)
                http.authorizeRequests().antMatchers("/app/" + app.getName()).hasAnyRole(appRoles);
        }

        // Limit access to the admin pages
        http.authorizeRequests().antMatchers("/admin").hasAnyRole(userService.getAdminRoles());

        // All other pages are available to authenticated users
        http.authorizeRequests().anyRequest().fullyAuthenticated();

        http.formLogin().loginPage("/login").and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessHandler(logoutHandler)
                .logoutSuccessUrl("/login");
    }
}

From source file:com.xiovr.unibot.config.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    //      http.authorizeRequests().antMatchers("/css/**", "/images/**, /js/**")
    //            .permitAll().anyRequest().authenticated();
    ////from   w  w w  . j  a v  a2 s  .c  o m
    //      http.formLogin().failureUrl("/login").loginPage("/login")
    //            .loginProcessingUrl("/login/submit")
    //            .usernameParameter("username").passwordParameter("password")
    //            .defaultSuccessUrl("/", false).permitAll();
    //      http.logout().logoutUrl("/logout").invalidateHttpSession(true)
    //            .permitAll();

    http.headers().addHeaderWriter(
            new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN));
    http.headers().xssProtection();
    http.headers().cacheControl();
    http.headers().contentTypeOptions();
    HstsHeaderWriter writer = new HstsHeaderWriter(false);
    writer.setRequestMatcher(AnyRequestMatcher.INSTANCE);
    http.headers().addHeaderWriter(writer);
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/css/**", "/images/**").permitAll().anyRequest().authenticated();
    http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/login")
            .loginProcessingUrl("/login/submit").defaultSuccessUrl("/", false).permitAll().and()
            .exceptionHandling().accessDeniedPage("/error").and().logout().permitAll();
}

From source file:scratch.cucumber.example.SecurityConfiguration.java

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

    // The http.formLogin().defaultSuccessUrl("/path/") method is required when using stateless Spring Security
    // because the session cannot be used to redirect to the page that was requested while signed out. Unfortunately
    // using this configuration method will cause our custom success handler (below) to be overridden with the
    // default success handler. So to replicate the defaultSuccessUrl("/path/") configuration we will instead
    // correctly configure and delegate to the default success handler.
    final SimpleUrlAuthenticationSuccessHandler delegate = new SimpleUrlAuthenticationSuccessHandler();
    delegate.setDefaultTargetUrl("/spring/");

    // Make Spring Security stateless. This means no session will be created by Spring Security, nor will it use any
    // previously existing session.
    http.sessionManagement().sessionCreationPolicy(STATELESS);
    // Disable the CSRF prevention because it requires the session, which of course is not available in a
    // stateless application. It also greatly complicates the requirements for the sign in POST request.
    http.csrf().disable();/*w w  w. j  ava 2 s.  com*/
    // Viewing any page requires authentication.
    http.authorizeRequests().anyRequest().authenticated();
    http.formLogin()
            // Viewing the sign in page does not require authentication.
            .loginPage("/spring/signIn").permitAll()
            // Override the sign in success handler with our stateless implementation. This will update the response
            // with any headers and cookies that are required for subsequent authenticated requests.
            .successHandler(new StatelessAuthenticationSuccessHandler(authenticationBinder, delegate));
    http.logout().logoutUrl("/spring/signOut").logoutSuccessUrl("/spring/");
    // Add our stateless authentication filter before the default sign in filter. The default sign in filter is
    // still used for the initial sign in, but if a user is authenticated we need to acknowledge this before it is
    // reached.
    http.addFilterBefore(new StatelessAuthenticationFilter(authenticationBinder, securityContextHolder),
            UsernamePasswordAuthenticationFilter.class);
}

From source file:com.traffitruck.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    // handle content encoding
    CharacterEncodingFilter filter = new CharacterEncodingFilter();
    filter.setEncoding("UTF-8");
    filter.setForceEncoding(true);//from  www . j  a  va 2s .  co  m
    http.addFilterBefore(filter, CsrfFilter.class);

    http.authorizeRequests()
            .antMatchers("/css/**", "/js/**", "/images/**", "/registerUser", "/verifyPhone",
                    "/resendVerificationCode", "/registrationConfirmation", "/forgotPassword", "/resetPassword")
            .permitAll()
            .antMatchers("/newload", "/myLoads", "/deleteLoad", "/load_details/**", "/editLoad/**",
                    "/updateload")
            .hasAuthority(Role.LOAD_OWNER.name())
            .antMatchers("/truckerMenu", "/findTrucksForLoad", "/addAvailability", "/myTrucks", "/newTruck",
                    "/load_details_for_trucker/**", "/load_for_truck_by_radius", "/myAlerts", "/newAlert")
            .hasAuthority(Role.TRUCK_OWNER.name())
            .antMatchers("/loads", "/trucks", "/truckApproval", "/nonApprovedTrucks",
                    "/approval/licenseimage/**", "/truckApproval", "/load_details_json/**", "/deleteLoadAdmin",
                    "/users", "/alerts", "/allow_load_details/**")
            .hasAuthority(Role.ADMIN.name()).anyRequest().authenticated();

    http.formLogin().loginPage("/login").successHandler(successHandler()).permitAll().and().logout().permitAll()
            .deleteCookies("remember-me").logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/login?logout");
    http.rememberMe().tokenRepository(repository).userDetailsService(userDetails);

    http.sessionManagement().maximumSessions(9999).expiredUrl("/login?logout").maxSessionsPreventsLogin(false)
            .and().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).invalidSessionUrl("/login");
}