当前位置: 首页 > 知识库问答 >
问题:

对现有终结点的错误 401 未经授权,服务器日志中未引发错误

曾骁
2023-03-14

我已将用户名和密码字段添加到现有客户实体。我添加了一个自定义 JWT 过滤器和身份验证提供程序,并带有 WebSecurityConfig 注释@Order(2)。但是当我发送带有用户名和密码有效负载的post请求时,我收到未经授权的错误401响应,但是服务器日志中没有错误消息,我已经适当地检查了WebConfig文件。我做错了什么?我整天都在做这件事,我似乎已经很沮丧了。

这是用户详细信息类

public class MyCustomerDetails implements UserDetails{

    /**
     * 
     */
    private static final long serialVersionUID = -5087929420394311276L;

    private Long id;
    private String username;
    private String password;
    
    public MyCustomerDetails() {
        
    }
    
    public MyCustomerDetails(Long id, String username, String password) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
    }

   public static MyCustomerDetails build(Customer customer) {
        return new MyCustomerDetails(customer.getId(), 
                customer.getUserName(), customer.getPassword());
    }


   @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getPassword() {
        // TODO Auto-generated method stub
        return password;
    }

    @Override
    public String getUsername() {
        // TODO Auto-generated method stub
        return username;
    }

    ............

这是控制器类

@CrossOrigin(origins = {"http://localhost:3000"})
@RestController
public class CustomerController {
    
        @Autowired
        CustomerAccountService customerRepo;
        
         @Autowired
         private CustomerJwtTokenUtil customerJwtTokenUtil;
        
         @Autowired
         private AuthenticationManager authenticationManager;
         
    
         @PostMapping(value="/validateCustomer")
          public ResponseEntity <?> createAuthenticationToken( @RequestBody MyCustomerDetails
          authenticationRequest) throws Exception 
             {  
             authenticate(authenticationRequest.getUsername(),  
                authenticationRequest.getPassword()); 
        // Long userId = authenticationRequest.getId();
             final MyCustomerDetails userDetails =  
                 (MyCustomerDetails)   customerRepo.loadUserByUsername(authenticationRequest.getUsername());
           
           final String token = 
                   customerJwtTokenUtil.generateToken(userDetails);
          
          return new ResponseEntity<>(new JwtResponse(token), HttpStatus.OK) ;
                    
         
               }
         private void authenticate(String username, String password) throws Exception {
                    try {
                        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
                    } catch (DisabledException e) {
                        throw new Exception("USER_DISABLED", e);
                    } catch (BadCredentialsException e) {
                        throw new Exception("INVALID_CREDENTIALS", e);
                    }
                }
             

这是WebSecurityconfig类


@Configuration
@Order(2)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CustomerSecurityConfiguration extends WebSecurityConfigurerAdapter {

    
    @Autowired
    private CustomerJwtAuthenticationEntryPoint customerJwtAuthenticationEntryPoint;
    
    @Autowired
    private UserDetailsService myCustomerDetailsService;
    
    @Autowired 
    private CustomerJwtRequestFilter customerJwtRequestFilter;
     
    
    @Bean
    public CustomerAccountService myCustomerAccountService() {
        return new CustomerAccountService();
    }
    
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    /*
     * @Bean public UserDetailsService myCustomerDetailsService() { return
     * myCustomerDetailsService(); }
     */
    
    
     @Bean
        public DaoAuthenticationProvider daoAuthenticationProvider(PasswordEncoder passwordEncoder,
                                                                   UserDetailsService userDetailsService){ 
            DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
            daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
            daoAuthenticationProvider.setUserDetailsService(userDetailsService);
            return daoAuthenticationProvider;
      }
     
     
     @Override
     @Bean
     public AuthenticationManager authenticationManagerBean() throws Exception {
         return super.authenticationManagerBean();
     }

     
     protected void configure(AuthenticationManagerBuilder auth ) throws Exception {
         auth.userDetailsService(myCustomerDetailsService).passwordEncoder(passwordEncoder());
         }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http.cors().and().csrf().disable()
      .authorizeRequests()
      .antMatchers("/***").permitAll()
    
     // .antMatchers("/customer/**").hasAuthority("CUSTOMER")
      .anyRequest().authenticated()
      .and()
      .exceptionHandling()
      .authenticationEntryPoint(customerJwtAuthenticationEntryPoint)
      
      .and()
      .formLogin().permitAll()
    //  .loginPage("/login")
     
      .and()
      .logout().logoutUrl("/logout").logoutSuccessUrl("/login")
     
      .and()
      .sessionManagement()
      .maximumSessions(1)
      .and()
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
      http.addFilterBefore(customerJwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
          
    
}

服务类别

@Primary
public class CustomerAccountService implements UserDetailsService {
    
    
    @Autowired  
    private CustomerAccountRepo custRepo;
    
    @Qualifier("passwordEncoder")
    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;
    
    
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Customer customer = custRepo.findByUserName(username);
        if(customer == null) {
            throw new UsernameNotFoundException("Customer not found");
        }
        
      return MyCustomerDetails.build(customer);
        
      }
    

这是基类


@Configuration
@EnableWebMvc
//@ComponentScan(basePackages = "com.bethsaida.org.security")
@EnableJpaRepositories
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class BethsaidaApplication  {
    
     public static void main(String[] args) 
      {SpringApplication.run(BethsaidaApplication.class, args);}
 
     public class WebConfig implements WebMvcConfigurer 
        { 
         private static final long MAX_AGE_SECS = 3600;

        @Override
        public void addCorsMappings(CorsRegistry registry) 
         { registry.addMapping("/**")
             .allowedOrigins("*")
             .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
             .maxAge(MAX_AGE_SECS);}
        }
     
    }



共有1个答案

仉明知
2023-03-14

你可以用这个

   @Override
   public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("*")
        .allowedMethods("POST", "PUT", "DELETE")
        .allowedHeaders("header1", "header2")
        .exposedHeaders("header1", "header2")
        .allowCredentials(false).maxAge(3600);
   }

直接在您的CustomSecurityConfiguration类中。因为WebMvcConfigrer是由WebMvcConfigrerAdapter实现的,所以您可以在CustomSecurityConfiguration类中定义此方法。

有关更多信息,请参阅此处

