使用Spring Boot Security做Restful api后端接口登录验证包含Cookies记住用户名密码

前言

使用spring security做后端接口验证需要注意的是很多接口需要自己重新,然后定义不同的错误码返回给前端,包含登录验证、登录失效、没有权限、登出等错误提示,均为JSON格式,其中记住我需要重写TokenBasedRememberMeServices,来避免key不一致造成解密失败。

##开始
1 .使用maven 引用spring security 等相关jar包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>

2 .在配置文件中编写如下代码,其中csrf表示提交方式,禁用后logout用get即可访问

http
.addFilterAt(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint)
.and().authenticationProvider(restAuthenticationProvider)
.authorizeRequests()
.antMatchers(securityIgnoreUrls.toArray(ignores)).permitAll()
.antMatchers("/api/admin/**").hasRole(RoleEnum.ADMIN.getName())
.antMatchers("/api/student/**").hasRole(RoleEnum.STUDENT.getName())
.antMatchers("/api/teacher/**").hasRole(RoleEnum.TEACHER.getName())
.anyRequest().permitAll()
.and().exceptionHandling().accessDeniedHandler(restAccessDeniedHandler)
.and().formLogin().successHandler(restAuthenticationSuccessHandler).failureHandler(restAuthenticationFailureHandler)
.and().logout().logoutUrl("/api/user/logout").logoutSuccessHandler(restLogoutSuccessHandler).invalidateHttpSession(true)
.and().rememberMe().key(CookieConfig.getName()).tokenValiditySeconds(CookieConfig.getInterval()).userDetailsService(formDetailsService)
.and().csrf().disable()
.cors();

3 .然后有很多类需要我们继承,来完成restful api的验证

  • LoginUrlAuthenticationEntryPoint 用户未登录会跳到这里,返回JSON格式做未登录处理
  • RestAccessDeniedHandler 没有权限会跳到这里,返回自定义处理码的JSON格式
  • RestAuthenticationFailureHandler 用户名密码验证错误会跳到这里
  • RestAuthenticationProvider 验证用户名密码是否正确的地方
  • RestAuthenticationSuccessHandler 用户登录成功会跳到这里,返回正确登录消息
  • RestDetailsServiceImpl 用户第二次访问会跳到这里,根据用户名获取用户信息
  • RestLoginAuthenticationFilter 获取登录传过来的参数,反序列传过来的json格式。
  • RestLogoutSuccessHandler 用户退出接口
  • RestTokenBasedRememberMeServices 记住我,可以设置cookie的时间

4 .具体代码截图
在这里插入图片描述
5.代码地址:https://gitee.com/mindskip/uexam/tree/master/source/xzs/src/main/java/com/mindskip/xzs/configuration/spring/security

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值