首页 > 解决方案 > Spring Boot 登录 401 未经授权的邮递员

问题描述

在我的 Spring Boot 应用程序中,我有一个用于登录的端点和一个用于注册的端点。注册一切正常时,新用户已正确创建。
然后,如果我尝试使用刚刚创建的凭据登录,Postman 会返回 401 Unauthorized 错误。这些是我的控制器方法(先登录然后注册):

@PostMapping(PathConstants.LOGIN_ACTION)
    @ApiOperation("Login into Helios administrational console.")
    @Override
    public ResponseEntity<?> autenticate(@Valid @RequestBody LoginRequest request) {
        System.out.println("Login");
        System.out.println("Us psw " + request.getUsername() + "   " + request.getPassword());
        Authentication auth = authManager
                .authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
        System.out.println("Auth " + auth.toString());
        SecurityContextHolder.getContext().setAuthentication(auth);
        String token = jwtProvider.generateToken(auth);
        System.out.println("TOken " + token);
        return ResponseEntity.ok(new JwtAuthResponse(token));
    }



    @PostMapping(PathConstants.SIGNUP_ACTION)
    @ApiOperation("Signup to Helios administrational console.")
    @Override
    public ResponseEntity<?> register(@Valid @RequestBody SignUpRequest request) {
        sysdataUserService.createNewSysdataUser(request);
        return ResponseEntity.ok().body(new DashboardResponse(true, "New sysdata user registered successfully."));
    }

我使用正确的数据进入控制台“登录”和“Us psw”,但之后

Authentication auth = authManager
                .authenticate(...)

什么都没有打印。我在想方法有问题authenticate,但可能是什么问题?我该如何解决?这些是我的安全配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, PathConstants.USER_AUTH +"/**", PathConstants.HELIOS+"/dashboard/**").permitAll()
                .antMatchers(HttpMethod.GET, "/"+PathConstants.PROCESS_DEFINITION+"/**").permitAll()
                .antMatchers(HttpMethod.POST, "/"+PathConstants.PROCESS_DEFINITION+"/**").permitAll()
                .antMatchers(HttpMethod.GET, "/"+PathConstants.PROCESS_INSTANCE+"/**").permitAll()
                .antMatchers(HttpMethod.POST,  PathConstants.LOGIN_ACTION).permitAll()
                //.anyRequest().authenticated()
                .anyRequest().permitAll()
                .and()
                .exceptionHandling().authenticationEntryPoint(jwtAuthEntryPoint).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // custom jwt filter.
        http.addFilterBefore(jwtAuthFilter(), UsernamePasswordAuthenticationFilter.class);
    }

我已经添加 .antMatchers(HttpMethod.POST, PathConstants.LOGIN_ACTION).permitAll()尝试这种方式是否有效,但我仍然有 401。然后我有这些用于 Cors 策略的 WebMvcConfigurations:

@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("*")
                .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
                .allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
                        "Access-Control-Request-Headers")
                .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials").maxAge(MAX_AGE);
                //.allowCredentials(true).maxAge(MAX_AGE);
    }

怎么了?
所有其他端点都可以正常工作,但不能登录。

标签: spring-bootauthenticationjwthttp-status-code-401

解决方案


推荐阅读