简介:Spring Security 是一款安全管理软件,认证与授权是它作为安全框架的核心功能
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
登录验证的流程:
由前端接待用户名密码访问接口,进行对数据库中的用户名和密码进行校验,如果正确会生成一个携带用户名和密码的jwt ,将jwt响应给前端, 登录后访问其他请求需要在请求头中携带token,根据token携带的信息进行解析,获取userid ,根据userid 进行权限判定,最后响应信息。
使用RBAC权限模型:(基于角色的权限控制)
代码实现:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//关闭csrf
.csrf().disable()
//不通过Session获取SecurityContext
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
// 对于登录接口 允许匿名访问
.antMatchers("/user/login").anonymous()
.antMatchers("/testCors").hasAuthority("system:dept:list222")
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
//添加过滤器
http.addFilterBefore(jwtAuthenticationTokenFilter,
UsernamePasswordAuthenticationFilter.class);
//配置异常处理器
http.exceptionHandling()
//配置认证失败处理器
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler);
//允许跨域
http.cors();
}