簡體   English   中英

基於 JWT 角色的 Spring Security 授權

[英]JWT role Based Authorization with Spring Security

我想向具有“ADMIN”角色的用戶授予對 /hello URL 的訪問權限,我有這樣的安全配置。 從“/authenticate” URL 我得到 jwt 令牌。

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/authenticate").permitAll()
            //.antMatchers("/hello").hasRole("ADMIN")
            .anyRequest().authenticated().
            and().
            exceptionHandling().and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

我試圖在我的控制器中添加 @PreAuthorize 注釋,但它不起作用所有用戶都可以訪問該 url。

    @GetMapping("/hello")
    @PreAuthorize("hasRole('ADMIN')")
    public String test(){
        return "Hello";
    }

從控制器中刪除 @PreAuthorize 注釋並像這樣更改安全配置后,它解決了我的問題。
@Darren 非常感謝您的評論,它解決了我的問題。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/authenticate").permitAll()
        .antMatchers("/hello").hasAuthority("ADMIN")
        .anyRequest().authenticated().
        and().
        exceptionHandling().and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, 
        UsernamePasswordAuthenticationFilter.class);
}

暫無
暫無

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

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