区分
认证使用的是 oauth2
授权使用的是 spring security
JWT:
普通的oauth2颁发的就是一串随机hash字符串,jwt就是一种特殊格式的token,包含头部Header,载荷Payload,签名Signature。
模式
需要配置如下三步:
(1)配置资源服务器
(2)配置认证服务器
(3)配置spring security
oauth2分成了4种模式
(1)授权码模式(authorization code)
(2)简化模式(implicit)
(3)密码模式(resource owner password credentials)
(4)客户端模式(client credentials)
流程
首先进入登录页面-》输入用户名密码,访问spring security oauth2内置的login接口,返回code,然后使用code跳转,然后访问token接口获取token,以后的全部请求只需要带token即可访问。
需要注意的是code使用一次后即废弃。
(1)请求 http://127.0.0.1:18001/auth/login
参数:
sername: xxx
password: xxx
登录
(2)请求
http://127.0.0.1:xx/auth/oauth/authorize?response_type=code&client_id=xxxredirect_uri=http://127.0.0.1:8080
参数:
response_type: code
client_id: xxx
redirect_uri: http://127.0.0.1:8080
获取code
(3)请求
http://127.0.0.1:xx/?code=xxx
参数:
code: xxx
根据code获取跳转页面
(4)请求
http://127.0.0.1:xx/auth/oauth/token
获取token,返回值为带有token的json
以后的请求都带有token 可以通过认证
配置文件
认证与授权
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
加密与解密
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
代码配置
WebSecurityConfig
AuthorizationServerConfig
feign调用没权限解决
@Configuration
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
requestTemplate.header("Authorization", request.getHeader("Authorization"));
}
}