簡體   English   中英

使用 Spring Security 基於角色的授權

[英]role based authorization using spring security

我正在使用 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);
    }

控制器.java

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

        authenticationService.deleteUser(userId);

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

但是在我使用ROLE_USER登錄的應用程序用戶中,他也可以訪問該方法,如何將訪問限制為ROLE_ADMIN

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM