2. 接口访问的认证及鉴权

2020-10-01  本文已影响0人  coderymy

配置用户登录---认证

在configure中配置.loginProcessingUrl("/xxx/login")
当请求这个接口的时候就会默认进入认证程序,需要满足认证要求才可以成功认证,还需要在后面配置.permitAll()让login请求不需要任何权限

配置api接口访问权限---鉴权

/**
 * @description:
 * @author: coderymy
 * @create: 2020-10-01 13:54
 * <p>
 * 1. 创建WebSecurityConfig 类继承WebSecurityConfigurerAdapter
 * 2. 类上加上@EnableWebSecurity,注解中包括@Configuration注解
 * <p>
 * WebSecurityConfigurerAdapter声明了一些默认的安全特性
 * (1)验证所有的请求
 * (2)可以使用springSecurity默认的表单页面进行验证登录
 * (3)允许用户使用http请求进行验证
 */

/**
 * 如何自定义认证
 * 1. 实现并重写configure(HttpSecurity http)方法,鉴权,也就是判断该用户是否有访问该api的权限
 * <p>
 * <p>
 * 页面显示403错误,表示该用户授权失败(401代表该用户认证失败)前端可以使用返回的状态码来标识如何给用户展示
 * 用2XX表示本次操作成功,用4XX表示是客户端导致的失败,用5XX表示是服务器引起的错误
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //鉴权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 1. HttpSecurity被声明为链式调用
         * 其中配置方法包括
         *  1. authorizeRequests()url拦截配置
         *  2. formLogin()表单验证(.loginPage("")可以配置登录页面,但是对于前后端分离,其实没用)
         *  3. httpBasic()表单验证
         *  4. csrf()提供的跨站请求伪造防护功能
         */
        /**
         * 2. authorizeRequests目的是指定url进行拦截的,也就是默认这个url是“/”也就是所有的
         * anyanyRequest()、antMatchers()和regexMatchers()三种方法来拼配系统的url。并指定安全策略
         */
        http.authorizeRequests()
                //这里指定什么样的接口地址的请求,需要什么样的权限 ANT模式的URL匹配器
                .antMatchers("/select/**").hasRole("USER")//用户可以有查询权限
                .antMatchers("/insert/**").hasRole("ADMIN")//管理员可以有插入权限权限
                .antMatchers("/empower/**").hasRole("SUPERADMIN")//超级管理员才有赋权的权限
                .antMatchers("/login/**").permitAll()//标识list所有权限都可以直接访问,即使不登录也可以访问。一般将login页面放给这个权限
                .and()
                .formLogin();


        //指定表单的自定义登录页
        http.formLogin().loginPage("/xxx/xxx/xxx");
        http.httpBasic();

        super.configure(http);
    }
}
  1. 继承WebSecurityConfigurerAdapter
  2. 重写configure方法
  3. 配置参数HttpSecurity使用链式的方式来配置什么样的api需要什么样的权限才能访问
上一篇 下一篇

猜你喜欢

热点阅读