Spring Security的基础使用

目录

一. 什么是spring security

二. Spring security 的使用

1.创建springboot项目

 2.主启动类

2.配置controller层

3.配置config类

4.配置多用户登录以及注入权限及登录config注入

5.配置config层

6.登录成功处理类及无权限处理类

7.配置工具类

8.启动测试

三. 总结


一. 什么是spring security

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安 全访问控制解决方案的安全框架。它提供了一组可以在Sprirg应用上下文 中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection依赖主入)和AOP(面向切面编程)功能,为应 用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写 大量重复代码的工作。 以上解释来源于百度白科。可以一句话来概括,SpringSecurity 是一个安全框架。可以帮我们完成认证,授权,密码加密,rememberme的功能。

二. Spring security 的使用

1.创建springboot项目

Spring Security的基础使用_第1张图片

 2.主启动类

package com.exy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@SpringBootApplication
public class SecurityApplication {

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

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

2.配置controller层

package com.exy.controller;

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

/**
 * @program: springsecurity-qy145-01
 * @description:
 * @author: 
 * @create: 2022-03-10 11:07
 * 只要账号登录 后 都可以访问所有的资源。
 *    1.ykq 进入可以访问 list  inser  delete update
 *    2.mcl 进入只能访问 list  export
 **/
@RestController
public class Test {

    @GetMapping("/list")
    public String list(){

        return "user:list";
    }

    @GetMapping("/insert")
    public String insert(){

        return "user:insert";
    }

    @GetMapping("/delete")
    public String delete(){

        return "user:delete";
    }

    @GetMapping("/update")
    public String update(){

        return "user:update";
    }

    @GetMapping("/export")
    public String export(){

        return "user:export";
    }
}

3.配置config类

package com.exy.config;

import com.exy.handle.MyAccessDeniedHandler;
import com.exy.handle.SuccessHandler;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.parameters.P;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @program: security01
 * @description:
 * @author: jdy
 * @create: 2022-03-10 10:05
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SuccessHandler successHandler;
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("jdy")
                .password(passwordEncoder.encode("123132"))
                .roles("admin")
                .authorities("user:list","user:delete");

    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().successHandler(successHandler).permitAll();
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);

        http.authorizeRequests()
                .antMatchers("/list").hasAnyAuthority("user:list")
                .antMatchers("/insert").hasAnyAuthority("user:insert")
                .antMatchers("/update").hasAnyAuthority("user:update")
                .antMatchers("/delete").hasAnyAuthority("user:delete")
                .antMatchers("/export").hasAnyAuthority("user:export");
    }
}

4.配置多用户登录以及注入权限及登录config注入

package com.exy.config;

import com.exy.handle.MyAccessDeniedHandler;
import com.exy.handle.SuccessHandler;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.parameters.P;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @program: security01
 * @description:
 * @author: jdy
 * @create: 2022-03-10 10:05
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SuccessHandler successHandler;
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("jdy")
                .password(passwordEncoder.encode("123132"))
                .roles("admin")
                .authorities("user:list","user:delete");

    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().successHandler(successHandler).permitAll();
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);

        http.authorizeRequests()
                .antMatchers("/list").hasAnyAuthority("user:list")
                .antMatchers("/insert").hasAnyAuthority("user:insert")
                .antMatchers("/update").hasAnyAuthority("user:update")
                .antMatchers("/delete").hasAnyAuthority("user:delete")
                .antMatchers("/export").hasAnyAuthority("user:export");
    }
}

5.配置config层

package com.exy.config;

import com.exy.handle.MyAccessDeniedHandler;
import com.exy.handle.SuccessHandler;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.parameters.P;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @program: security01
 * @description:
 * @author: jdy
 * @create: 2022-03-10 10:05
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SuccessHandler successHandler;
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("jdy")
                .password(passwordEncoder.encode("123132"))
                .roles("admin")
                .authorities("user:list","user:delete");

    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().successHandler(successHandler).permitAll();
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);

        http.authorizeRequests()
                .antMatchers("/list").hasAnyAuthority("user:list")
                .antMatchers("/insert").hasAnyAuthority("user:insert")
                .antMatchers("/update").hasAnyAuthority("user:update")
                .antMatchers("/delete").hasAnyAuthority("user:delete")
                .antMatchers("/export").hasAnyAuthority("user:export");
    }
}

6.登录成功处理类及无权限处理类

package com.exy.handle;

import com.exy.util.CommonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @program: security01
 * @description:
 * @author: jdy
 * @create: 2022-03-10 16:02
 **/

@Component
public class SuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        CommonResult commonResult = new CommonResult(2000, "登录成功", authentication);
        PrintWriter writer = response.getWriter();
        writer.print(new ObjectMapper().writeValueAsString(commonResult));
        writer.flush();
        writer.close();
    }
}
package com.exy.handle;

import com.exy.util.CommonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @program: security01
 * @description:
 * @author: jdy
 * @create: 2022-03-10 17:15
 **/
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        CommonResult commonResult = new CommonResult(2000, "权限不足", accessDeniedException);
        PrintWriter writer = response.getWriter();
        writer.print(new ObjectMapper().writeValueAsString(commonResult));
        writer.flush();
        writer.close();
    }
}

7.配置工具类

@Data
@AllArgsConstructor
@NoArgsConstructor

public class CommonResult {
    private int code;
    private String msg;
    private Object data;
}

8.启动测试

Spring Security的基础使用_第2张图片

 Spring Security的基础使用_第3张图片

 Spring Security的基础使用_第4张图片

三. 总结

进入移动互联网时代,大家每天都在刷手机,常用的软件有微信、支付 宝、头条,抖音等,下边拿微信来举例子说明认证相关的基本概念,在初 次使用微信前需要注册成为微信用户,然后输入账号和密码即可登录微 信,输入账号和密码登录微信的过程就是认证。 系统为什么要认证? 认证是为了保护系统的隐私数据与资源,用户的身份合法,方可访问该系统 的资源。 认证︰用户认证就是判断一个用户的身份是否合法的过程,用户去访问系 统资源时系统要求验证用户的身份信息,身份合法 方可继续访问,不合法 则拒绝访问。常见的用户身份认证方式有:用户名密码登录,二维码登录, 手机短信登录,指纹认证等方式。

你可能感兴趣的:(java,后端,spring,spring,java,安全)