'Spring Boot, ReactJS - How to access secure API after login from Frontend React JS

I just start learning spring security. I searched for solution on how to access secure API from frontend based on user role after login but still no luck.

From the backend, I secure API by role like this.

  • Only ADMIN role can access localhost:8080/admin/*
  • Only USER role can access localhost:8080/user/*

Below is my WebSecureConfig.

   protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.cors().disable();
    http.authorizeRequests()
            .antMatchers("/","/register","/add","/login","/index").permitAll()
            .antMatchers("/admin/*").hasAuthority("ADMIN")
            .antMatchers("/user/*").hasAuthority("USER")
            .anyRequest().authenticated()
            .and()
            .formLogin().loginPage("/login")
            .defaultSuccessUrl("/index")
            .failureUrl("/login?fail=true")
            .loginProcessingUrl("/perform_login")
            .usernameParameter("username")
            .passwordParameter("password")
            .and()
            .logout().logoutUrl("/logout")
            .deleteCookies("JSESSIONID")
            .and()
            .httpBasic();
}

This is my Entity class

public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role;

}

This is my controller class. I create 2 Get methods to test user role. One is admin url and one is user url

@GetMapping("/admin/index")
public String getAdminIndex(){
    return "This is Admin Page";
}

@GetMapping("/user/index")
public String getUserIndex(){
    return "This is User Page";
}

From frontend, I use axios to perform login

async login(_username, _password) {
return await axios.post(
  LOGIN_URL,
  {},
  {
    withCredentials: true,
    auth: {
      username: _username,
      password: _password,
    },
  }
);

}

It works. I got all information of user.
Then from frontend, I create 2 functions to handle get API based on role

getAdminPage() {
  return axios.get("http://localhost:8080/admin/index");
}
getUserPage() {
  return axios.get("http://localhost:8080/user/index");

}

This is my login form

On the login form, I have 2 buttons, Admin and User. Each button will handle a function getAdminPage() or getUserPage() which I mentioned above.

My question is, after login, only Admin role can click on Admin button, and only User role can click on User button. Even though both Admin and User roles can see both buttons. How can I handle that? Right now, I only know how to perform login, but do not know how to access secure API from frontend based on user role.

Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source