栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用AuthenticationFailureHandler在Spring Security中自定义身份验证失败响应

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用AuthenticationFailureHandler在Spring Security中自定义身份验证失败响应

你可以通过在configure方法中的HttpSecurity对象上调用.exceptionHandling()来为Spring Security添加异常处理。如果只想处理错误的凭据,则可以忽略.accessDeniedHandler(accessDeniedHandler())。

拒绝访问处理程序可处理你已在方法级别保护应用程序安全的情况,例如使用@ PreAuthorized,@ PostAuthorized和@Secured。

你的安全性配置示例可能像这样

SecurityConfig.java@Autowiredprivate CustomAuthenticationEntryPoint unauthorizedHandler;@Autowiredprivate CustomAccessDeniedHandler accessDeniedHandler;    @Overrideprotected void configure(HttpSecurity http) throws Exception {    http.csrf()        .disable()        .exceptionHandling() .authencationEntryPoint(unauthorizedHandler)  // handles bad credentials .accessDeniedHandler(accessDeniedHandler);    // You're using the autowired members above.    http.formLogin().failureHandler(authenticationFailureHandler);}@Beanpublic Jackson2JsonObjectMapper jackson2JsonObjectMapper() {ObjectMapper mapper = new ObjectMapper();    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);    return new Jackson2JsonObjectMapper(mapper);}  

CustomAuthenticationEntryPoint.java

你可以在其自己的单独文件中创建它。这是入口点处理的无效凭据。在方法内部,我们必须创建自己的JSON并将其写入HttpServletResponse对象。我们将使用在Security Config中创建的Jackson对象映射器bean。

 @Componentpublic class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {    private static final long serialVersionUID = -8970718410437077606L;    @Autowired  // the Jackson object mapper bean we created in the config    private Jackson2JsonObjectMapper jackson2JsonObjectMapper;    @Override    public void commence(HttpServletRequest request,   HttpServletResponse response,   AuthenticationException e) throws IOException {                 CustomError error = new CustomError(HttpStatus.FORBIDDEN, error, description);                try { String json = jackson2JsonObjectMapper.toJson(error); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); response.getWriter().write(json);        } catch (Exception e1) { e1.printStackTrace();        }    }}

CustomAccessDeniedHandler.java

这将处理授权错误,例如尝试在没有适当特权的情况下访问方法。你可以以与上面相同的方式来实现它,但凭据不良。

@Componentpublic class CustomAccessDeniedHandler implements AccessDeniedHandler {    @Override    public void handle(HttpServletRequest request, HttpServletResponse response,        AccessDeniedException e) throws IOException, ServletException {    // You can create your own repsonse here to handle method level access denied reponses..    // Follow similar method to the bad credentials handler above.    }}

希望这会有所帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/404954.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号