首页 > 解决方案 > 出现未经授权的错误:需要完全身份验证才能访问此资源

问题描述

我正在我的应用程序中实现JWTSpring Security进行身份验证。

我有 3 个角色:管理员、版主和用户。

例如,在使用用户角色登录后,我得到了主页,但是一旦我通过单击按钮进入用户空间,我得到:

2020-09-04 09:01:22.819 错误 10148 --- [nio-8080-exec-5] cbssecurity.jwt.AuthEntryPointJwt:未经授权的错误:访问此资源需要完全身份验证

文件webSecurityConfig.java是:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        // securedEnabled = true,
        // jsr250Enabled = true,
        prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests().antMatchers("/api/auth/**").permitAll()
            .antMatchers("/api/test/**").permitAll()
            .anyRequest().authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

文件application.properties,我把:

spring.datasource.url=...
spring.datasource.username=...
spring.datasource.password=...
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect=...
spring.jpa.hibernate.ddl-auto=update
bezkoder.app.jwtSecret= bezKoderSecretKey
bezkoder.app.jwtExpirationMs= 86400000

在浏览器控制台中,我得到了那个异常

你能帮我解决这个问题吗?非常感谢。

标签: reactjsspring-bootspring-securityjwt

解决方案


你应该评论@PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")

说说结果?。


推荐阅读