栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot、Spring Security登录认证及权限问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot、Spring Security登录认证及权限问题


目录

一、登录验证

1.自定义密码账号

Ⅰ.引入依赖

Ⅱ. XxxApplication启动类

Ⅲ. 在application.yml文件中自定义

Ⅳ.启动项目

2.从数据库中查找账号和密码 

Ⅰ.引入依赖

Ⅱ. application.yml文件

Ⅲ. bean包的操作

Ⅳ. service层

Ⅴ.config配置类 

Ⅵ.启动项目

二、权限问题

1.config类

2.bean包

3.service层

4.启动项目


一、登录验证

1.自定义密码账号

Ⅰ.引入依赖

先搭建好一个SpringBoot框架,在基础上引入依赖



    org.springframework.boot
    spring-boot-starter-web
    2.7.1



    org.projectlombok
    lombok
    1.18.24



    org.springframework.boot
    spring-boot-starter-security

Ⅱ. XxxApplication启动类
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }
}

Ⅲ. 在application.yml文件中自定义
spring:
  security:
    user:
      name: porsche
      password: 911

Ⅳ.启动项目

运行项目,在网页中输入账号密码。

2.从数据库中查找账号和密码  Ⅰ.引入依赖


    mysql
    mysql-connector-java



    com.baomidou
    mybatis-plus-boot-starter
    3.5.1



    com.alibaba
    druid-spring-boot-starter
    1.2.9

Ⅱ. application.yml文件
server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: bjwl
    password: bjwl
    url: jdbc:mysql://192.168.1.118:3306/book_store?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true
    type: com.alibaba.druid.pool.DruidDataSource
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: false 
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Ⅲ. bean包的操作

实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class Users implements Serializable {

    private Integer id;
    private String userName;
    private String passWord;
    private String nickName;
    private Integer state;
}

LoginUsers类:

@AllArgsConstructor
@NoArgsConstructor
public class LoginUsers implements UserDetails {
    private Users users;

    //返回当前用户的所有权限
    public Collection getAuthorities() {
        return users.getList();
    }

    //返回密码
    public String getPassword() {
        return users.getPassWord();
    }

    //返回用户名
    public String getUsername() {
        return users.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Ⅳ. service层
// 是SpringSecurity的业务类,负责实现认证和授权
@Service
public class UsersService implements UserDetailsService {
    @Resource
    private UsersMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users users = mapper.selectOne(wrapper);//查询一条记录
        if (Objects.isNull(users)) {
            throw new RuntimeException("用户名没有找到");
        }
        return new LoginUsers(users);
    }
}

Ⅴ.config配置类 
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UsersService usersService;

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //数据库的认证
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(usersService).passwordEncoder(getPasswordEncoder());
    }
}

Ⅵ.启动项目

 此时后台也会显示出,在数据库中查询了一次

二、权限问题

1.config类

在类中设置权限,和设置权限名,给1.html只开启了abc01的权限,给2.html开启了abc01和abc02的权限。

也就是说abc01可以访问1.html和2.html,abc02只可以访问2.html

protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()
            .loginPage("/login.html")   //登录页面设置
            .loginProcessingUrl("/a/lo")    //登录访问路径  这里同 login.html中的action
            .permitAll()
            .and().exceptionHandling().accessDeniedPage("/403.html")
            .and().authorizeRequests()
            .antMatchers("/login.html", "/a/lo").permitAll()    //设置哪些路径可以直接访问,不需要认证
            .antMatchers("/1.html").hasAuthority("adc01")   //设置当前网页访问权限
            .antMatchers("/2.html").hasAnyAuthority("abc01","abc02")
            .anyRequest().authenticated()   //所有请求都可以访问
            .and().csrf().disable();    //关闭csrf,csrf:跨站请求伪造
}

2.bean包

在实体类中加入

@TableField(exist = false)
private List list;

3.service层

为用户设置权限名

List list = new ArrayList<>();
list.add(new SimpleGrantedAuthority("abc02"));
users.setList(list);

4.启动项目

登录

访问1.html

访问2.html

 


转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号