原来
输入错误密码登录,出现 Spring Security Oauth2 封装的响应消息格式
这显然 不是我希望的,我希望能按照 我定义的格式来响应给前端。
{
"error": "invalid_grant",
"error_description": "Bad credentials"
}
改造
自定义响应异常转换,判断是登录异常 返回我定义的数据格式,
package com.invespec.auth.config;
import com.invespec.auth.utils.Responsei18nUtil;
import com.invespec.common.constant.ResponseCode;
import com.invespec.common.model.dto.R;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;
/**
* @Classname CustomWebResponseExceptionTranslator
* @Description 自定义响应异常转换
* @Date 2019/8/15 0015 10:47
* @Created by Administrator
*/
@Component
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
@Override
public ResponseEntity translate(Exception e) throws Exception {
if (e instanceof OAuth2Exception) {
return ResponseEntity.ok(new R(ResponseCode.INCORRECT_USER_PASSWORD.getCode(),Responsei18nUtil.getMessage(ResponseCode.INCORRECT_USER_PASSWORD.getCode())));
}
if (e instanceof InternalAuthenticationServiceException) {
//获取锁定时间
String message = e.getMessage();
return ResponseEntity.ok(new R(ResponseCode.ACCOUNT_LOCKOUT.getCode(), Responsei18nUtil.getMessage(ResponseCode.ACCOUNT_LOCKOUT.getCode()).replace("#",message)));
}
throw e;
}
}
自定义转换类定义好了后 我们来看怎么使用
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
//token增强配置
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
//使用自定义的异常转换类
endpoints.exceptionTranslator(customWebResponseExceptionTranslator);
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(tokenEnhancer, jwtAccessTokenConverter));
endpoints
.tokenStore(jdbcTokenStore())
.tokenEnhancer(tokenEnhancerChain)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
.reuseRefreshTokens(false);
}
密码输入错误3次 触发,加强用户账号安全
评论区