SpringSecurity使用方法

SpringSecurity

使用方法

  1. 创建SpringBoot项目

  2. 在pom文件中导入依赖

       		 <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
            </dependency>
    
  3. 创建一个简单Controller测试

    @RestController
    @RequestMapping("/test")
    public class TestController {
    
        @GetMapping("add")
        public String add(){
            return "hello Security";
        }
    }
    
  4. 运行之后
    在这里插入图片描述

默认用户名是user 密码是 控制台打印的


重要的两个接口

  1. UserDetailsService

    查询用户名和密码的过程在实现这个接口的方法里

  2. PasswordEncode

    用于密码加密,在返回user对象时将密码加密处理


在web应用中去配置权限

第一种方式:通过yml配置文件
spring:
  security:
    user:
      name: atguigu
      password: atguigu

直接在配置文件中设置用户名和密码

第二种方式:通过配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder passwordEncoder = passwordEncoder();
        String password = passwordEncoder.encode("123");
        auth.inMemoryAuthentication().withUser("lucy").password(password).roles("admin");
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

使用配置类继承WebSecurityConfigurerAdapter类实现config方法,在config方法中配置用户名和密码,这里的密码使用PasswordEncoder加密处理

第三种方式:自定义编写实现类
@Configuration
public class SecuityConfig1 extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

这里使用userDetailsService类来配置用户名的信息,这个类需要实现UserDetailsService接口

@Service("UserDetailsService")
public class MyUserDatailsService implements UserDetailsService {
    @Autowired
    private UsersMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<users> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<users> equals = lambdaQueryWrapper.eq(users::getUsername,username);
        users users = userMapper.selectOne(equals);
        if(users == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        System.out.println(users);
        List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");

        return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassworld()),admin);
    }
}

这里实现接口后重写loadUserByUsername方法。在这个方法里我们实现了查询数据库的方法,这个username就是security传过来的用户名。通过用户名来查询数据库封装成一个User对象返回给前端,这里默认的返回类型是Scurity中自带的UserDetails接口,因此我们返回的User类需要实现它。这个User类也是Security自带的类,它默认就实现了UserDetails接口,直接拿来使用就行。


自定义登录页面和不需认证也可访问的页面

  1. 在配置类中实现相关的配置

     @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.formLogin()    //自己定义自己写的页面
                .loginPage("/login.html")   //登录页面设置
                .loginProcessingUrl("/user/login")//登录访问路径
                .defaultSuccessUrl("/test/index").permitAll()//登录成功之后,跳转的路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll()//设置哪些页面可以直接访问
                .anyRequest().authenticated()
                .and().csrf().disable();//关闭csrf防护
        }
    

    在配置类中重写configure()方法,利用里面的各种方法来进行配置。

  2. 编写相关页面与Controller

    • login页面:在resource目录下的static目录下创建

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Title</title>
      </head>
      <body>
      <form action="/user/login" method="post">
          用户名:<input type="text" name="username">
          <br>
          密码:<input type="password"name="password">
          <br>
          <input type="submit" value="login">
      </form>
      
      </body>
      </html>
      

    注意这里的用户名和密码的name属性一定要交username和password,这样才能被springsecurity识别到。

    • controller

        @GetMapping("index")
          public String index(){
              return "hello index";
          }
      
  3. 测试
    在浏览器去访问.antMatchers(“/”,“/test/hello”,“/user/login”).permitAll()里设置的路径可以直接访问,但若是去访问其它路径,比如“/test/index”就会跳转到login登录页面
    在这里插入图片描述

    输入数据库中存在的用户后就可以访问。


基于角色或权限进行访问控制

hasAuthority()

​ 如果当前的主体具有指定的权限,则返回 true,否则返回 false

此方法在SecurityConfig类中的configure()方法中配置格式如下:

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()    //自己定义自己写的页面
            .loginPage("/login.html")   //登录页面设置
            .loginProcessingUrl("/user/login")//登录访问路径
            .defaultSuccessUrl("/test/index").permitAll()//登录成功之后,跳转的路径
            .and().authorizeRequests()
                .antMatchers("/","/test/hello","/user/login").permitAll()//设置哪些页面可以直接访问
                .antMatchers("/test/index").hasAuthority("admins")//设置admins权限的用户才能访问
            .anyRequest().authenticated()
            .and().csrf().disable();//关闭csrf防护
    }

用antMatchers方法来指定要访问的页面,使用hasAuthority()来指定权限,在MyUserDatailsService类中指定权限:

 List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_laoban");

里面的字符传用逗号隔开,只要有一个隔开后的字符串与之相匹配就可以通过访问。

hasAnyAuthority()

​ 如果当前的主体具有指定的权限之一(指定的权限为用逗号分隔的字符串),则返回 true,否则返回 false

和上面的使用方法一样,唯一的区别就是这个方法可以设置多个权限,用逗号隔开

.antMatchers("/test/index").hasAnyAuthority("admins","admin")//设置权限为字符串列表之一的就能访问

hasRole()

​ 如果用户具备给定角色就允许访问,否则出现403

​ 如果当前主体具有知道的角色,则返回true

​ 该方法和hasAuthority()使用方式差不多,但这是通过角色判断的,而在springSecurity中角色都有一个前缀“ROLE_”,因此,用户角色要包含“ROLE__”。

.antMatchers("/test/index").hasRole("xiaosou")//设置角色为xiaosou
List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_xiaosou");

hasAnyRole()

​ 如果用户具备给定角色之一就允许访问,否则出现403

​ 该方法和hasAnyAuthority()差不多,可以一次设置多个角色,只要有其中一个角色就可以访问改页面

.antMatchers("/test/index").hasAnyRole("xiaosou","laoban")
 List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_laoban");

