春のセキュリティを使用して役割ベースの許可

ラヴィクマールRavanam:

私は、JWTを使って春のセキュリティと春のブートアプリケーションを使用しています。

ログインユーザが管理者のアクセス権を持っている、と彼はユーザーを削除しようとしている、それは次のコードで受け付けています

角度: -

    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のみ。

RG:

期待されるURLと一致するようにアリのmatcherを変更します。

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=23512&siteId=1