获取错误的异常响应(403)

u0sqgete  于 2021-07-22  发布在  Java
关注(0)|答案(2)|浏览(224)

我有一个登录控制器,如果凭据是坏的,它应该返回badcredentialsexception,并以json格式显示消息,但是我得到的不是403响应。
我的代码:
控制器-

@PostMapping("/login")
public ResponseEntity<AuthenticationResponse> login(@Valid @RequestBody AuthenticationRequest data) {
    try {

        System.out.println(data);
        String email = data.getEmail();
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(email, data.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenProvider.createToken(email);
        AuthenticationResponse response = new AuthenticationResponse(email, token);
        return ok(response);
    } catch (AuthenticationException ex) {
        throw new BadCredentialsException(messageSource.getMessage("authController.invalidCredentials", null, null));
    }
}

证券配置-

http
                .httpBasic().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/**")
                .permitAll()
                .and()
                .apply(new JwtConfigurer(jwtTokenProvider))
                .and()
                .cors().and().csrf()
                .disable();

令牌创建-

public String createToken(String username) {
        Claims claims = Jwts.claims().setSubject(username);

        Date now = new Date();
        Date validity = new Date(now.getTime() + validityInMilliseconds);

        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now)
                .setExpiration(validity)
                .signWith(HS256, secretKey)
                .compact();
    }

我现在得到的是-

{
        "timestamp": "2021-03-14T23:34:49.038+00:00",
        "status": 403,
        "error": "Forbidden",
        "message": "",
        "path": "/auth/login/"
    }

目标是在json中获得消息,即凭证有问题。非常感谢您的帮助:)

jjjwad0x

jjjwad0x1#

因为默认的身份验证入口点是 org.springframework.security.web.authentication.Http403ForbiddenEntryPoint 您可以这样覆盖默认身份验证入口点:

public static class Message {
    private String message;

    public Message(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

private static final ObjectMapper objectMapper = new ObjectMapper();

@Override
protected void configure(HttpSecurity http) throws Exception {
    // set your authentication entry point
    http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // you could replace your custom HTTP status
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        out.print(objectMapper.writeValueAsString(new Message(authException.getMessage())));
        out.flush();
    });

    http
            .httpBasic().disable()
            .csrf().disable()

            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/**")
            .permitAll()
            .and()
            .apply(new JwtConfigurer(jwtTokenProvider))
            .and()
            .cors().and().csrf()
            .disable();
}

您还可以检查异常类型:

if (authException instanceof BadCredentialsException) {
        // Do somthing
    }
r1wp621o

r1wp621o2#

试试这个:
证券配置

http
            .httpBasic().disable()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/auth/login")
            .permitAll()
            .and()
            .apply(new JwtConfigurer(jwtTokenProvider))
            .and()
            .cors().and().csrf()
            .disable()
            .anyRequest().authenticated()
            .and().apply(securityConfigurerAdapter());;

相关问题