Spring Boot Security – Database Authentication Example

Spring Boot Starters & Common Configurations Thực hành

Trong bài hướng dẫn trước mình đã triển khai Spring Boot Security – Creating a custom login page.

Cho đến bây giờ, mình đang sử dụng cấu hình bộ nhớ để xác thực người dùng và các role liên quan. Trong ví dụ này, mình sẽ xác thực người dùng và role với các bảng cơ sở dữ liệu.

Maven Project:

boot-36_4

Theo mặc định, Spring Security mong đượi các bảng được đăng tên là users table để lưu trữ username, password và bảng authorities. Trong schema-mysql.sql hãy thêm schemas và insert các câu lệnh sau:

DROP TABLE IF EXISTS employee;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS authorities;


CREATE TABLE employee (
  empId VARCHAR(10) NOT NULL,
  empName VARCHAR(100) NOT NULL
);

create table users (
    username varchar(50) not null primary key,
    password varchar(120) not null,
    enabled boolean not null
);

create table authorities (
    username varchar(50) not null,
    authority varchar(50) not null,
    foreign key (username) references users (username)
);

insert into users(username, password, enabled)values('javainuse','javainuse',true);
insert into authorities(username,authority)values('javainuse','ROLE_ADMIN');
 
insert into users(username, password, enabled)values('employee','employee',true);
insert into authorities(username,authority)values('javainuse','ROLE_USER');Code language: PHP (php)

Spring Boot JDBC chạy đoạn script này trước khi chạy ứng dụng.

Cuối cùng sửa đổi cấu hình Spring Security để chuyển sang jdbc authentication.

package com.javainuse.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class EmployeeSecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Autowired
    DataSource dataSource;

	//Enable jdbc authentication
    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource);
    }

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/resources/**");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/welcome").hasAnyRole("USER", "ADMIN")
				.antMatchers("/getEmployees").hasAnyRole("USER", "ADMIN").antMatchers("/addNewEmployee")
				.hasAnyRole("ADMIN").anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll()
				.and().logout().permitAll();

		http.csrf().disable();
	}

    //remove this in memory authentication configuration
	// @Autowired
	//public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
	//	authenticationMgr.inMemoryAuthentication().withUser("admin").password("admin").authorities("ROLE_USER").and()
	//			.withUser("javainuse").password("javainuse").authorities("ROLE_USER", "ROLE_ADMIN");
	//} 

}Code language: JavaScript (javascript)

Chạy ứng dụng và truy cập localhost:8080/welcome, chúng ta sẽ được chuyển đến trang login.

boot-36_1

Nhập javainuse người dùng và mật khẩu javainuse

boot-35_3

Vì vậy, ứng dụng đang hoạt động tốt và được xác thực chính xác bằng cách sử dụng các bảng cơ sở dữ liệu.

Nguồn:

https://www.javainuse.com/spring/boot_security_jdbc_authentication

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *