【问题标题】:role based authorization using spring security使用spring security的基于角色的授权
【发布时间】:2020-06-16 21:04:19
【问题描述】:

我正在使用 jwt 使用带有 spring security 的 spring boot 应用程序。

登录用户具有管理员权限,他正在尝试删除用户,它正在接受以下代码

角度:-

    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((""));
    }

但在我使用ROLE_USER 登录的应用程序用户中,他也可以访问该方法,如何将访问限制为仅限ROLE_ADMIN

【问题讨论】:

  • 请尝试.antMatchers("/api/v1/admin/**").hasRole("ADMIN")
  • 我会将其转换为答案 :)

标签: java angular spring-boot authentication spring-security


【解决方案1】:

修改 ant 匹配器以匹配预期的 URL。

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

【讨论】:

    猜你喜欢
    • 2020-07-09
    • 2016-07-01
    • 2021-02-15
    • 2020-12-18
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    相关资源
    最近更新 更多