1. 程式人生 > 其它 >springboot(一)中使用Spring Security 來使用者登入

springboot(一)中使用Spring Security 來使用者登入

第一步:首先建立一個Spring Boot專案

注意一點使用SpringBoot的版本是

<version>2.2.1.RELEASE</version>

把其中的配置檔案修改一下

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
因為是web專案所有要加一個web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
新增加一個配置檔案
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
第二步:建立一個Controller包
寫一個測試的Controller
@RestController
@RequestMapping("/test")
public class TestController {

@GetMapping("hello")
public String add(){
return "hello world";
}
}
修改一下埠號
server.port=8081
啟動進入剛剛寫的測試Controller(http://localhost:8081/test/hello)會跳轉到這裡

這樣就說明攔截成功

它有一個預設的使用者名稱是user,密碼是

啟動的時候會生成,輸入賬號密碼會跳轉,進入到一下頁面,

說明沒有問題。

Web設定使用者名稱和密碼的三種方式

第一種方式:通過配置檔案

第二種方式:通過配置類

@Override
protected void configure(AuthenticationManagerBuilder auth)throws Exception{
//建立一個物件
BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
//進行加密
String encode = passwordEncoder.encode("123");
//列印輸出
System.out.println(encode);
//通過配置類設定使用者名稱和密碼
auth.inMemoryAuthentication().withUser("root").password(encode).roles("admin");
}
到這一步要是登入會報錯
There is no PasswordEncoder mapped for the id "null"
在下面建立一個
@Bean
PasswordEncoder password(){
return new BCryptPasswordEncoder();
}
這樣就不報錯了

第三種方式:自定義編寫實現類

第一步:建立配置類,設定使用哪個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物件有

//註解和SecurityConfigTest類中的Autowired一樣
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//設定許可權不能為空必須有值
List<GrantedAuthority>auths=
AuthorityUtils.commaSeparatedStringToAuthorityList("role");
//返回三個引數使用者名稱,密碼,許可權
return new User("root1",
new BCryptPasswordEncoder().encode("321"),auths);
}
}
把第二個方法個註釋掉

使用資料庫完成使用者認證

第一步:引入依賴
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok 用來簡化實體類-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
第二步:建立資料庫和表
建立語句如下:
create database cs;
use cs;

create table users(
id bigint primary key auto_increment,
username varchar(20) unique not null,
password varchar(100)
);
-- 密碼 atguigu
insert into users values(1,'張
san','$2a$10$2R/M6iU3mCZt3ByG7kwYTeeW0w7/UqdeXrb27zkBIizBvAven0/na');
-- 密碼 atguigu
insert into users values(2,'李
si','$2a$10$2R/M6iU3mCZt3ByG7kwYTeeW0w7/UqdeXrb27zkBIizBvAven0/na');
create table role(
id bigint primary key auto_increment,
name varchar(20)
);
insert into role values(1,'管理員');
insert into role values(2,'普通使用者');
create table role_user(
uid bigint,
rid bigint
);
insert into role_user values(1,1);
insert into role_user values(2,2);
create table menu(
id bigint primary key auto_increment,
name varchar(20),
url varchar(100),
parentid bigint,
permission varchar(20)
);
insert into menu values(1,'系統管理','',0,'menu:system');
insert into menu values(2,'使用者管理','',0,'menu:user');
create table role_menu(
mid bigint,
rid bigint
);
insert into role_menu values(1,1);
insert into role_menu values(2,1);
insert into role_menu values(2,2);
第三步:建立users對應實體類
實體類名是entity
@Data
public class Users {
private Integer id;
private String username;
private String password;
}
@Data是lombok可以不用寫get,set方法
第四步:整合mp,建立介面,繼承mp的介面
public interface UserMapper extends BaseMapper<Users> {
}
第五步:在MyUserDetailsService呼叫mapper裡面的方法查詢資料庫進行使用者認證
在service更新程式碼

@Autowired

private UserMapper userMapper;
  @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//呼叫userMapper方法,根據使用者名稱查詢資料庫
QueryWrapper<Users> wrapper = new QueryWrapper<>();
//where username=?
wrapper.eq("username",username);
//查詢
Users users = userMapper.selectOne(wrapper);
//判斷
if (users == null){//資料庫沒有使用者名稱,認證失敗
//拋異常
throw new UsernameNotFoundException("使用者名稱不存在!");
}
//設定許可權不能為空必須有值
List<GrantedAuthority>auths=
AuthorityUtils.commaSeparatedStringToAuthorityList("role");
//返回三個引數使用者名稱,密碼,許可權
//從查詢資料庫返回users物件,得到使用者名稱和密碼,返回
return new User(users.getUsername(),
new BCryptPasswordEncoder().encode(users.getPassword()),
auths);
}
在第四步上面加上@Repository註解
@Repository
public interface UserMapper extends BaseMapper<Users> {
}
第六步 在啟動類添加註解
@MapperScan("com.qxrz.securitydemo.mapper")
第七步配置檔案新增資料庫配置
#mysql 資料庫連線 #資料庫8就使用 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #不是8使用 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3307/cs?serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=root

本文來自部落格園,作者:我是一個小倉鼠,轉載請註明原文連結:https://www.cnblogs.com/yongyuankuaile/p/15350129.html