Priyesh Jakhmola
Priyesh Jakhmola

Reputation: 101

Using Sessions in angular with Springboot

So I'm trying to login and maintain session to keep track of users logged into my library portal, I have made the backend services on Springboot and am using Angular for frontend, I was looking into Spring Boot + Session Management Hello World Example, https://www.javainuse.com/spring/springboot_session i have made some modifications for this to work with my app, the code runs perfectly when i hit the api using postman, but when i try to hit these API from angular, for some reason it creates new session for every page I shuffle through, and when i invalidate a session it creates one and destroys the same leaving the session i created with login still sitting in my DB,

code for API my controller :-

@Autowired
 BCryptPasswordEncoder passwordEncoder;

@GetMapping("/")
public String home(Model model, HttpSession session) {
    @SuppressWarnings("unchecked")
    List<String> messages = (List<String>) session.getAttribute("MY_SESSION_MESSAGES");

    if (messages == null) {
        messages = new ArrayList<>();
    }
    model.addAttribute("sessionMessages", messages);

    return "index";
}

@PostMapping("/persistMessage")
public String persistMessage(@RequestBody message msg ,  HttpServletRequest request) {
    @SuppressWarnings("unchecked")
    List<String> msgs = (List<String>) request.getSession().getAttribute("MY_SESSION_MESSAGES");
    if (msgs == null) {
        msgs = new ArrayList<>();
        request.getSession().setAttribute("MY_SESSION_MESSAGES", msgs);
    }
    msgs.add(msg.getMsg());
    request.getSession().setAttribute("MY_SESSION_MESSAGES", msgs);
    return "redirect:/";
}

@PostMapping("/destroy")
public String destroySession(HttpServletRequest request) {
    request.getSession().invalidate();
    return "redirect:/";
}
        @PostMapping("/uname")
public User getUserByEmail(@RequestBody User user) throws Exception {
    
     String name = userRepo.findByEmailAddress(user.getEmail());
     
     throw new emailException(name);
     
     
    
}

@PostMapping("/login")
public String login(@RequestBody User user) throws Exception{
    
    
    String email = user.getEmail();
    String pass = user.getPassword();
    
    
    
    if(userRepo.findByEmail(email) == null) {
         throw new emailException("User with this email doesnt exist!");
       
    }else {
        
        String encodedPass = userRepo.encryptPass(email);
        Boolean matches = passwordEncoder.matches(pass, encodedPass);
        
        if (matches == true) {
            
            if(loginRepo.loggedinuser(email, pass)!= null) {
             
                 
             loginRepo.existinglogin(email);
             
             loginRepo.save(new logindetails(email,pass,1));
             
            
             
             return "login Sucessful";
             
            
             
            
         }else {
             

             loginRepo.save(new logindetails(email,pass,1));
             return "login Sucessful";
         }
        }
        
        else {
            return "Incorrect Password! ";
            
        }
        
        
        
    }
    

}

Angular .ts file for login (to create session)

   name = "";

loginUser(Email: string, Password: string) {

let url = "http://localhost:8081/lib/login";

let url1 = "http://localhost:8081/lib/persistMessage";
let url2 = "http://localhost:8081/lib/uname";


this.http.post(url, {


  "email": Email,
  "password": Password
}).subscribe(
  (response) => {

    console.log(response)


  },
  (error) => {


    if (error.status == 200) {

      this.http.post(url2, {


        "email": Email,
      }).subscribe(
        (response) => {

        },
        (error) => {


          if (error.status == 500) {

            this.name = error.error.message;




            this.http.post(url1, {


              "msg": this.name
            }).subscribe(
              (response) => {

              },
              (error) => {


                if (error.status == 200) {

                } else {

                  alert(error.message.message)



                }
              }
            )

          } else {




          }
        }
      ),



        alert("Logged in Successfully! Click OK to go to Books page")

      this.router.navigate(['/booklist'])




    } else {



      alert(error.error.message);

    }
  }
)

}

logout .ts file (to destroy session)

   logout() {

    let url = "http://localhost:8081/lib/destroy";

this.http.post(url, {


}).subscribe(
  (response) => {

    console.log(response),
      this.router.navigate(['/home'])

  },
  (error) => {


    if (error.status == 200) {

      alert("Logged Out Successfully!");

      this.router.navigate(['/home'])


    } else {



      alert(error.error.message);

    }
  }
)

}

i am running my springboot on eureka server which is managed by zuul gateway. though I'm not using the gateway for this.

same Api when i hit on postman i.e http://localhost:8081/lib/persistMessage with body

 {
   "msg": "[email protected]"
  }

works and creates session, same with angular, but when i hit http://localhost:8081/lib/destroy with postman it destroys the session but same Api when called from angular Won't work. please help where i am going wrong.

Also I'm using exception to get the user name to be stored in session, because for some reason angular wont pickup my return name.

Upvotes: 2

Views: 3329

Answers (1)

GeertPt
GeertPt

Reputation: 17874

If you're using the angular commom $http client, it does not send the JSESSIONID cookie by default on requests.

You can enable it via a lot of different ways, the easiest is to add a parameter to your post call:

this.http.post(url1, {
    "msg": this.name
}, {withCredentials: true})

See also Communication between AngularJS and a Jersey Webservice which are on a different domain. Can't access correct session

Upvotes: 1

Related Questions