【安全框架】Spring Security、Oauth2、JWT 这一篇就够了

【安全框架】Spring Security、Oauth2、JWT 这一篇就够了,第1张

【安全框架】Spring Security、Oauth2、JWT 这一篇就够了

文章目录

Spring Security

1. 安全框架概述2. Spring Security 简述3.Spring Security

3.1 创建项目3.2 项目依赖3.3 页面

3.3.1 login.html3.3.2 main.html 3.4 测试

3.4.1 启动项目3.4.2 打开浏览器 3.5 自定义登录逻辑

3.5.1 Security 的配置类3.5.2 UserDetailsService 的实现类3.5.3 重启测试 3.6 自定义登陆页面

3.6.1 login.html3.6.2 Security 的配置类3.6.3 Controller3.6.4 重启测试 3.7 自定义失败页面

3.7.1 error.html3.7.2 Security 的配置类3.7.3 Controller 3.8 设置请求账户和密码的参数名

3.8.1 login.html3.8.2 Security 的配置类 3.9 自定义登陆成功处理器

3.9.1 MyAuthenticationSuccessHandler3.9.2 Security 的配置类 3.10 自定义登陆失败处理器

3.10.1 MyAuthenticationFailureHandler3.10.2 Security 的配置类 3.11 权限判断

3.11.1 main1.html3.11.2 Security 的配置类 3.12 角色判断

3.12.1 Security 的配置类 3.13 IP地址判断

3.13.1 Security 的配置类 3.14 自定义403处理方案

3.14.1 MyAccessDeniedHandler3.14.2 Security 的配置类 3.15 access 自定义权限

3.15.1 MyService3.15.2 MyServiceImpl3.15.3 Security 的配置类 3.16基于注解的访问控制

3.16.1 @Serured 注解

3.16.1.1 Security 的配置类3.16.1.2 Controller3.16.1.3 启动类 3.16.2 @PreAuthorize & @PostAuthorize

3.16.2.1 启动类3.16.2.2 Controller 3.17 Remember Me 功能实现

3.17.1 添加依赖3.17.2 Security 的配置类3.17.3 application.yml 3.18 Thymeleaf 在 SpringSecurity 中的使用

3.18.1 添加依赖3.18.2 thymeleaf 命名空间和 security 命名空间3.18.3 demo.html3.18.4 Controller 3.19 在 thymeleaf 中进行权限判断

3.19.1 demo.html 3.20 logout 退出登录的 *** 作

3.20.1 Security 的配置类3.20.2 main.html 3.21 Spring Security 中的 csrf

3.21.1 Controller3.21.2 Security 配置类 4. Oauth2 认证

4.1 常用术语4.2 令牌类型4.3 特点

4.3.1 优点4.3.2 缺点 4.4 授权模式

4.4.1 授权码模式4.4.2 简化模式4.4.3 密码模式4.4.4 客户端模式4.4.5 更新令牌 5. Spring Security Oauth2

5.1 添加依赖5.2 授权码模式

5.2.1 Security 配置类5.2.2 自定登录逻辑5.2.3 自定义 User5.2.4 授权服务器配置5.2.5 资源服务器配置5.2.6 启动测试

5.2.6.1 地址栏输入5.2.6.2 打开Postman 5.3 密码模式

5.3.1 Security 配置类5.3.2 授权服务器配置5.3.3 启动测试 5.4 Readis 存储 Token

5.4.1 Redis 配置类5.4.2 授权服务器配置5.4.3 启动测试 6. JWT

6.1 常见的认证机制

6.1.1 HTTP Basic Auth6.1.2 cookie Auth6.1.3 Token Auth

6.1.3.1 Token Auth 大概的流程6.1.3.2 Token Auth 的优点: 6.1.3 OAuth 6.2 JWT 简介

6.2.1 JWT令牌的优点6.2.2 JWT令牌的缺点 6.3 JWT的构成

6.3.1 头部(Header)6.3.2 载荷(Payload, 类似于飞机上承载的物品)6.3.2 签证(Signature)、签名

6.3.2.1 签名的目的 6.4 JJWT

6.4.1 添加依赖6.4.2 生成令牌6.4.3 解析令牌 7.Spring Security Oauth2 整合 JWT

7.1 JwtToken 配置类7.2 授权服务器配置7.3 扩展 JWT 里的内容存储

7.3.1 Jwt内容增强器7.3.2 JwtToken 配置类7.3.3 授权服务器配置 7.4 解析 Jwt 中的内容

