Chapter 03- What is RBAC

Section 01- What is Authentication? What kind of authorization?

Certification (Authentication) :

Authentication is used to identify whether the current user is a valid user in the system

Authorization (Authorization) :

The authorization function is to grant a user role that logs in to the system a list of menus or functions that the role can access

Section 02- What is RBAC

RBAC concept

RBAC is Role Base Access Control. In THE concept of RBAC, permissions are associated with roles. Users have specific roles and can automatically obtain permissions of these roles, which simplifies permission management. Basic idea is the system of various operation permissions should not be assigned to the user directly, but between users set and permissions set to create a character set, each character corresponds to a set of permissions response, once the user is assigned a proper role, after the user has the characters of all operation permissions, when creating the user only needs to assign roles to users, You can obtain a set of permissions. By designing a set of permissions corresponding to a role, you can simplify permission management. In RBAC, a user belongs to a role and a role has permissions. If a user belongs to a role, the user has permissions corresponding to the role. For example, in the background management system, common users can only view data, while administrators can modify data.

RBAC table design

Database table design based on RBAC, containing at least four tables, user table contains the user name password whether to enable fields, such as role table contains the character name character expression and other fields, role and user is a many-to-many relationship, need an intermediate table to correlate the relationship between users and roles, role and user relational tables contain the user ID and role ID two fields, There is also a permission table that indicates which permissions a role has, and the permissions can be represented by urIs

Authentication interfaces and classes in Spring Security

1) UserDetails: interface Methods: Boolean isAccountNonExpired(); Whether the account is expired Boolean isAccountNonLocked(); Boolean isCredentialsNonExpired(); Certificate expires Boolean isEnabled(); Is Collection< enabled for the account? extends GrantedAuthority> getAuthorities(); Permissions collection Implements Class: User

Common methods: user.withusername ().password().roles()

You can customize a class to implement the UserDetails interface as a user class in your system.

2) UserDetailsService: Service interface to get the user information, get the UserDetails object, need to define a custom class to implement the interface, get data from the database, UserDetails loadUserByUsername(String var1) : Obtains user information based on the user name(user name, password, role combination, availability, lock, etc.)

UserDetailsService interface implementation class have I: InMemoryUserDetailsManager: maintenance of user information in memory. JdbcUserDetailsManager: The user information is stored in the database. The JDBC Template of Spring is used to operate the data. You can create, update, delete, and check whether the data exists

The use of Section 03 – InMemoryUserDetailsManager class

1. Create a New Maven project and add dependencies

<! Add spring boot -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-parent</artifactId>
    <version>2.1.5. RELEASE</version>
</parent>

<! -- Specify dependencies -->
<dependencies>
    <! -- Web development dependencies -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <! --spring security-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
Copy the code

2. Create an application configuration in the config package class 1) create password processing class object (2) use InMemoryUserDetailsManager create user

@Configuration
public class ApplicationSecurityConfig {

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

    @Bean
    public UserDetailsService userDetailsService(a){
        PasswordEncoder passwordEncoder = passwordEncoder();

        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        // Create an in-memory USER and assign the ADMIN and USER roles
        manager.createUser(User.withUsername("admin")
                .password(passwordEncoder.encode("12345"))
                .roles("ADMIN"."USER").build());

        manager.createUser(User.withUsername("thor")
                .password(passwordEncoder.encode("12345"))
                .roles("USER").build());

        returnmanager; }}Copy the code

3. Create WebSecurityCinfigurerAdapter in the config package

@EnableWebSecurity
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http); http.userDetailsService(userDetailsService); }}Copy the code

4. Create controllers in the Controller package

@RestController
public class HelloSecurityController {

    @GetMapping("/hello")
    public String helloUserAndAdmin(a){
        return "Hello Spring Security"; }}Copy the code

5. Create a SpringBoot application boot class

@SpringBootApplication
public class SecurityApplication {

    public static void main(String[] args) { SpringApplication.run(SecurityApplication.class,args); }}Copy the code

Start the application, the browser address http://localhost:8080 will automatically jump to http://localhost:8080/login

Section 04-JdbcUserDetailsManager class

1. Create a data table, copy the users. DDL file, and modify it briefly

create table users(username varchar(50) not null primary key,password varchar(500) not null,enabled boolean not null);
create table authorities (username varchar(50) not null,authority varchar(50) not null.constraint fk_authorities_users foreign key(username) references users(username));
create unique index ix_auth_username on authorities (username,authority);
Copy the code

2. Create a new Maven project and add dependencies

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.18</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
Copy the code

3. Configure the data source in application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
Copy the code

4. Create a configuration class in the Config package

@Configuration
public class SecurityConfig {

    @Autowired
    private DataSource dataSource;

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

    @Bean // The bean ID is jdbcUserDetailsManager
    public UserDetailsService jdbcUserDetailsManager(a){

        PasswordEncoder passwordEncoder = passwordEncoder();

        JdbcUserDetailsManager manager = new JdbcUserDetailsManager(dataSource);
        manager.createUser(User.withUsername("odin")
                .password(passwordEncoder.encode("12345"))
                .roles("ADMIN"."MANAGER"."USER")
                .build());

        manager.createUser(User.withUsername("thor")
                .password(passwordEncoder.encode("12345"))
                .roles("MANAGER"."USER")
                .build());

        manager.createUser(User.withUsername("loki")
                .password(passwordEncoder.encode("12345"))
                .roles("USER")
                .build());

        returnmanager; }}Copy the code
@EnableWebSecurity
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Resource // Import by bean ID
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.congfigure(http); http.userDetailsService(userDetailsService); }}Copy the code

5. Create a SpringBoot application boot class

@SpringBootApplication
public class SecurityApplication {

    public static void main(String[] args) { SpringApplication.run(SecurityApplication.class,args); }}Copy the code

Start the application, the browser address http://localhost:8080 will automatically jump to http://localhost:8080/login can implement authentication function