spring cloud oauth2资源服务器自定义认证失败和拒绝访问错误消息

JAVA CONFIG

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
...
	@Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(this.resource.getResourceId());
        // 当拒绝访问时返回消息
        resources.accessDeniedHandler((request, response, e) -> {
            RpcPayload result = new RpcPayload();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            result.setException(e.getClass().toString());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter()
                    .write(objectMapper.writeValueAsString(result));
        });
        // 当认证失败时返回消息
        resources.authenticationEntryPoint((request, response, e) -> {
            RpcPayload result = new RpcPayload();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            result.setException(e.getClass().toString());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter()
                    .write(objectMapper.writeValueAsString(result));
        });
    }
...
}

posted on 2022-04-11 22:39  路过君  阅读(374)  评论(0编辑  收藏  举报

导航