springsecurity配置步骤

28 篇文章 0 订阅
20 篇文章 0 订阅
//第1步:解决跨域问题。cors 预检请求放行,让Spring security 放行所有preflight request(cors 预检请求)
http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();

//第2步:让Security永远不会创建HttpSession,它不会使用HttpSession来获取SecurityContext
http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().headers().cacheControl();

//第3步:请求权限配置
//放行注册API请求,其它任何请求都必须经过身份验证.
http.authorizeRequests()
        //在web下的API,无需登录即可访问
        .antMatchers("/web/**").permitAll()
        //ROLE_ADMIN可以操作任何事情
        //.antMatchers("/**").hasRole("ADMIN")
        //同等上一行代码
        //.antMatchers("/**").hasAuthority("ROLE_ADMIN")
        /*
         由于使用动态资源配置,以上代码在数据库中配置如下:
         在sys_backend_api_table中添加一条记录
         backend_api_id=1,
         backend_api_name = 所有API,
         backend_api_url=/**,
         backend_api_method=GET,POST,PUT,DELETE
         */

        //动态加载资源
        .anyRequest().access("@dynamicPermission.checkPermisstion(request,authentication)");


//第4步:拦截账号、密码。覆盖 UsernamePasswordAuthenticationFilter过滤器
http.addFilterAt(myUsernamePasswordAuthenticationFilter() , UsernamePasswordAuthenticationFilter.class);

//第5步:拦截token,并检测。在 UsernamePasswordAuthenticationFilter 之前添加 JwtAuthenticationTokenFilter
http.addFilterBefore(myOncePerRequestFilter, UsernamePasswordAuthenticationFilter.class);

//第6步:处理异常情况:认证失败和权限不足
http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint).accessDeniedHandler(myAccessDeniedHandler);

//第7步:登录,因为使用前端发送JSON方式进行登录,所以登录模式不设置也是可以的。
http.formLogin();

//第8步:退出
http.logout().addLogoutHandler(myLogoutHandler).logoutSuccessHandler(myLogoutSuccessHandler);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值