role based authorization using spring security

Ravi Kumar Ravanam :

I am using spring boot application with spring security using jwt.

login user is having the admin access, and he is trying to delete the user, it is accepting with the following code

angular:-

    delete(userId: number) {
        debugger;
        return this.http.delete(`/api/v1/admin/deleteUser/${userId}`);
    }

SpringSecurityConfig.java

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()      
         .headers()
          .frameOptions().sameOrigin()
          .and()
            .authorizeRequests()
             .antMatchers("/api/v1/authenticate", "/api/v1/register","/api/v1/basicauth").permitAll()
                .antMatchers("/").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")//only admin can access this
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/home")
                .failureUrl("/login?error")
                .permitAll()
                .and()
            .logout()
             .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
             .logoutSuccessUrl("/login?logout")
             .deleteCookies("my-remember-me-cookie")
                .permitAll()
                .and()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

            // Add a filter to validate the tokens with every request
            http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

controller.java

@DeleteMapping(path = "/admin/deleteUser/{userId}")
    public ResponseEntity<?> deleteUser(HttpServletRequest request,@PathVariable int userId) { 

        authenticationService.deleteUser(userId);

        return ResponseEntity.ok((""));
    }

but in my application user login with ROLE_USER, he is also able to access that method, how to restrict access upto ROLE_ADMIN only.

R.G :

Modify the ant matchers to match the expected URL.

.antMatchers("/api/v1/admin/**").hasRole("ADMIN") //only admin can access this

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23266&siteId=1