简体   繁体   English

错误:使用@PreAuthorize 时需要完全身份验证才能访问此资源

[英]Error: Full authentication is required to access this resource when using @PreAuthorize

I am trying to implement a authentication using Spring Boot, JWT with Roles我正在尝试使用 Spring Boot、JWT with Roles 实现身份验证

I have the error:我有错误:

full authentication is required to access this resource访问此资源需要完整身份验证

when send POST request to "http://localhost:8080/api/profile/edit_user_detail" (with authoziration header)POST请求发送到“http://localhost:8080/api/profile/edit_user_detail”(带有授权标头)时

Below is my Controller下面是我的控制器

@Controller
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping("/api/profile")
public class UserAPI {

    @Autowired
    UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    QARepository qaRepository;
    @Autowired
    DiscussRepository discussRepository;
    @Autowired
    AnnouncementRepository announcementRepository;

    @PostMapping(value = {"/edit_user_detail"})
    @PreAuthorize("hasRole('ROLE_USER')")
    public ResponseEntity<?> editInfo(@RequestBody Map map) throws ParseException {
        String username = map.get("username").toString();
        String display_name = map.get("display_name").toString();

        User user = userRepository.findByUserName(username).get(0);
        user.setuDigitalName(display_name);
       
        userRepository.save(user);

        return ResponseEntity.ok("Updated");
    }

But when i remove the line但是当我删除该行时

@PreAuthorize("hasRole('ROLE_USER')") @PreAuthorize("hasRole('ROLE_USER')")

then i can success POST the request and edited successfully the user (I have checked in database)然后我可以成功发布请求并成功编辑用户(我已经检查了数据库)

Also this is my EntryPoint (to catch Exception)这也是我的入口点(捕捉异常)

@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {
    private static final Logger log = LoggerFactory.getLogger(AuthEntryPointJwt.class);
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.error("Authorized error: " + e.getMessage());
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Error: Unauthorized");
        e.printStackTrace();
    }
}

And this is my Configuration file这是我的配置文件

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ConfigAuthenticate extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServices userDetailsServices;

    @Autowired
    private AuthEntryPointJwt unauthorizeHandler;

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

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

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServices).passwordEncoder(passwordEncoder());
    }

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

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

}

I think there are a problem with configuration in WebSecurityConfigurerAdapter , i have try to我认为WebSecurityConfigurerAdapter 中的配置有问题,我已尝试

  • Change @PreAuthorize("hasRole('ROLE_USER')") to @PreAuthorize("hasRole('USER')")@PreAuthorize("hasRole('ROLE_USER')")改为@PreAuthorize("hasRole('USER')")
  • Check the JWT Token in header, also the ROLE in database检查标头中的 JWT 令牌,以及数据库中的 ROLE

but it's still not work, anybody have solution但它仍然不起作用,任何人都有解决方案

Try removing .antMatchers("/**").permitAll() , and add these lines to your:尝试删除.antMatchers("/**").permitAll() ,并将这些行添加到您的:

application.yml应用程序.yml

logging:
  level:
    org.springframework.security: TRACE

or application.properties或 application.properties

logging.level.org.springframework.security=TRACE

And you could see the information about your user like this:您可以像这样看到有关您的用户的信息:

AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]]

You can rely on Granted Authorities in order to determine user's roles您可以依靠Granted Authorities来确定用户的角色


Because you're setting .antMatchers("/**").permitAll() before .anyRequest().authenticated() , I'm not so sure whether you validated the user successfully or not.因为您在.antMatchers("/**").permitAll()之前设置了.antMatchers("/**").permitAll() .anyRequest().authenticated() ,所以我不确定您是否成功验证了用户。 If not, then the AnonymousAuthenticationFilter will create an anonymous user for you.如果没有,那么AnonymousAuthenticationFilter将为您创建一个匿名用户。 And in case you don't add @PreAuthorize("hasRole('USER')") , the FilterSecurityInterceptor , bases on .antMatchers("/**").permitAll() , will allow the request gets through it and accesses the controller.如果您不添加@PreAuthorize("hasRole('USER')") ,基于.antMatchers("/**").permitAll()FilterSecurityInterceptor将允许请求通过它并访问控制器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 JWT 授权时获取“访问此资源需要完全身份验证” - Getting "Full authentication is required to access this resource" when using JWT grant 未经授权的错误:需要完全身份验证才能访问此资源 - Unauthorized error: Full authentication is required to access this resource 错误未经授权,需要完全验证才能访问此资源 - Error Unauthorized, Full authentication is required to access this resource JAVA JPA 错误 401:“访问此资源需要完整身份验证” - JAVA JPA error 401: "Full authentication is required to access this resource" spring oauth错误,需要完全认证才能访问此资源 - spring oauth error Full authentication is required to access this resource 启动应用程序时“未授权:访问此资源需要完全身份验证” - "Unauthorized: Full authentication is required to access this resource" when booting up the app 状态=401,错误=未授权,消息=在尝试接收令牌时需要完全身份验证才能在 Spring 框架中访问此资源 - status=401, error=Unauthorized, message=Full authentication is required to access this resource in Spring Framework when trying to receive a token Jhipster gateway 需要完整的身份验证才能访问此资源 - Jhipster gateway Full authentication is required to access this resource InsufficientAuthenticationException:访问此资源需要完全身份验证 - InsufficientAuthenticationException: Full authentication is required to access this resource 需要身份验证才能访问此资源错误 - Authentication is required to access this resource error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM