




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
第SpringBoot访问安全之认证和鉴权详解目录拦截器认证鉴权在web应用中有大量场景需要对用户进行安全校,一般人的做法就是硬编码的方式直接埋到到业务代码中,但可曾想过这样做法会导致代码不够简洁(大量重复代码)、有个性化时难维护(每个业务逻辑访问控制策略都不相同甚至差异很大)、容易发生安全泄露(有些业务可能不需要当前登录信息,但被访问的数据可能是敏感数据由于遗忘而没有受到保护)。
为了更安全、更方便的进行访问安全控制,我们可以想到的就是使用springmvc的拦截器(HandlerInterceptor),但其实更推荐使用更为成熟的springsecurity来完成认证和鉴权。
拦截器
拦截器HandlerInterceptor确实可以帮我们完成登录拦截、或是权限校验、或是防重复提交等需求。其实基于它也可以实现基于url或方法级的安全控制。
如果你对springmvc的请求处理流程相对的了解,它的原理容易理解。
publicinterfaceHandlerInterceptor{
*Intercepttheexecutionofahandler.CalledafterHandlerMappingdetermined
*anappropriatehandlerobject,butbeforeHandlerAdapterinvokesthehandler.
*在业务处理器处理请求之前被调用。预处理,可以进行编码、安全控制、权限校验等处理
*handler:controller内的方法,可以通过HandlerMethodmethod=((HandlerMethod)handler);获取到@RequestMapping
booleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException;
*Intercepttheexecutionofahandler.CalledafterHandlerAdapteractually
*invokedthehandler,butbeforetheDispatcherServletrenderstheview.
*在业务处理器处理请求执行完成后,生成视图之前执行。后处理(调用了Service并返回ModelAndView,但未进行页面渲染),有机会修改ModelAndView
voidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)throwsException;
*Callbackaftercompletionofrequestprocessing,thatis,afterrendering
*theview.Willbecalledonanyoutcomeofhandlerexecution,thusallows
*forproperresourcecleanup.
*在DispatcherServlet完全处理完请求后被调用,可用于清理资源等。返回处理(已经渲染了页面)
voidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)throwsException;
//你可以基于有些url进行拦截
@Configuration
publicclassUserSecurityInterceptorextendsWebMvcConfigurerAdapter{
@Override
publicvoidaddInterceptors(InterceptorRegistryregistry){
String[]securityUrls=newString[]{"/**"};
String[]excludeUrls=newString[]{"/**/esb/**","/**/dictionary/**"};
registry.addInterceptor(userLoginInterceptor()).excludePathPatterns(excludeUrls).addPathPatterns(securityUrls);
super.addInterceptors(registry);
/**fixed:url中包含//报错
*org.springframework.security.web.firewall.RequestRejectedException:TherequestwasrejectedbecausetheURLwasnotnormalized.
*@return
@Bean
publicHttpFirewallallowUrlEncodedSlashHttpFirewall(){
DefaultHttpFirewallfirewall=newDefaultHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
returnfirewall;
@Bean
publicAuthInterceptoruserLoginInterceptor(){
returnnewAuthInterceptor();
publicclassAuthInterceptorimplementsHandlerInterceptor{
publicLoggerlogger=LoggerFactory.getLogger(AuthInterceptor.class);
@Autowired
privateApplicationContextapplicationContext;
publicAuthInterceptor(){
@Override
publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{
LoginUserInfouser=null;
try{
user=(LoginUserInfo)SSOUserUtils.getCurrentLoginUser();
}catch(Exceptione){
logger.error("从SSO登录信息中获取用户信息失败!详细错误信息:%s",e);
thrownewServletException("从SSO登录信息中获取用户信息失败!",e);
String[]profiles=applicationContext.getEnvironment().getActiveProfiles();
if(!Arrays.isNullOrEmpty(profiles)){
if("dev".equals(profiles[0])){
returntrue;
if(user==null||UserUtils.ANONYMOUS_ROLE_ID.equals(user.getRoleId())){
thrownewServletException("获取登录用户信息失败!");
returntrue;
@Override
publicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)throwsException{
@Override
publicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)throwsException{
}
认证
确认一个访问请求发起的时候背后的用户是谁,他的用户信息是怎样的。在springsecurity里面认证支持很多种方式,最简单的就是用户名密码,还有LDAP、OpenID、CAS等等。
而在我们的系统里面,用户信息需要通过kxtx-sso模块进行获取。通过sso认证比较简单,就是要确认用户是否通过会员系统登录,并把登录信息包装成授权对象放到SecurityContext中,通过一个filter来完成:
@Data
@EqualsAndHashCode(callSuper=false)
publicclassSsoAuthenticationextendsAbstractAuthenticationToken{
privatestaticfinallongserialVersionUID=-1799455508626725119L;
privateLoginUserInfouser;
publicSsoAuthentication(LoginUserInfouser){
super(null);
this.user=user;
@Override
publicObjectgetCredentials(){
return"kxsso";
@Override
publicObjectgetPrincipal(){
returnuser;
@Override
publicStringgetName(){
returnuser.getName();
publicclassSsoAuthenticationProcessingFilterextendsOncePerRequestFilter{
@Override
protectedvoiddoFilterInternal(HttpServletRequestrequest,HttpServletResponseresponse,FilterChainfilterChain)
throwsServletException,IOException{
LoginUserInfouser=(LoginUserInfo)SSOUserUtils.getCurrentLoginUser();
SsoAuthenticationauth=newSsoAuthentication(user);
SecurityContextHolder.getContext().setAuthentication(auth);
filterChain.doFilter(request,response);
@Component
publicclassSsoAuthenticationProviderimplementsAuthenticationProvider{
@Value("${env}")
Stringenv;
@Override
publicAuthenticationauthenticate(Authenticationauthentication)throwsAuthenticationException{
LoginUserInfologinUserInfo=(LoginUserInfo)authentication.getPrincipal();
*DEV环境允许匿名用户访问,方便调试,其他环境必须登录。
if(!UserUtils.ANONYMOUS_ROLE_ID.equals(loginUserInfo.getRoleId())||"dev".equals(env)){
authentication.setAuthenticated(true);
}else{
thrownewBadCredentialsException("请登录");
returnauthentication;
@Override
publicbooleansupports(Classauthentication){
returnSsoAuthentication.class.equals(authentication);
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled=true)
publicclassWebSecurityConfigextendsWebSecurityConfigurerAdapter{
protectedvoidconfigure(HttpSecurityhttp)throwsException{
//关闭session
http.sessionManagement().sessionCreationPolicy(Sessi
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 甘肃省会师中学2025届生物七下期末综合测试模拟试题含解析
- 2025届广东省中学山一中学七年级生物第二学期期末综合测试模拟试题含解析
- 2025届福建省泉州市泉州聚龙外国语学校八年级物理第二学期期末检测模拟试题含解析
- 全国教育大会内容解读
- 2025年浙江嘉兴市海宁市硖石城中村建设有限公司招聘笔试参考题库含答案解析
- 2025年浙江安吉县文旅集团文旅酒店管理有限公司招聘笔试参考题库含答案解析
- 2025年山东烟台市莱州市地方储备粮管理有限公司招聘笔试参考题库含答案解析
- 黑龙江高考英语复习重点单选题100道及答案
- 湖南省天壹名校联盟2023-2024学年高二下学期3月联考生物试题 无答案
- 四川省成都市成华区某校2023-2024学年高三上学期期中生物试题 无答案
- YB-4001.1-2007钢格栅板及配套件-第1部分:钢格栅板(中文版)
- 1999年版干部履历表A4
- 养殖场兽医诊断与用药制度范本
- 12-漏缆卡具安装技术交底
- 热烈祝贺华东六省一市第十五届小学数学课堂教学观摩研省名师优质课赛课获奖课件市赛课一等奖课件
- 物业管家的五层修炼物业金牌管家培训课件
- 业主共有资金管理制度
- 校园摄影作品说明范文(热门6篇)
- 房建装修修缮工程量清单
- 广东省珠海市电工等级低压电工作业
- 乳品行业-无菌包装机培训资料3
评论
0/150
提交评论