SpringBoot整合SpringSecurity. ----第一波 (了解咋用)


参考: https://www.bilibili.com/video/BV1KE411i7bC?p=2&spm_id_from=pageDriver

maven依赖


    org.springframework.boot
    spring-boot-starter-security

创建配置文件SecurityConfig

认证与授权

SecurityConfig

package com.config;

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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
      //链式写法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //首页所有人都可以访问
                .antMatchers("/").permitAll()
                .antMatchers("/getmemory/**").hasAnyRole("vip");

//        没有权限默认跳转到登录页面
        //Login --默认接口 /login
        http.formLogin()
                .defaultSuccessUrl("/getmemory")  //defaultSuccessUrl登录成功跳转的url
                .usernameParameter("user")        //接收user作为账号
                .passwordParameter("pwd");        //接收pwd作为密码

        http.rememberMe(); //        rememberMe为开启记住我功能--其实就是设置了cookie的有效时长
        http.csrf().disable();//禁用跨站csrf攻击防御--开启后接口只需要传账号和密码 可做前后端分离



        //注销 开启注销功能,logoutSuccessUrl跳转页面
        http.logout().logoutSuccessUrl("/");
    }
    
    
    
    //设置登录和角色

    //密码编码 passwordEncoder (请求时密码加密)--不加密授权登录会说没加密
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常应该从数据库中读
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lucax").password(new BCryptPasswordEncoder().encode("123456")).roles("vip")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("root");


    }

}

其他配置api扩展

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable() //禁用跨站csrf攻击防御
      .formLogin()
        .loginPage("/login.html")//用户未登录时,访问任何资源都转跳到该路径,即登录页面
        .loginProcessingUrl("/login")//登录表单form中action的地址,也就是处理认证请求的路径
        .usernameParameter("uname")///登录表单form中用户名输入框input的name名,不修改的话默认是username
        .passwordParameter("pword")//form中密码输入框input的name名,不修改的话默认是password
        .defaultSuccessUrl("/index")//登录认证成功后默认转跳的路径
        .and()
      .authorizeRequests()
        .antMatchers("/login.html","/login").permitAll()//不需要通过登录验证就可以被访问的资源路径
        .antMatchers("/biz1").hasAnyAuthority("biz1") //前面是资源的访问路径、后面是资源的名称或者叫资源ID
        .antMatchers("/biz2").hasAnyAuthority("biz2")
        .antMatchers("/syslog").hasAnyAuthority("syslog")
        .antMatchers("/sysuser").hasAnyAuthority("sysuser")
        .anyRequest().authenticated();
  }
}

控制层api扩展

package com.control.test.Success;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;


@RestController
public class login {

    @GetMapping("/tologin/")
    public void toLogin(@PathVariable() String name) {
        System.out.println(SecurityContextHolder.getContext()); //获取请求用户的身份
        System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal()); //判断用户是否登录
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            System.out.println(1);
            Object tager = ((UserDetails) principal).getAuthorities();  //---获取角色
            System.out.println(tager);

            String username = ((UserDetails) principal).getUsername();
            System.out.println(username);                             //--获取用户名
        } else {
            String username = principal.toString();
            System.out.println(username);
        }
    }
}