spring-security【2022-3-18更新】

这篇博客更新于2022-3-18,主要介绍了如何在Spring Security中进行自定义安全配置,包括使用WebSecurityConfigurerAdapter和AuthenticationManagerBuilder来定制策略,以及实现自定义登录成功和失败处理器。此外,还涉及到了403权限不足异常的处理方法,并给出了模拟前端界面的错误、登录和主页面模板。
摘要由CSDN通过智能技术生成

【2022-3-18更新】

  1. 文档结构目录;
  2. 更新笔记。

更新整理 👉 Git,或 💪点击这里

导包

<!--   spring security 包含下面两个注释掉的包   -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--        <dependency>-->
<!--            <groupId>org.springframework.security</groupId>-->
<!--            <artifactId>spring-security-web</artifactId>-->
<!--        </dependency>-->
<!--        <dependency>-->
<!--            <groupId>org.springframework.security</groupId>-->
<!--            <artifactId>spring-security-config</artifactId>-->
<!--        </dependency>-->
  • WebSecurityConfigurerAdapter:自定义 Security 策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecuryti模式

Authentication - 认证
Authorization - 授权

  • Controller.java
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
   

    @RequestMapping("/toMain")
    public String toLogin(){
   
        return "redirect:main.html";
    }

    @RequestMapping("/toError")
    public String Error(){
   
        return "redirect:error.html";
    }
}

本质上主要是使用了AOP 和 拦截器!

  • SecurityConfiguration.java
package com.example.demo.config;

import com.example.demo.hanlder.MyAccessDeniedHandler;
import com.example.demo.hanlder.MyAuthenticationFailureHandler;
import com.example.demo.hanlder.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
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;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
   

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    // 下面自定义登录逻辑时需要用到
    @Bean
    public PasswordEncoder getPasswordEncoder() {
   
        return new BCryptPasswordEncoder();
    <
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值