15 Spring Security (1)
15 Spring Security (1)
Spring Security is powerful and highly customizable authentication and access control framework for Java
application.
Spring Security is a framework that focuses on providing both authentication and authorization to Java application.
Authentication
Authentication is a process to verify the identity of user.
Spring security supports various authentication mechanisms such as form-base, basic, digest, OAuth, JWT.
Authorization
Authorization means it gives the permission to user to access a specific resource or functions after successful
Authentication.
It also provide user based access control authorization where user can access a resource as role bases assigning.
Other way is
We can create security configuration class.
Add annotation on this class as @Configuration and @EnableWebSecurity.
@EnableWebSecurity – this annotation tells to spring to enable its web security support.
This annotation allow to default and customization of feature in security of application.
@Configuration
@EnableWebSecurity
public class SecurityConfig{
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user1 = User.withDefaultPasswordEncoder()
.username("adminUser")
.password(this.passwordEncoder().encode("admin"))
.roles("ADMIN")
.build();
UserDetails user2 = User.withDefaultPasswordEncoder()
.username("normalUser")
.password(this.passwordEncoder().encode("normal"))
.roles("NORMAL")
.build();
return new InMemoryUserDetailsManager(user1,user2);
}
Explain Cross-Origin Resource sharing (CORS) and how would you configure in a spring boot application?
Cross Origin resource sharing allows a website to safely access resource from another website.
In spring boot we can set up CROS by adding @CrossOrigin to controller class or configuration it globally.
This annotation tells spring application which other web sites can use its resources and what type of request they
can make and what header they can use.
This way we can control who can interact with our application keeping it secure while letting it communicate across
different web domains.
Create class for UserDetailService and implement UserDetailServise and annoted this as @Service.
Implement all method in it.