Quickly build IDEA+SpringBoot+SpringSecurity

I am new, don’t ask me if I’m fine, I don’t know.

Basic concepts and instructions:

1. Spring Security comes with the initial login page, of course, you can also replace it with the page you made.
2. The functions of Spring Security I temporarily understand are:
authentication : it can be understood as login, authentication of identity, and judgment of whether to log in or not, it is just one On shopping sites, you can browse the products without logging in, but when you add to the shopping cart, you will make a login judgment. If you do not log in, you will be guided to log in.
Authorization : Determine what identity you are and what function it corresponds to. If you log in to Taobao as Jack Ma, then you can set up menus, set up products, etc. If you are a customer logging into Taobao, then you can only browse and purchase.

3. This demonstration does not connect to the database, it is simply a demonstration of Spring Security, which is not very complicated, and I am confused when it is complicated.

Steps of this demonstration:

  1. Add dependency
  2. Configure the application.properties file
  3. Complete configuration class
  4. Run directly

The one wrapped in the red circle is to be made this time
Insert picture description here

Start directly:

1. Add dependencies

<!--spring security安全框架,身份识别-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. Configure the application.properties file.
Note: Here is an explanation. When I created the project, I chose SpringBoot+MySQL+mybatis, so the database needs to be configured here, otherwise an error will be reported. . . . . .

spring.datasource.url=jdbc:mysql:///localhost:3306/ssm001?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
mybatis.mapper-locations=classpath:mapper/*.xml

#配置视图解析器
#访问地址前缀
spring.mvc.view.prefix=/WEB-INF/views
#访问地址后缀
spring.mvc.view.suffix=.jsp
#工程路径
server.servlet.context-path=/
#端口
server.port=8080

3. Complete the configuration class (the following are two configuration classes and a Controller class, you should remember to change the package name and class name)

package com.example.demo4.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//SpringMVC配置类
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    

    @Override
    public void addViewControllers(ViewControllerRegistry registry){
    
    
        registry.addViewController("/").setViewName("redirect:/login");
    }
}
package com.example.demo4.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

//Security配置类
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    

//    定义用户信息服务(查询用户信息)
    @Bean
    public UserDetailsService userDetailsService(){
    
    
//        内存的方式
        InMemoryUserDetailsManager manager =new InMemoryUserDetailsManager();

//        manager.createUser(User.withUsername("模拟数据库中取出的用户名").password("模拟数据库中取出的密码").authorities("数据库中取出的权限").build());
        manager.createUser(User.withUsername("admin").password("admin").authorities("p1").build());
        return manager;
    }

//    密码编码器,NoOpPasswordEncoder字符串比较,没有加密80
    @Bean
    public PasswordEncoder passwordEncoder(){
    
    
        return NoOpPasswordEncoder.getInstance();
    }

//    安全拦截机制(核心)
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        http.authorizeRequests()
//                设置需要拦截的地址,和对应的权限(/r/r1是地址,p1是权限)
//                .antMatchers("/r/r1").hasAuthority("p1")
//                .antMatchers("/r/r2").hasAuthority("p2")
//                设置所有在/r/下面的地址全部都要认证通过
                .antMatchers("/r/**").authenticated()
//                 除了上述/r/下面的地址,其他的都不需要认证
                .anyRequest().permitAll()
                .and()
//                允许表单登陆
                .formLogin()
//                自定义登陆成功的页面地址
                .successForwardUrl("/login-success");
    }


//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
//        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
//    }

}
package com.example.demo4.config;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/")
public class SecurityController {
    
    

    @RequestMapping(value = "login-success",produces = {
    
    "text/plain;charset=UTF-8"})
    public String loginSuccess(){
    
    return "登陆成功;";}

    @RequestMapping(value = "/r/r1",produces = {
    
    "text/plain;charset=UTF-8"})
    public String r1(){
    
    return "资源1;";}

    @RequestMapping(value = "/r/r2",produces = {
    
    "text/plain;charset=UTF-8"})
    public String r2(){
    
    return "资源2;";}
}

4. Start running
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/MYNAMEL/article/details/109524888