Oauth2 自定义异常信息返回(springboot无法全局捕获invalid_client,unauthorized,invalid_token)

在SpringBoot当中使用Oauth2的时候,发现部分Oauth2的异常无法被springboot的ControllerAdvance全局异常捕获!!!

特此记录下相关的处理方式:

invalid_client Bad client credentials

当使用password模式时,如果client_id 或者client_secret错误时,请求接口会返回以下格式的数据!!!

{
“error”: “invalid_client”,
“error_description”: “Bad client credentials”
}

在项目当中通常有自己的统一返回代码,需要返回统一的封装,方便前端接口的处理!!!

处理方式

1 首先创建异常信息的处理

/**
 * @author hjljy
 * Oauth2异常信息返回处理
 */
@Component
@Slf4j
public class CustomAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {
    
    

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
    
    
        log.error(e.getMessage());
        //如果是client_id和client_secret相关异常 返回自定义的数据格式
        if(e instanceof BadCredentialsException){
    
    
            response.setStatus(HttpStatus.OK.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            ResultInfo<Boolean> result = ResultInfo.error(ResultCode.INVALID_CLIENT);
            result.setData(false);
            response.getWriter().write(JacksonUtil.obj2String(result));
        }else {
    
    
            super.commence(request,response,e);
        }

    }
}

2 客户端配置自定义的异常信息处理

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
    
    
        CustomAuthenticationEntryPoint authenticationEntryPoint = new CustomAuthenticationEntryPoint();
        ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
        filter.setAuthenticationManager(authenticationManager);
        filter.setAuthenticationEntryPoint(authenticationEntryPoint);
        filter.afterPropertiesSet();
        security.addTokenEndpointAuthenticationFilter(filter);
        security
                // 允许表单登录 需要注释掉
//                .allowFormAuthenticationForClients()
                // 密码加密编码器
                .passwordEncoder(passwordEncoder)
                // 允许所有的checkToken请求
                .checkTokenAccess("permitAll()");
    }

unauthorized Full authentication is required to access this resource

当访问资源服务器,未携带token时,就会出现这个错误!如果携带了token,但是权限不足的话,可以全局异常切面可以通过拦截AccessDeniedException进行处理。

{
“error”: “unauthorized”,
“error_description”: “Full authentication is required to access this resource”
}

处理方式

1 首先创建异常信息的处理

/**
 * @author hjljy
 * Oauth2异常信息返回处理
 */
@Component
@Slf4j
public class CustomAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {
    
    

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
    
    
        log.error(e.getMessage());
        if(e instanceof BadCredentialsException){
    
    
            //如果是client_id和client_secret相关异常 返回自定义的数据格式
            response.setStatus(HttpStatus.OK.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            ResultInfo<Boolean> result = ResultInfo.error(ResultCode.INVALID_CLIENT);
            result.setData(false);
            response.getWriter().write(JacksonUtil.obj2String(result));
        }else if(e instanceof InsufficientAuthenticationException){
    
    
            //如果是没有携带token
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            ResultInfo<Boolean> result = ResultInfo.error(ResultCode.TOKEN_NOT_FOUND);
            result.setData(false);
            response.getWriter().write(JacksonUtil.obj2String(result));
        }else {
    
    
            super.commence(request,response,e);
        }

    }
}

2 在资源配置当中配置异常处理

@Configuration
@EnableResourceServer
public class Oauth2ResourceConfiguration extends ResourceServerConfigurerAdapter {
    
    

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    
    
        CustomAuthenticationEntryPoint customAuthenticationEntryPoint = new CustomAuthenticationEntryPoint();
        resources.authenticationEntryPoint(customAuthenticationEntryPoint);
    }
}

invalid_token Cannot convert access token to JSON

当携带的Token格式错误,或者token值不对,例如本应该是

Authorization: bearer token值  结果直接是Authorization: token值 就会报错,或者token的值错误

{
“error”: “invalid_token”,
“error_description”: “Cannot convert access token to JSON”
}

对应处理方式

如果已经配置了上面unauthorized Full authentication is required to access this resource这个异常的处理方式,会发现token值异常也会返回上面的异常信息,这是因为两个异常都是InsufficientAuthenticationException,只是提示不一样而已,所以简单的处理方式就是将上面的返回提示就改为:未携带TOKEN或无效TOKEN,返回给前端即可。

处理方式总结

总的来说,处理方式主要是定义一个自己的CustomAuthenticationEntryPoint,并将这个类注入到Oauth2服务段和客户端的配置里面,然后复写commence这个方法,将需要返回的数据格式封装到response里面即可。

猜你喜欢

转载自blog.csdn.net/ycf921244819/article/details/118488338