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项目


 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.启动测试


 

三. 总结
进入移动互联网时代,大家每天都在刷手机,常用的软件有微信、支付 宝、头条,抖音等,下边拿微信来举例子说明认证相关的基本概念,在初 次使用微信前需要注册成为微信用户,然后输入账号和密码即可登录微 信,输入账号和密码登录微信的过程就是认证。 系统为什么要认证? 认证是为了保护系统的隐私数据与资源,用户的身份合法,方可访问该系统 的资源。 认证︰用户认证就是判断一个用户的身份是否合法的过程,用户去访问系 统资源时系统要求验证用户的身份信息,身份合法 方可继续访问,不合法 则拒绝访问。常见的用户身份认证方式有:用户名密码登录,二维码登录, 手机短信登录,指纹认证等方式
————————————————
版权声明:本文为CSDN博主「贾斯汀_abc」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_48972623/article/details/123408466

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值