spring-security 401未授权错误:使用@PreAuthorize时凭据错误

aurhwmvo  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(184)

我总是有一个错误时,测试服务在 Postman ,例如,如果我测试版主访问()它总是生成401坏凭据。我认为问题在配置中,但我希望jwt令牌部分是好的。
enter image description here
这是我配置文件:

@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 安保的新手。

c9qzyr3d

c9qzyr3d1#

there are a few points to be checked for 401 error

  1. Try removing @preAuthorise from your method moderatorAccess() as you have already said that here
    .antMatchers("/api/test/**").permitAll() .anyRequest().authenticated();
  2. check the token passed in your header and your jwtfilter class, if you are following any tutorial, usually we make wrong key , so the token in header should be like key: Authorization and value as Bearer 'your toke here' , plaster your filter code here for reference
    3.You can remove the annotation @preauthorise and try this
antMatchers("/api/auth/seller/**").hasAuthority("ADMIN").
  1. Also when granting roles to the users, people make a mistake in role and Authority
    a role is just an authority with a special ROLE_ prefix. So in Spring security 3 @PreAuthorize("hasRole('ROLE_XYZ')") is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')") and in Spring security 4 @PreAuthorize("hasRole('XYZ')") is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')").
    Read more here - Difference between Role and GrantedAuthority in Spring Security
  2. check the token generated is for the correct role, like in your database the user is the moderator role and you are creating jwt token with that user and hitting an API with admin access
  3. Check if there is an error in configuring by disabling spring security and check if the endpoint is working by removing the spring security
  4. you can also enable formLogin in the same method of WebSecurityConfigurerAdapter like .formLogin() and try to hit the API with your browser using standard login page provided by spring security
  5. Compare your code with this github repo having basic implementation of what you are trying to do https://github.com/koushikkothagal/spring-security-jwt

相关问题