spring oauth2自定义登录错误

luc*_*ard 2 java spring spring-security spring-boot spring-security-oauth2

登录失败时我有定义自定义错误消息的问题,所以现在当我的登录失败时,我得到带有效负载的http 400:

{"error":"invalid_grant","error_description":"Bad credentials"}
Run Code Online (Sandbox Code Playgroud)

如何自定义此消息,并返回自己的json?

我使用的是spring boot(1.3.2.RELEASE)和spring security OAuth2(2.0.8.RELEASE).

Ali*_*ani 7

首先,创建一个扩展的新异常Oauth2Exception.例如,我们有CustomOauthException以下内容:

@JsonSerialize(using = CustomOauthExceptionSerializer.class)
public class CustomOauthException extends OAuth2Exception {
    public CustomOauthException(String msg) {
        super(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

这里我们将CustomOauthExceptionSerializer用于序列化为CustomOauthExceptionJSON字符串:

public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException> {
    public CustomOauthExceptionSerializer() {
        super(CustomOauthException.class);
    }

    @Override
    public void serialize(CustomOauthException value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("custom_error", value.getOAuth2ErrorCode());
        gen.writeStringField("custom_error_description", value.getMessage());
        if (value.getAdditionalInformation()!=null) {
            for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String add = entry.getValue();
                gen.writeStringField(key, add);
            }
        }
        gen.writeEndObject();
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,我们需要WebResponseExceptionTranslator在我们的注册表中将AuthorizationServerConfigurerAdapter春季安全性转换Oauth2Exception为我们CustomOauthException的.我们到了:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                // other endpoints
                .exceptionTranslator(e -> {
                    if (e instanceof OAuth2Exception) {
                        OAuth2Exception oAuth2Exception = (OAuth2Exception) e;

                        return ResponseEntity
                                .status(oAuth2Exception.getHttpErrorCode())
                                .body(new CustomOauthException(oAuth2Exception.getMessage()));
                    } else {
                        throw e;
                    }
                });
    }

    // rest of the authorization server config
}
Run Code Online (Sandbox Code Playgroud)

完成所有这些后,您将看到自定义的JSON响应:

{"custom_error":"invalid_grant", "custom_error_description":"Bad credentials"}
Run Code Online (Sandbox Code Playgroud)