SpringSecurity基础-认证授权结果处理

简介: 在传统的应用中,认证成功后页面需要跳转到认证成功页面或者跳转到个人中心页,但是在前后端分离的项目通常是使用Ajax请求完成认证,这时候我们需要返回一个JSON结果告知前端认证结果,然后前端自行跳转页面。要做到上述功能,我们需要自定义认证成功处理器实现AuthenticationSuccessHandler接口复写 onAuthenticationSuccess方法,该方法其中一个参数是Authentication ,他里面封装了认证信息,用户信息UserDetails等,我们需要在这个方法中使用Response写出json数据即可

1.认证结果处理

1.1.认证成功处理

在传统的应用中,认证成功后页面需要跳转到认证成功页面或者跳转到个人中心页,但是在前后端分离的项目通常是使用Ajax请求完成认证,这时候我们需要返回一个JSON结果告知前端认证结果,然后前端自行跳转页面。

要做到上述功能,我们需要自定义认证成功处理器实现AuthenticationSuccessHandler接口复写 onAuthenticationSuccess方法,该方法其中一个参数是Authentication ,他里面封装了认证信息,用户信息UserDetails等,我们需要在这个方法中使用Response写出json数据即可

1.导入JSON依赖

<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.50</version></dependency>

2.定义AuthenticationSuccessHandler

定义类实现AuthenticationSuccessHandler接口复写onAuthenticationSuccess方法,实现自己的认证成功结果处理

publicclassMyAuthenticationSuccessHandlerimplementsAuthenticationSuccessHandler {
@OverridepublicvoidonAuthenticationSuccess(HttpServletRequestrequest, HttpServletResponseresponse, Authenticationauthentication) 
throwsIOException, ServletException {
response.setContentType("application/json;charset=utf-8");
Mapmap=newHashMap<>();
map.put("success",true);
map.put("message","认证成功");
map.put("data",authentication);
response.getWriter().print(JSON.toJSONString(map));
response.getWriter().flush();
response.getWriter().close();
    }
}

3.配置AuthenticationSuccessHandler

在SpringSecurity配置定义的AuthenticationSuccessHandler

http.formLogin()
//.successForwardUrl("/loginSuccess") // 设置登陆成功页.successHandler(newMyAuthenticationSuccessHandler)
...

1.2.认证失败结果处理

自定义登录失败的处理,需要实现AuthenticationFailureHandler接口,复写onAuthenticationFailure方法实现自己的认证失败结果处理

1.定义认证失败处理器

publicclassMyAuthenticationFailureHandlerimplementsAuthenticationFailureHandler {
@OverridepublicvoidonAuthenticationFailure(HttpServletRequestrequest, HttpServletResponseresponse, AuthenticationExceptionexception) throwsIOException, ServletException {
response.setContentType("application/json;charset=utf-8");
Mapmap=newHashMap<>();
map.put("success",false);
map.put("message","认证失败");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().print(JSON.toJSONString(map));
response.getWriter().flush();
response.getWriter().close();
    }
}

2.配置处理器

http.formLogin()
.failureHandler(newMyAuthenticationFailureHandler)
...

2.授权结果处理

1.授权失败处理

当用户请求资源服务的资源时,需要进行用户的认证和授权检查,当认证或授权检查失败,我们需要要返回自己的失败结果信息,可以通过HttpSecurity设置授权失败结果处理器,内部通过 ExceptionTranslationFilter 调用AuthenticationEntryPoint实现匿名用户授权失败结果处理, ExceptionTranslationFilter 通过 AccessDeniedHandler来处理授权失败结果处理。

1.定义认证检查失败处理

定义AccessDeineHandler 用来解决认证过的用户访问无权限资源时的异常

publicclassDefaultAccessDeniedHandlerimplementsAccessDeniedHandler {
@Overridepublicvoidhandle(HttpServletRequestrequest, HttpServletResponseresponse, AccessDeniedExceptionaccessDeniedException) throwsIOException, ServletException {
Stringresult=JSON.toJSONString(AjaxResult.me().setSuccess(false).setMessage("无访问权限"));
response.setContentType("text/html;charset=utf-8");
PrintWriterwriter=response.getWriter();
writer.print(result);
writer.flush();
writer.close();
    }
}

2.定义AuthenticationEntryPoint

AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常

publicclassMyAuthenticationEntryPointimplementsAuthenticationEntryPoint {
@Overridepublicvoidcommence(HttpServletRequesthttpServletRequest, HttpServletResponsehttpServletResponse, AuthenticationExceptione) throwsIOException, ServletException {
e.printStackTrace();
httpServletResponse.setContentType("application/json;charset=utf-8");
Map<String,Object>result=newHashMap<>();
result.put("success",false);
result.put("message","登录失败,用户名或密码错误["+e.getMessage()+"]");
httpServletResponse.getWriter().print(JSONUtils.toJSONString(result));
    }
}

3.配置异常处理器

配置异常处理器

httpSecurity.exceptionHandling()
 .accessDeniedHandler(newDefaultAccessDeniedHandler ())
.authenticationEntryPoint(newMyAuthenticationEntryPoint()) //身份认证验证失败配置
Heron
+关注
目录
打赏
0
0
0
0
14
分享
相关文章
|
11月前
|
shiro认证和授权
shiro认证和授权
76 3
08 Shrio 授权的三种方式
08 Shrio 授权的三种方式
55 1
11 Shrio 授权流程
11 Shrio 授权流程
51 0
SpringSecurity基础-认证和授权概述
RBAC是基于角色的访问控制(Role-Based Access Control )在 RBAC 中,权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限。这就极大地简化了权限的管理。这样管理都是层级相互依赖的,权限赋予给角色,而把角色又赋予用户,这样的权限设计很清楚,管理起来很方便。
144 0
SpringSecurity基础-授权流程
授权一定是在认证通过之后,授权流程是通过FilterSecurityInterceptor拦截器来完成,FilterSecurityInterceptor通过调用SecurityMetadataSource来获取当前访问的资源所需要的权限,然后通过调用AccessDecisionManager投票决定当前用户是否有权限访问当前资源。授权流程如下
195 0
快速理解 IdentityServer4 中的认证 & 授权
在实际的生产环境中,存在各种各样的应用程序相互访问,当用户访问 `app` 应用的时候,为了安全性考虑,通常都会要求搭配授权码或者安全令牌服务一并访问,这样可有效地对 `Server` 端的 `API` 资源起到一定程度的有效保护...
598 0
快速理解 IdentityServer4 中的认证 & 授权
SpringSecurity认证和授权
目前,我们的测试环境,是谁都可以访问的,我们使用 Spring Security 增加上认证和授权的功能
SpringSecurity认证和授权
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等