一 验证码
实体对象
private String code;
private LocalDateTime expireTime;
手机发送验证码 http://xxxx/code/sms
参数:phone 18915152022
deviceId p40ro121212
发送图片验证码 http://xxx/code/image
参数: whidth 图片尺寸
deviceId p40ro121212
store
redis:APP 小程序建议使用 key 的拼接建议 xxxxpre:code:codeType:deviceId
session: pc 浏览器端建议使用
jdbc:不建议使用
二 登录方式
1.用户名密码登录 http://xxx/authentication/signIn
header参数:
deviceId p40ro121212
Authorization Basic aHptOmh6bTEyMw== 即就是:(new BASE64Encoder()).encode((“clientId“+”:”+”clientSecret“).getBytes(“utf-8”));
表单参数:
username admin
password 123456
imageCode 5532
2.手机号验证码登录 http://xxx/authentication/mobile
header参数:
deviceId p40ro121212
Authorization Basic aHptOmh6bTEyMw== 即就是:(new BASE64Encoder()).encode((“clientId“+”:”+”clientSecret“).getBytes(“utf-8”));
表单参数:
mobile 18915152022
smsCode 787699
- 三方openid 登录 http://xxx/authentication/openid
建议使用 jwt 增强token,这样返回的信息更丰满
三 Security
三个核心功能
- 认证功能 (你是谁)
- 授权功能 (你能干什么)
- 攻击防护 (防止伪造身份)
3.1 基本原理
UserNamePasswordAuthenticationFilter 用户名密码认证
………
ExceptionTranslationFilter 处理异常类
FilterSecurityInterceptor 他就是一个守门员,最终都会走到这里
3.1.1 默认登录认证
即 根据idea 生成响应的security 工程,什么也不配置,然后新建一个rest 例如 getUser,它会让我们去登录
用户名是 user
密码是控制台打印的密码:
访问成功
这里与旧版本不一样了,旧版本是基于 http basic 安全认证的。
3.1.2 http basic 安全认证
package com.example.security.config;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;/*** @author hezhaoming* @date 2021/1/10*/@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {//http basic 认证http.httpBasic()// 下面这些请求都需要授权.and().authorizeRequests()//任何请求.anyRequest()//都需要认证.authenticated();}}
3.2 自定义登录
3.2.1 登录用户名密码校验
package com.example.security.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.Component;/*** @author hezhaoming* @date 2021/1/10*/@Componentpublic class MyUserDetailService implements UserDetailsService {@Autowiredprivate PasswordEncoder passwordEncoder;@Overridepublic UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {//todo 这里一般是查询数据库的用户名密码,这里作为演示写死String encode = passwordEncoder.encode("123456");return new User(userId, encode,true, true, true, true,AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER"));}}
3.2.2 自定义登录页面
3.2.3 自定义登录成功处理
3.2.4 自定义登录失败处理
3.3 源码透析


