SpringSecuity用户认证(详解)

SpringSecuity用户认证

既然我们开发的项目是spring这一套,这篇文章我们就来详细讲解SpringSecuity安全框架。

至于Shiro安全框架,我打算另起一篇讲解。

一、搭建SpringBoot工程

首先,我们先要搭建一个简单的SpringBoot工程

设置父工程,添加依赖,导入插件

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.3</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>    


<!--导入插件-->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>2.7.3</version>
        </plugin>
    </plugins>
</build>

创建启动类

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {

        SpringApplication.run(MainApplication.class,args);
    }
}

创建Controller

@RestController
public class HelloController {
    @RequestMapping("/")
    public String hello(){
        return "hello";
    }
}

访问网址:localhost:8080/

在这里插入图片描述.

二、系统默认用户认证

1)引入SpringSecurity依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.7.3</version>
</dependency>

引入依赖后再去访问之前的网址,则会自动跳转到一个SpringSecurity的默认登陆页面,

默认用户名是user,密码会输出在控制台,如下:

在这里插入图片描述.

在这里插入图片描述

三、设置登录用户名和密码

1、通过配置文件

application.yaml

spring:
  security:
    user:
      name: kxy
      password: 123456

登录账号:kxy 密码:123456

2、通过配置类

SecurityConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode("123");
        auth.inMemoryAuthentication().withUser("jin").password(password).roles("admin");
    }

    //创建接口名字
    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }
}

登录账号:jin 密码:123

注意 : 如果配置文件和配置类都写了,最终以配置类为主!

3、自定义编写实现类 【常用】

第一步:创建配置类,设置使用哪个userDetailsService实现类

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

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

第二步:编写实现类,返回User对象,User对象有用户名明码和操作权限

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        List<GrantedAuthority> auths =
                AuthorityUtils.commaSeparatedStringToAuthorityList("role");

        return new User("root",new BCryptPasswordEncoder().encode("123456"),auths);

    }
}

登录账号:root 密码:123456

四、根据数据库设置用户认证账号密码

1、创建数据库、导入依赖、实体类
create database security;

use security;

create table user(
id int(10) PRIMARY KEY auto_increment,
username varchar(20) not null,
password varchar(100) not null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO user(id,username,password) VALUES
(1,'kxy','123456')

在这里插入图片描述.

 <!--mybatis-plus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
		<!--test依赖-->
 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class Users {
    private Integer id;
    private String username;
    private String password;
}
2、配置数据库信息
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    username: root
    password: 123456
3、整合MP,创建接口,继承MP的接口
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jin.pojo.Users;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface UserMapper extends BaseMapper<Users> {
}
4、在MyUserDetailsService调用mapper里面的方法查询数据库进行用户认证
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jin.mapper.UserMapper;
import com.jin.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用userMapper方法,根据用户名查询
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Users user = userMapper.selectOne(wrapper);

        if(user==null){
            //数据库没有用户名,认证失败
            throw new UsernameNotFoundException("用户名不存在!");
        }

        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");

        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), auths);
    }
}

注意:

要么在启动器添加注解MapperScan,或者Mapper接口上添加@Mapper

这步省略,第四步操作已完成!


SpringSecurity用户授权

点击跳转: https://blog.csdn.net/weixin_45737330/article/details/127118820

SpringSecurity用户注销

点击跳转:https://blog.csdn.net/weixin_45737330/article/details/127123226

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

已转行@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值