User Form Based Login


@Configuration

public class MySecurityConfig {


@Bean

SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http.httpBasic();

http.authorizeHttpRequests().anyRequest().authenticated();

return http.build();

}

 }

Getting given below screen without using Form based login 


After using http.formLogin();

@Bean

SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http.formLogin();

http.authorizeHttpRequests().anyRequest().authenticated();

return http.build();

}



Will get this screen with login page

Few more Method

Support there is one more method is there in our application controller calss

@RestController

public class HelloController {

@GetMapping("/hello")

public String hello() {

return "Spring Security Rocks!!";

}

@GetMapping("/by")

public String bye() {

return "Bye Bye tata";

}


}


if we have login with Hello user once

http://localhost:8080/hello

than we can able to access

http://localhost:8080/by usl as well without asking to login again

so avoid this accessiblity of other url


This is Happening because of in our configuration fileanyRequest().authenticated() will enable all the request

which comes in to the application


@Configuration

public class MySecurityConfig {

@Bean

SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http.formLogin();

http.authorizeHttpRequests().anyRequest().authenticated();

return http.build();

}


@Bean

BCryptPasswordEncoder passwordEncoder() {

return new BCryptPasswordEncoder();

}

}


use given below which will allow only /hello url with login access

@Bean

SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http.formLogin();

http.authorizeHttpRequests().requestMatchers("/hello").authenticated();

return http.build();

}


OR

@Bean

SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http.formLogin();

http.authorizeHttpRequests().requestMatchers("/hello").authenticated()

.anyRequest().denyAll();

return http.build();

}

now with /by url will get given below Access to localhost was denied will come up




Comments