401未授权错误:使用@ preauthorization时凭证错误



我在测试邮差服务时总是出错例如,如果我测试ModeratorAccess(),它总是生成401个坏凭据。我认为问题在配置,但我希望JWT令牌部分是好的。

输入图片描述

这是我的配置文件:
@Configuration
@EnableAspectJAutoProxy
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled = true,
proxyTargetClass = 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);
}
}

这是我的控制器:

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class TestController {
@GetMapping("/all")
public String allAccess() {
return "Public Content.";
}

@GetMapping("/user")
@PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
public String userAccess() {
return "User Content.";
}
@GetMapping("/mod")
@PreAuthorize("hasRole('MODERATOR')")
//@PreAuthorize("permitAll")
public String moderatorAccess() {
return "Moderator Board.";
}
@GetMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public String adminAccess() {
return "Admin Board.";
}
}

我是spring security的新手。

对于401错误有几点需要检查

  1. 尝试从方法moderatorAccess()中删除@preAuthorise,因为您已经在这里说过了

    .antMatchers("/api/测试/* *").permitAll ().authenticated .anyRequest () ();

  2. 检查在你的头和你的jwtfilter类中传递的令牌,如果你遵循任何教程,通常我们会制作错误的密钥,所以头中的令牌应该像key: Authorization和value作为Bearer 'your toke here',把你的过滤器代码贴在这里供参考

3。您可以删除注释@preauthorise,然后试试

antMatchers("/api/auth/seller/**").hasAuthority("ADMIN").
  1. 另外,当授予用户角色时,人们在角色和权限上犯了错误

    角色只是一个带有特殊ROLE_前缀的权限。因此,在Spring security 3中@ preauthorization ("hasRole('ROLE_XYZ')")与@ preauthorization ("hasAuthority('ROLE_XYZ')")相同,并且在Spring security 4中@ preauthorization ("hasRole('XYZ')")与@ preauthorization ("hasAuthority('ROLE_XYZ')"

点击这里阅读更多- Spring Security中Role和GrantedAuthority的区别

  1. 检查为正确的角色生成的令牌,例如在您的数据库中,用户是主持人角色,您正在使用该用户创建jwt令牌并使用管理员访问API

  2. 通过禁用spring security检查配置是否有错误,并通过移除spring security检查端点是否正常工作

  3. 你也可以在WebSecurityConfigurerAdapter.formLogin()相同的方法中启用formLogin,并尝试使用spring security提供的标准登录页面在浏览器中访问API

  4. 比较你的代码与这个github repo有什么你想做的基本实现https://github.com/koushikkothagal/spring-security-jwt

最新更新