上面的代码设置了角色为,xiaosou和laoban。AuthorityUtils.commaSeparatedStringToAuthorityList(“admins,ROLE_laoban”);方法里的参数可以代表权限和角色名称,当有多个页面访问控制时,只要满足其中一个就可以访问页面。


自定义403页面

在resource目录下的static目录下创建error目录,在error目录下创建一个403.html,这样下次当用户没有权限时会直接跳转到403.html。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
  你没有权限访问此页面
</div>
</body>
</html>

在这里插入图片描述


注解开发

@Secured

​ 一般使用在contoller层方法上,判断是否具有角色,另外需要注意的是这里匹配的字符串需要添加前缀“ROLE_”。使用注解需要先开启注解功能!@EnableGlobalMethodSecurity(securedEnabled = true)

在Controller类的方法上添加改注解

    @Secured("ROLE_testUser")
    @GetMapping("secured")
    public String secured(){
        return "secured";
    }

这里就表示需要角色为“testUser”的用户才可以访问此方法,注意这个注解参数中的角色需要加“ROLE_的前缀”。在UserDatailsService中给User对象设置好角色名称就可以了


List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList(
                "admin,admins,laoban,ROLE_testUser");
@PreAuthoize

​ 判断用户是否具有角色或权限。这个注解不仅仅可以通过角色来验证,还能通过用户权限来验证。使用方法如下:

  @PreAuthorize("hasAnyRole('laoban','testUser')")
    @GetMapping("authoize")
    public String PreAuthoize(){
        return "PreAuthoize";
    }

这里使用的是角色或权限访问控制的方法,也可以使用上面提到的任意方法,注意方法在双引号内部,形参用单引号包住,逗号隔开。这里形参中的角色名不需要加任何前缀,但UserDatailsService中的设置角色名还是需要添加“ROLE_”前缀

@PostAuthorize

​ 在方法执行后验证,用户是否具有角色或权限。该方法使用的场景不多,使用方法如下:

	@PostAuthorize("hasAnyAuthority('admins','testUser')")
    @GetMapping("Authorize")
    public String PostAuthorize(){
        return "PostAuthorize";
    }

注解的使用方式和@PreAuthoize一样,不同的是,这个方法会先执行一遍再去验证用户是否具有权限。


用户注销

  1. 在配置类中添加上一个退出的配置

    //退出配置
    http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();
    

    使用logout()定义好用户注销的路径和用户注销成功后的跳转页面。


自动登录

​ 自动登录是当用户第一次登录成功时,后端将返回包含身份验证令牌的响应。在后续的请求中,如果用户的身份验证令牌有效,服务器将用户视为已经身份验证过。并允许用户访问需要身份验证的资源。

​ 下面使用cookie存储身份验证的信息。

  1. 在数据库中创建一个用来存放带有验证令牌的表

    CREATE TABLE `persistent_logins` (
    `username` varchar(64) NOT NULL,
    `series` varchar(64) NOT NULL,
    `token` varchar(64) NOT NULL,
    `last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`series`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    
  2. 在配置类中注入数据源

       //注入数据源
        @Autowired
        private DataSource dataSource;
    
  3. 创建返回值为JdbcTokenRepositoryImpl类的方法并让Spring管理

       @Bean
        public PersistentTokenRepository persistentTokenRepository(){
            JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
            //设置数据源
            jdbcTokenRepository.setDataSource(dataSource);
            //自动创建表,第一次执行会创建,以后要执行就删掉
            //jdbcTokenRepository.setCreateTableOnStartup(true);
            return jdbcTokenRepository;
        }
    
  4. 在配置类中的 void configure(HttpSecurity http)方法中添加rememberMe()方法

    @Configuration
    public class SecuityConfig1 extends WebSecurityConfigurerAdapter {
        @Autowired
        private UserDetailsService userDetailsService;
    
        //注入数据源
        @Autowired
        private DataSource dataSource;
    
        @Bean
        public PersistentTokenRepository persistentTokenRepository(){
            JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
            //设置数据源
            jdbcTokenRepository.setDataSource(dataSource);
            //自动创建表,第一次执行会创建,以后要执行就删掉
            //jdbcTokenRepository.setCreateTableOnStartup(true);
            return jdbcTokenRepository;
        }
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
        }
        @Bean
        PasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //退出配置
            http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();
            http.formLogin()    //自己定义自己写的页面
                .loginPage("/login.html")   //登录页面设置
                .loginProcessingUrl("/user/login")//登录访问路径
                .defaultSuccessUrl("/success.html").permitAll()//登录成功之后,跳转的路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll()//设置哪些页面可以直接访问
                    .antMatchers("/test/index").hasAuthority("admins")//设置admins权限的用户才能访问
                .anyRequest().authenticated()
                    .and().rememberMe().tokenRepository(persistentTokenRepository())//操作数据库的对象
                    .tokenValiditySeconds(120)//表示记住多长时间,单位为秒
                    .userDetailsService(userDetailsService)//设置userData,用来操作数据库
                .and().csrf().disable();//关闭csrf防护
        }
    }
    

    使用tokenRepository()方法来操作数据库的对象;tokenValiditySeconds(120)方法来设置用户存放的时间。userDetailsService()方法来设置uaseData。

.anyRequest().authenticated()
.and().rememberMe().tokenRepository(persistentTokenRepository())//操作数据库的对象
.tokenValiditySeconds(120)//表示记住多长时间,单位为秒
.userDetailsService(userDetailsService)//设置userData,用来操作数据库
.and().csrf().disable();//关闭csrf防护
}
}


使用tokenRepository()方法来操作数据库的对象;tokenValiditySeconds(120)方法来设置用户存放的时间。userDetailsService()方法来设置uaseData。

重启服务,在浏览器中登录后再推出浏览器一样可以访问需要授权的资源。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值