Disabling CSRF and Frame Options:
http
.csrf().disable()
.headers().frameOptions().disable()
- csrf().disable(): Disables Cross-Site Request Forgery protection.
- headers().frameOptions().disable(): Disables frame options to allow using the H2 console within a frame.
Configuring URL-Based Authorization:
.and()
.authorizeRequests()
.antMatchers("/", "/css/**", "/images/**", "/js/**", "/h2-console/**", "/profile").permitAll()
.antMatchers("/api/v1/**").hasRole(Role.USER.name())
.anyRequest().authenticated()
- authorizeRequests(): Starts configuring URL-based access management.
- antMatchers("/", "/css/", "/images/", "/js/", "/h2-console/", "/profile").permitAll(): Allows unrestricted access to the specified URLs.
- antMatchers("/api/v1/**").hasRole(Role.USER.name()): Requires users to have the USER role to access URLs starting with /api/v1/.
- anyRequest().authenticated(): Requires all other URLs to be accessible only to authenticated (logged-in) users.
entire source
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.headers().frameOptions().disable() // Disables these options to use the H2 console screen.
.and()
.authorizeRequests() // The starting point for setting URL-specific access management.
.antMatchers("/", "/css/**", "/images/**", "/js/**", "/h2-console/**", "/profile").permitAll()
// Specifies the targets for access management.
// Allows management by URL and HTTP method.
// Grants full access to the specified URLs such as '/' through the permitAll() option.
.antMatchers("/api/v1/**").hasRole(Role.USER.name())
// Only users with the USER role can access APIs with the "/api/v1/**" address.
.anyRequest().authenticated()
// Refers to the remaining URLs not specified.
// Adds authenticated() to require login for all remaining URLs.
.and()
.logout()
.logoutSuccessUrl("/")
.and()
.oauth2Login()
.userInfoEndpoint()
// Manages settings for retrieving user information after a successful OAuth2 login.
.userService(customOAuth2UserService);
// Registers the implementation of the UserService interface to handle post-login actions.
// You can specify additional functions to proceed after retrieving user information from the resource server (i.e., social services).
}