得到错误的异常响应 (403) [英] Getting wrong exception response (403)

查看:34
本文介绍了得到错误的异常响应 (403)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个登录控制器,如果凭据不好,它应该返回 BadCredentialsException 和 json 中的消息,但我得到的是 403 响应.

I have a login controller, which if credentials are bad - should return BadCredentialsException with the message in json, but in stead of this I get 403 response.

我的代码:

控制器 -

@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();
    }

我得到的当前 Json 是 -

Current Json I get is -

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

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

The goal is to get the message in the json, that something is bad with the credentials. Thanks a lot for any help :)

推荐答案

因为默认的 Authentication 入口点是 org.springframework.security.web.authentication.Http403ForbiddenEntryPoint

Because of the default Authentication entry point is org.springframework.security.web.authentication.Http403ForbiddenEntryPoint

您可以像这样覆盖默认的身份验证入口点:

You could override the default authentication entry point like this:

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();
}

您还可以检查异常类型:

You also can check the exception type:

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

这篇关于得到错误的异常响应 (403)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