Spring-Security Privilege Management Framework (1) - Log on Based on Role Privileges

Keywords: Programming Spring Front-end

Summary of Spring-Security Framework Learning
Prerequisite: Before presenting, let's create a project and import it into IDE

Test whether the project is running successfully and start learning formally after success
Case1: As long as you can log in
Objectives: In our access project, we access index directly, without interception, access to other paths requires login verification, and allow logged-in users to log off and use forms for login, do not intercept front-end js,css,image and other files, we set up an admin user in memory to log in.
Go directly to the code (there will be comments in the code):
SecuDemoApplication:

package com.dhtt.security.SecuDemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableAutoConfiguration
public class SecuDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecuDemoApplication.class, args);
    }

    @RequestMapping("/index")
    public String hello() {
        return "hello Spring boot....";

    }

    @RequestMapping("/home")
    public String home() {
        return "this my home....";

    }
}

SpringSecruityConfig:

package com.dhtt.security.SecuDemo;

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 SpringSecruityConfig extends WebSecurityConfigurerAdapter{

    /**
     * HTTP Request interception processing
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/index").permitAll()  //Primary path direct request
        .anyRequest().authenticated()    //Ask him to verify all requests
        .and()
        .logout().permitAll()   //Allow write off
        .and()
        .formLogin();  //Allow form login
        http.csrf().disable();  //Turn off csrf authentication
    }

    /**
     * Processing front-end files, intercepting and ignoring
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**","/css/**","/image/**");
    }

    /**
     * Setting up user admin in memory
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
    }
}

Then we start the project and access the path in the foreground.
(1) Visit http://localhost:8080/index successfully

(2) Visit http://localhost:8080/home:
We found that the front desk would jump to the login interface for us, and then we carried out login verification. We found that the login interface did not jump and proved that the login failed. At this time, we observed the background.

Found backstage error reporting
(3) Error-reporting problem solving: The reason is the version of spring boot and Spring Security. We need to provide an example of PasswordEncore.
MyPasswordEncoder:

package com.dhtt.security.SecuDemo;

import org.springframework.security.crypto.password.PasswordEncoder;

public class MyPasswordEncoder implements PasswordEncoder{

    @Override
    public String encode(CharSequence rawPassword) {
        return rawPassword.toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encodedPassword.equals(rawPassword);
    }

}

Modification in Spring Secruity Config:

/**
     * Setting up user admin in memory
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
        .withUser("admin").password("123456").roles("ADMIN");
    }

Now run the project access / home again and we find that the login is successful and the page is accessed successfully.

Case2: Has a specified role, each role has a specified permission
(1) Goal: We add a new USER, which can access all addresses for ADMIN permissions, but user's permissions stipulate that it cannot access / role Auth, code:
Modification in Spring Secruity Config:

/**
     * Setting up user admin in memory
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
        .withUser("admin").password("haha1996").roles("ADMIN");
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
        .withUser("zhangsan").password("123456").roles("ADMIN");
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
        .withUser("username1").password("password").roles("USER");
    }

SecuDemoApplication: Here we add a new annotation

package com.dhtt.security.SecuDemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableAutoConfiguration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecuDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecuDemoApplication.class, args);
    }

    @RequestMapping("/index")
    public String hello() {
        return "hello Spring boot....";

    }

    @RequestMapping("/home")
    public String home() {
        return "this my home....";

    }

    @RequestMapping("/roleAuth")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String role() {
        return "HELLO SPRING SECURITY....";

    }
}

The result of the test run is the same as our expectation. We use admin to login, and the address is accessible. When we use user to login, we find that the access to the / role Auth path fails and there is no privilege.

                                To be continued...

Posted by SQHell on Sat, 19 Jan 2019 12:30:12 -0800