pom.xml 配置添加
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
目录结构
filter => 过滤器文件夹用来存放会话验证等一系列登录后的过滤逻辑
JwtAuthenticationTokenFilter => token 认证流程
handle => security 一系列认证过滤的处理结果类
JwtAccessDeniedHandler => 权限认证不通过抛出异常处理类
JwtAuthenticationEntryPoint => token认证不通过处理类
LoginFailureHandler => 登录失败处理类
MyAuthenticationSuccessHandler => 登录成功处理类
impl => 认证逻辑实现类
JwtUserDetailServiceImpl => UserDetailsService 的实现类,loadUserByUsernam方法的实现
jwt => jwt 插件业务逻辑
JwtUser => 对userdetail 类的拓展和重载
JwtProperties => jwt 配置获取
JwtTokenUtil => jwt api 封装类
各个类的代码在后面
Security 登录认证流程WebSecurityConfig 继承Security 的WebSecurityConfigurerAdapter
1.配置好密码加密方式 => WebSecurityConfig
2.配置自定义的userDetail类实现登录逻辑 =>JwtUserDetailServiceImpl
3.配置认证权限的限制
httpSecurity
.formLogin()
//自定义认证成功处理器
.successHandler(jwtAuthenticationSuccessHandler)
// 自定义失败拦截器
.failureHandler(loginFailureHandler)
// 自定义登录拦截URI
.loginProcessingUrl("/hello/login")
.and()
//token的验证方式不需要开启csrf的防护
.csrf().disable()
// 自定义认证失败类
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
// 自定义权限不足处理类
.accessDeniedHandler(jwtAccessDeniedHandler)
.and()
//设置无状态的连接,即不创建session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/hello/login").permitAll()
//配置允许匿名访问的路径
.anyRequest().authenticated();
// 解决跨域问题(重要) 只有在前端请求接口时才发现需要这个
httpSecurity.cors().and().csrf().disable();
//配置自己的jwt验证过滤器
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
// disable page caching
httpSecurity.headers().cacheControl();
//.antMatchers("/admin/**").hasRole("ADMIN");配置只有ADMIN 权限的用户才能访问该路由
认证流程(个人理解):
1.用户登录
2.调用security 配置的login 接口 默认参数 username、password
如需要修改默认传参字段可通过如下配置
.usernameParam