 类似资料:
  • 我的代码:GoogleCredential凭据 credential.refreshToken() 错误日志: 创建服务号的步骤: 我在凭据中的oauth 2.0中创建了一个Web应用程序 然后我用客户端ID创建了一个服务号 现在我正在使用这个服务号和从它生成的p12证书来验证和创建Google凭据的对象 一旦刷新令牌,我就给了我401例外。 在这种情况下,任何帮助都会受到感激

  • 问题内容: 我正在使用GCM服务从服务器推送信息。如果我使用浏览器密钥,它将成功消息显示为: {“ multicast_id”:4849013215736515938,“ success”:1,“ failure”:0,“ canonical_ids”:0,“ results”:[{“ message_id”:“ 0: 1348742583011905%2adac3a0f9fd7ecd“}]},

  • 我使用spring ide在本地机器嵌入式apache服务器上部署了spring boot web应用程序,并访问了一个带有错误令牌的url,在这种情况下,它会返回未经授权的访问错误401和托管异常处理抛出的特定错误消息,而如果我在独立但相同的apache服务器上部署相同的应用程序,它会给我500个内部服务器错误而不是401或任何其他服务器端错误。 我捕获的日志只有以下一行不同: 下面是我用来处理

  • Microsoft.Graph REST.API 我试图通过https://graph.microsoft.com/v1.0/me从graph.api获得有关我的信息 我也在这里检查这个其他主题,但我找不到像我一样的错误

  • 我试图从当前上下文中的所有项目中找到一个项目,但我似乎总是收到以下错误消息: 请求失败。远程服务器返回错误:(401)未授权。 首先,我设置了访问交换服务的所有内容: 然后我定义要接收的项目(按ID): 最后但同样重要的是,我尝试在我的物品中搜索这个物品: 这就是我的错误发生的地方。我尝试过各种其他的方法,但无论我做什么,我都会被授权。 有人可以以正确的方式指导我,以解决这个问题吗? 编辑 我收到

  • 我试图测试Firebase Cloud messaging APIs,因为控制台没有提供所有功能(特别是当应用程序在后台时定制通知)。但由于某些原因,我无法让它工作,它总是显示401错误。我调查了出现这种情况的原因,并在重新生成新的服务器密钥后进行了尝试,但错误仍然存在。令人惊讶的是,当我生成一个新的服务器密钥时,它没有反映在Firebase控制台中,它将服务器密钥显示为空。此外,我尝试添加我的I