从Spring Security自定义auth错误 [英] Customize auth error from Spring Security

查看:346
本文介绍了从Spring Security自定义auth错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否可以自定义以下授权错误:

I was wondering if I could customize the following authorization error:

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

我在用户请求没有权限时得到它。我想将它定制为与Spring Boot错误非常相似:

I get it when the user request does not have permissions. And I would like to customize it to be quite similar than Spring Boot error:

{
 "timestamp":1445441285803,
 "status":401,
 "error":"Unauthorized",
 "message":"Bad credentials",
 "path":"/oauth/token"
}

可能吗?

非常感谢。

推荐答案

我明白了:)

https://stackoverflow.com/a/37132751/2520689

我需要创建一个实现AuthenticationEntryPoint的新类,如下所示:

I need to create a new class which implements "AuthenticationEntryPoint" as the following:

public class AuthExceptionEntryPoint implements AuthenticationEntryPoint
{
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException, ServletException
    {
        final Map<String, Object> mapBodyException = new HashMap<>() ;

        mapBodyException.put("error"    , "Error from AuthenticationEntryPoint") ;
        mapBodyException.put("message"  , "Message from AuthenticationEntryPoint") ;
        mapBodyException.put("exception", "My stack trace exception") ;
        mapBodyException.put("path"     , request.getServletPath()) ;
        mapBodyException.put("timestamp", (new Date()).getTime()) ;

        response.setContentType("application/json") ;
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED) ;

        final ObjectMapper mapper = new ObjectMapper() ;
        mapper.writeValue(response.getOutputStream(), mapBodyException) ;
    }
}

并将其添加到我的ResourceServerConfigurerAdapter实现中:

And add it to my ResourceServerConfigurerAdapter implementation:

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
{   
    @Override
    public void configure(HttpSecurity http) throws Exception
    {
        http.exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint()) ;

    }
}

你可以找到我的GitHub项目实现您需要的一切:

You can find my GitHub project which implements everything you need:

https: //github.com/pakkk/custom-spring-security

这篇关于从Spring Security自定义auth错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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