7.4.1 添加依赖7.4.2 Controller 7.5 刷新令牌

7.5.1 授权服务器 8. Spring Security Oauth2 整合 SSO

8.1 添加依赖8.2 启动类8.3 Client01 的 Controller8.4 application.yml8.5 原来的 Spring Security Oauth2 的授权服务器配置8.5 *** 作演示

8.5.1 访问api

Spring Security

Spring家族一员。是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Contro1,DI: Dependency Injection依赖注入)和AOP(面向切面编程〉功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

1. 安全框架概述

什么是安全框架?解决系统安全问题的框架。如果没有安全框架,我们需要手动处理每个资源的访问控制,非常麻烦。使用安全框架,我们可以通过配置的方式实现对资源的访问限制。

2. Spring Security 简述

Spring Security是一个高度自定义的安全框架。利用Spring loC/DI和AOP功能,为系统提供了声明式安全访问控制功能,减少了为系统安全而编写大量重复代码的工作。使用Spring Secruity的原因有很多,但大部分都是发现了javaEE的Servlet规范或EJB规范中的安全功能缺乏典型企业应用场景。同时认识到他们在WAR 或EAR 级别无法移植。因此如果你更换服务器环境,还有大量工作去重新配置你的应用程序。使用Spring Security解决了这些问题,也为你提供许多其他有用的、可定制的安全功能。正如你可能知道的两个应用程序的两个主要区域是“认证"和"授权”(或者访问控制)。这两点也是Spring Security重要核心功能。

认证是建立一个他声明的主体的过程(一个"主体"一般是指用户,设备或一些可以在你的应用程序中执行动作的其他系统),通俗点说就是系统认为用户是否能登录。

授权指确定一个主体是否允许在你的应用程序执行一个动作的过程。通俗点讲就是系统判断用户是否有权限去做某些事情。

3.Spring Security 3.1 创建项目

3.2 项目依赖
    
        
            org.springframework.boot
            spring-boot-starter-security
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.springframework.security
            spring-security-test
            test
        

	 
3.3 页面 3.3.1 login.html



    
    登录





3.3.2 main.html



    
    Home


登录成功


3.4 测试 3.4.1 启动项目

3.4.2 打开浏览器
http://localhost:8080/login.html

初始账号 user

初始密码每次启动都会改变

会跳转到Spring Security 提供的登陆页面

注:没有做任何配置

3.5 自定义登录逻辑 3.5.1 Security 的配置类
package com.yuan.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;


@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder getPassWord() {
        return new BCryptPasswordEncoder();
    }
}
3.5.2 UserDetailsService 的实现类
package com.yuan.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("执行了loadUserByUsername方法");
        //1.查询数据库,用户名称/账号是否存在,如果不存在就抛出UsernameNotFoundException异常
        if (!"admin".equals(username)) throw new UsernameNotFoundException("用户名不存在");
        //2.把查询的密码(注册时加密过)进行解析,或者直接把密码放入构造方法
        String password = passwordEncoder.encode("123");
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_abc"));
    }
}
3.5.3 重启测试
http://localhost:8080/login.html

输入一个错的

输入正确的之后跳到了我们自己写的登陆页面

3.6 自定义登陆页面 3.6.1 login.html



    
    Title





3.6.2 Security 的配置类
package com.yuan.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义登录页面
        http.formLogin()
                //当发现、login的时候认为是登录,去执行 UserDetailsServiceImpl->loadUserByUsername
                .loginProcessingUrl("/login")
                //自定义登录页面
                .loginPage("/login.html")
                //登陆成功要跳转的页面,必须是post请求
                .successForwardUrl("/toMain")
        ;

        //设置了自定义登陆页面之后,security提供的原始的认证将全部失效
        //授权认证
        http.authorizeRequests()
                //登录页面,登陆失败页面都不需要认证
                .antMatchers("/login.html").permitAll()
                //所以要对所有的请求做拦截做认证【必须是登录之后才能被访问】
                .anyRequest().authenticated()
        ;

        //暂时理解为防火墙
        //关闭csrf防护
        http.csrf().disable();
    }

    @Bean
    public PasswordEncoder getPassWord() {
        return new BCryptPasswordEncoder();
    }
}
3.6.3 Controller
@RequestMapping("/toMain")
public String toMain() {
    return "redirect:main.html";
}
3.6.4 重启测试
http://localhost:8080/login.html

登陆后自动跳转

3.7 自定义失败页面 3.7.1 error.html



    
    错误



    登录失败重新登录					
										


					

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5706797.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存