spring-security-error使用@preauthorize(“hasrole('admin'))会导致404

gudnpqoy  于 2021-09-21  发布在  Java
关注(0)|答案(1)|浏览(455)

我在使用@preauthorize(“hasrole('admin'))注解时遇到问题。我的控制器代码如下所示,其中包含方法welcome(),该方法只能由具有admin角色的用户访问:

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/user/auth")
public class TestController {

    @GetMapping("/welcome")
    @PreAuthorize("hasRole('ADMIN')")
    public String welcome() {
        return "Welcome!!!";
    }
}

以下是我的安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(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("/user/auth/**").permitAll()
                .anyRequest().authenticated();

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

authentrypointjwt类如下:

@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {

    private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        logger.error("Unauthorized error: {}", authException.getMessage());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized");
    }

}

这是我正在使用的url:http://localhost:8080/user/auth/welcome 这就是我们的回应

{
    "message": null,
    "httpStatusCode": 404,
    "errorLevelCode": "0x2",
    "errorMessage": "Access is denied",
    "apiPath": null,
    "httpMethod": null
}

所以,我使用postman在授权头中发送jwt bearer+令牌,它抛出404。它应该在发送授权头后返回带有令牌的资源。我想不出是什么问题。如果能有一些建议或者知道我在这里做错了什么,那将是非常棒的。提前谢谢。

i7uaboj4

i7uaboj41#

错误404表明您在端点Map方面有问题(在路径中找不到资源)。如果是安全问题,您将得到错误401(未经授权)或错误403(禁止)。
如果我是对的,那么当您删除@preauthorize并在访问权限为“permitall”的安全配置中添加“welcome”路径时,您应该会遇到相同的错误。

相关问题