Spring Security with Spring boot
1. Go to maven Repository and search “Spring Boot Starter Security” Choose any of the latest
version adds a dependency to pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>3.1.2</version>
</dependency>
2. Run the Springboot application Spring Security will generate a new password for you
check-in console.
Using generated security password: f6f3790e-e62a-4147-bc08-d1d3bsa92fdd7
3. Try to access Rest API in a web browser it will redirect to a login page.
http://localhost:8080/login
4. you can log in with username=user and password = f6f3790e-e62a-4147-bc08-
d1d3bsa92fdd7 the generated password.
5. After that you can use your api6.Change username and password using the application. properties file
spring.security.user.name=neeraj
spring.security.user.password=Neeraj
now you can log in with this login and password while accessing the API.
7. To log out from the spring security use the logout path.
http://localhost:8080/logout
8. Create In memory user
Create a class and create and user annotate with @Configration user
@Configuration
public class Security {
@Bean
UserDetailsService userDetailsService() {
UserDetails user =
User.builder ().username("Duresh").password(passwordEncoder().encode("abc")).roles("ADMIN").build();
return new InMemoryUserDetailsManager(user);
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
9. Get Current User by Principal class
@GetMapping("/getCurrentUser")
public String getLoggedInUser(Principal principal) {
return principal.getName();
}
Comments
Post a Comment