Home > Enterprise >  Java / 401 / Unauthorized / GET Method
Java / 401 / Unauthorized / GET Method

Time:08-18

I am trying to test an endpoint with Postman and I receive an error. I am trying to test a search function that should search for all hotels saved in a database

  1. route: http://localhost:8080/hotels
  2. error received in postman (as an output):
{
    "timestamp": "2022-08-17T04:43:07.249 00:00",
    "status": 401,
    "error": "Unauthorized",
    "path": "/hotels"
}
  1. I have to mention that in postman I am using GET HTTP method authorization: "no auth"
  2. if I change authorization in "basic auth" I receive the following message: could not get a response
  3. Security configuration in my app:
    protected void configure(HttpSecurity security) throws Exception {
        security
                .csrf().disable() 
                .cors().disable()
                .authorizeRequests()
                .antMatchers("/trip", "/hotels")
                .hasAnyAuthority("ADMIN")
                .and()
                .httpBasic()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

In order to help me I can post other parts from the code, or I can upload the project on Github and put a link here.

CodePudding user response:

Status 401 means that your credentials were not valid. Your code here:

.antMatchers("/trip", "/hotels")
.hasAnyAuthority("ADMIN")

says that you need to authenticate yourself with user who has "ADMIN" role. Then your endpoint will process the request and send you response. Otherwise you'll always get 401. Set in postman basic auth and put your username and password (user with ADMIN role) then it will work

CodePudding user response:

@pan-leszeczek

  1. i do not think is from that place, below you will find another part from my code.

        System.out.println("Inserting roles in database");
    

    Role userRole = new Role(); userRole.setName(RoleTypes.USER); userRole.setDescription("This role is designed for users");

    Role userRole1 = new Role(); userRole1.setName(RoleTypes.USER); userRole1.setDescription("Duplicate role");

    Role adminRole = new Role(); adminRole.setName(RoleTypes.ADMIN); adminRole.setDescription("This role can add hotels and trips");

    User adminUser = new User(); adminUser.setUsername("admin"); adminUser.setPassword("admin");

    Role adminRoleInDatbase = roleService.findByName(RoleTypes.ADMIN); adminUser.setRole(adminRoleInDatbase);

  2. when is use "post" method, in postman, and basic auth with user pass admin admin, i can insert new hotels in data base, but when i try to use GET method A) no auth - i receive 401 error b) basic auth with admin admin message from postman: could not get response

  • Related