#默认用Mysql数据库,如需用其他数据库请修改配置文件以及数据库驱动
#创建数据库SQL:数据库名、数据库用户名、数据库密码需要和application.properties中的一致
CREATE DATABASE IF NOT EXISTS oauth2_server DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
create user 'oauth2_server'@'localhost' identified by 'password_dev';
grant all privileges on oauth2_server.* to 'oauth2_server'@'localhost';
#初始化数据sql在src/main/resources/sql/init.sql,可自行修改client_id等初始化数据
authorization_code,implicit,password,client_credentials;
- authorization_code模式:用于PC端,页面跳转,安全性最高,需要两步获取token
1. Get /oauth/authorize?client_id=SampleClientId&response_type=code&redirect_uri=http://client.sso.com/login/oauth2/code/sso-login
用户同意授权后服务端响应,浏览器重定向到:http://client.sso.com/login?code=1E37Xk,接收code,然后后端调用步骤2获取token
2. Post /oauth/token?client_id=SampleClientId&client_secret=tgb.258&grant_type=authorization_code&redirect_uri=http://client.sso.com/login/oauth2/code/sso-login&code=1E37Xk
响应:
{
"access_token": "a.b.c",
"token_type": "bearer",
"refresh_token": "d.e.f",
"expires_in": 43199,
"scope": "read",
"userId": "1",
"jti": "823cdd71-4732-4f9d-b949-a37ceb4488a4"
}
- password模式:用于手机端或者其他无页面跳转场景,应由后台服务端调用,保护client_id和client_secret
Post /oauth/token?client_id=SampleClientId&client_secret=tgb.258&grant_type=password&scope=read&username=zhangsan&password=tgb.258
响应:
{
"access_token": "a.b.c",
"token_type": "bearer",
"refresh_token": "d.e.f",
"expires_in": 43199,
"scope": "read",
"userId": "1",
"jti": "823cdd71-4732-4f9d-b949-a37ceb4488a4"
}
使用Java工具包中的keytool制作证书jwt.jks,设置别名为【jwt】,密码为【keypass】,替换位置src/main/resources/jwt.jks
keytool -genkey -alias jwt -keyalg RSA -keysize 1024 -keystore jwt.jks -validity 3650
Get /oauth/token_key
Get /.well-known/jwks.json
Post /oauth/check_token?token=a.b.c
Get /user/me?access_token=a.b.c
或者http header中加入Authorization,如下
Authorization: Bearer a.b.c
Post /oauth/token?client_id=SampleClientId&client_secret=tgb.258&grant_type=refresh_token&refresh_token=d.e.f
Post /oauth/signUp?username=lisi&password=yourpass&client_id=SampleClientId&client_secret=tgb.258
java -jar oauth2-server-0.0.1-SNAPSHOT.jar
或者指定配置文件覆盖默认配置
java -jar oauth2-server-0.0.1-SNAPSHOT.jar --spring.config.additional-location=/path/to/override.properties
spring-security-oauth官方文档
Spring Boot and OAuth2 Tutorial
- 扩展grant_type待续
- 分布式支持
当Server和Client在一台机器上时,请配置域名代理,避免cookie相互覆盖