• Spring Security 采用formLogin模式认证


    Spring Security 学习

    1. 采用formLogin认证方式

    1.1 创建角色

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*
        * 采用formLogin认证方式
        * */
        http.formLogin()
           .and().authorizeRequests()
          .antMatchers("/user/login").permitAll() // 允许暴露的接口
              .antMatchers("/user/getUserList").hasAnyAuthority("ROLE_ADMIN") // 需要ROLE_ADMIN角色才可以访问
          .antMatchers().hasAnyRole("ORDINARY") // 普通用户不分配任何权限
          .anyRequest().authenticated();
    }
    

    ​ 创建角色方式有两个:

    ​ 一种是使用hasAnyAuthority创建角色,所创建的角色名称前需要加ROLE_角色名称。

    ​ 另一种使用hasAnyRole创建角色,不用加ROLE_ 直接填写 角色名称即可。

    ​ 从源码中可以看出hasRole 在return 时 添加了ROLE_前缀。

    1.2创建用户

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 为用户分配角色
        auth.inMemoryAuthentication()
                .withUser("zhangsan") // 创建用户名为zhangsan
                .password(passwordEncoder().encode("123456")) // 用户密码
                .roles("ADMIN") // 用户所持有的角色
                .and()
                .withUser("lisi")
                .password(passwordEncoder().encode("123456"))
                .roles("ORDINARY")
                .and()
                .passwordEncoder(passwordEncoder()); // 配置密码BCrypt加密
    }
    
    @Bean
        public PasswordEncoder passwordEncoder () {
            return new BCryptPasswordEncoder();
        }
    
    1. 用户 zhangsan (张三) 初始密码为:123456 所拥有的角色是admin。
    2. 用户lisi(李四)初始密码为:123456 赋予普通用户角色ORDINARY
    • 我们配置了/user/login 不做拦截可以直接访问

    • 在未登录的情况下访问需要验证的接口,将会跳转到SpringSecurity默认提供的登录页面。

    • 用普通用户(李四)访问http://localhost:8080/user/getUserList地址,将会提示没有权限错误 403

    • 采用admin用户(张三)访问http://localhost:8080/user/getUserList地址

  • 相关阅读:
    仿MSN小类别滑动效果
    pku1674 Sorting by Swapping
    pku1456 Supermarket
    pku1083 Moving Tables
    pku1125 Stockbroker Grapevine
    pku2232 New StoneForfexCloth Game
    如何低头前进
    和两年前一样
    股票亏了
    早上选举了
  • 原文地址:https://www.cnblogs.com/xyqbk/p/13581555.html
Copyright © 2020-2023  润新知