0% found this document useful (0 votes)
12 views4 pages

Theory of Springsecurity

The document outlines the process of creating a user registration and login system using Spring Boot, including setting up JPA entities, repositories, and controllers. It details the implementation of user creation with email and username validation, password encryption using BCrypt, and a login verification method. Additionally, it describes configuring Spring Security to permit all requests and manage user authentication securely.

Uploaded by

Nitesh Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views4 pages

Theory of Springsecurity

The document outlines the process of creating a user registration and login system using Spring Boot, including setting up JPA entities, repositories, and controllers. It details the implementation of user creation with email and username validation, password encryption using BCrypt, and a login verification method. Additionally, it describes configuring Spring Security to permit all requests and manage user authentication securely.

Uploaded by

Nitesh Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

First we create all the required package like

config,controller,service,security,repository,entity,payload etc

than we create a Class "AppUser" in "entity" by JpaEntity their we create a


variable name, username, password, email by basic type in JPA designer.

After that we create Jpa repository for "AppUser"

after that we create a class "UserController" in "controller" their we make that


class a @RestController and give end point in @RequestMapping("/api/v1/user")

here, In controller layer we create a method createUser and give it a annotation of


@PostMapping

like:-
private AppUserRepository appUserRepository;

//we make a constructor of AppUserRepository


public UserController(AppUserRepository appUserRepository){
this.appUserRepository = appUserRepository;
}
@PostMapping
public ResponseEntity<AppUser> createUser(@RequestBody AppUser user){
AppUser createdUser = appUserRepository.save(user);
return new ResponseEntity<>(createdUser,HtppStatus.CREATED);
}

Now, If we again try to register the user with same Username or with same email
address than it will show us an error but we don't want to see that error instead
of that we want to see a message that user exists or email exists.

So, for that we create a method in repository layer like this:-

public interface AppuserRepository extends JpaRepository<AppUser,Long>{


boolean existsByEmail(String email);
boolean existsByUsername(String username):
}

Now, after add the method in repository we need to go to controller layer and make
a coditions their

private AppUserRepository appUserRepository;

//we make a constructor of AppUserRepository


public UserController(AppUserRepository appUserRepository){
this.appUserRepository = appUserRepository;
}
@PostMapping
public ResponseEntity<AppUser> createUser(@RequestBody AppUser user){
if(appUserRepository.existsByEmail(user.getEmail()){
return new ResponseEntity<>("Email
exists",HttpStatus.Bad_Request);
}

if(appUserRepository.existsByUsername(user.getUsername()){
return new ResponseEntity<>("Username
exists",HttpStatus.Bad_Request);
}
AppUser createdUser = appUserRepository.save(user);
return new ResponseEntity<>(createdUser,HtppStatus.CREATED);
}

Now next step TO MAKE THE URL OPEN for that we do below things:-
Now, to configure the URL we need to do spring Config in our project and for that
we go to our "config" package and create

In order to take the permission to open the Url we go to our "config" package and
create a class "SecurityConfig"
the purpose of adding this class is we are going to modify the configuration of
spring security

when I signUp the "username and password" will go to database and the username-
password is verify with the database

make SecurityConfigClass annotated with @Configuration the meanning of


@Configuration is whenever the Application is start in Springboot this class that
is annoted with @Configuration that will automatically handover to springIOC.

now, In "SecurityConfig" class we create a method "SecurityFilterChain" like:-

@Configuration //
public class SecurityConfig{

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws
Exception{
http.csrf().disable().cors().disable();
http.authorizeHttpRequests.anyRequest.permitAll();
return http.build();
}

here, we also make SecurityFilterChain method annoted with @Bean beacuse Spring IOC
have only limited information of object creation so when we get object from another
class than we use @Bean for that.

And, Pass the object of HttpSecurity in it


than write "http.csrf().disable().cors().disable();" meaning of this line is
//disabling the attack safety. //if you enable the cors than your application will
intereact what you want.//only with the client I design for only with that my
backend will intreact.

And,after that we write "http.authorizeRequest.anyRequest.permitAll();" and the


meaning of this is // whatever url came here permit all.//any incoming http
requests permit all.

And, after that we write "return Http.build();" and the meaning of this line is
create an object with configuration that ultimately spring security is using it.

Now, The next step is "HOW TO ENCRYPT THE PASSWORD BEFORE I SAVE TO DATABASE"

to encrypt the pasword we create an object of "BCryptPasswordEncoder"


PasswordEncoder passwordEncoder = new BCryptPasswordEncoder;
how we implement it
The One way is this:-
public class A{
psvm(){
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
sout(passwordEncoder.encode("testing));
}
}

The another way is:-/if no. of rounds of your encryption is 10 than the decryption
is also 10. So, higher the round you take for encrypt than the no. of round of
decryption is deteriote here.

public class B{
psvm(){
sout(BCrypt.hasPw("testing",BCrypt.genSalt(10)));
}
}

NOW next thing is we go to controller layer and In we have UserController that is


save the password as it is in database now we are going to decrypt the password and
save it.

Before, You save this user what we do is, we go to user object and in user object
we set password like:-

user.setPassword(BCrypt.haspw(user.getPassword(),BCrypt.genSalt(10)));

And, here we implement like this:-

private AppUserRepository appUserRepository;

//we make a constructor of AppUserRepository


public UserController(AppUserRepository appUserRepository){
this.appUserRepository = appUserRepository;
}
@PostMapping
public ResponseEntity<AppUser> createUser(@RequestBody AppUser user){
if(appUserRepository.existsByEmail(user.getEmail()){
return new ResponseEntity<>("Email
exists",HttpStatus.Bad_Request);
}

if(appUserRepository.existsByUsername(user.getUsername()){
return new ResponseEntity<>("Username
exists",HttpStatus.Bad_Request);
}

//here we implement this


user.setPassword(BCrypt.haspw(user.getPassword(),BCrypt.genSalt(10)));

AppUser createdUser = appUserRepository.save(user);


return new ResponseEntity<>(createdUser,HtppStatus.CREATED);
}
Now, We are going to create singin Feature for that

Now, we are going to create veriftyLogin


for that we create a method in controller

And, from here we call userService and create a method verifyLogin in Service layer
and the return type is boolean.
public ResponseEntity<String> verifyLogin(@RequestBody Logindto loginDto){
boolean val = userService.verifyLogin(loginDto);
}

NOw, In order to search the record in our database on based of username we need to
create a method in repository layer which return of type Optional Class.

Otional<AppUser> findByUsername(String username);

after that we write code in service layer for the search the record in database by
Username
from above code we call "userService.verifyLogin".

So, the code is like

public Boolean verifyLogin(LoginDto loginDto){


Optional<AppUser> opUsername =
appUserRepository.findByUsername(loginDto.getUsername()); //and it will return
//optional class Optional<AppUser>
if(opUsername.isPresent()){
AppUser appUser = opUsername.get();
//Now, if username is present than it will check the password
BCrypt.checkpw(loginDto.getPassword(),appUser.getPassword());// It will
first check the password what user
is giving(loginDto.getPassword()) and what
is their in database(appUser.getPasswor())
}
return false; // otherwise it will return false.

You might also like