登录实现
拿浏览器网页登录举例:

基于 OAuth2.0-密码模式 实现网页登录的本质就是浏览器通过 /oauth/token 接口将 用户名 和 密码 等信息传给后台, 然后后台验证通过后返回一个有效的 token 给浏览器.

通过 curl 命令发送请求

请求头 Authorization 存放的是 clientId 和 secret 经过 Base64 编码后的结果

请求参数包括用户名(username)、密码(password)、授权模式(grant_type).

curl --location --request
POST 'http://localhost:8101/oauth/token?username=zhangsan&password=123456&grant_type=password \
--header 'Authorization: Basic bmltbzE6MTIzNDU2'

响应内容

{
"scope": "[all, read, write]",
"code": 0,
"access_token": "7e1d19dd-5cef-4993-a1c3-c35aa53d9b29",
"token_type": "bearer",
"refresh_token": "992518eb-4357-4283-8673-a9ca96ad2a9e",
"expires_in": 7199
}
问题
如果我们想把登录接口命名为 /login, 该怎么办?

方法一
在 AuthorizationServerConfigurerAdapter 配置一个 pathMapping, 把原有的路径给 覆盖 掉.

@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
.pathMapping("/oauth/token","/login"); }
}

方法二
根据上文 源码分析 - Spring Security OAuth2 生成 token 的执行流程 讲的 API , 实现 TokenEndpoint#postAccessToken()方法 的核心逻辑, 重新定义一个 /login 接口.

回顾上文中的一张图:

核心代码如下:

@PostMapping(value = "/login")
@ResponseBody
public String doLogin(
HttpServletRequest request,
String username,
String password) {

// 自定义响应对象
LoginRes res = new LoginRes();

try {
// 对请求头进行 base64 解码, 获取 client id 和 client secret
String[] tokens = CryptUtils.decodeBasicHeader(request.getHeader("Authorization"));
String clientId = tokens[0];
String clientSecret = tokens[1];

// 通过 clientId 获取客户端详情
ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);

// 校验 ClientDetails
if (clientDetails == null) {
throw new UnapprovedClientAuthenticationException("Unknown client id : " + clientId);
}

if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) {
throw new UnapprovedClientAuthenticationException("Invalid client secret for client id : " + clientId);
}

// 通过 username 和 password 构建一个 Authentication 对象
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(req.getUsername(),
req.getPassword());

// 验证用户信息
Authentication auth = authenticationManager.authenticate(authRequest);
// 放入 Secirty 的上下文
SecurityContextHolder.getContext().setAuthentication(auth);

// 通过 Client 信息和 请求参数, 获取一个 TokenRequest 对象
TokenRequest tokenRequest = new TokenRequest(new HashMap<String, String>(), clientId,
clientDetails.getScope(), "password");

// 通过 TokenRequest 和 ClientDetails 构建 OAuthRequest
OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);

// 通过 OAuth2Request 和 Authentication 构建OAuth2Authentication
OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, auth);

// 通过 OAuth2Authentication 构建 OAuth2AccessToken
OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);

// 把 token 信息封装到 自定义的响应对象中
res.setAccessToken(token.getValue());
res.setTokenType(token.getTokenType());
res.setRefreshToken(token.getRefreshToken().getValue());
res.setExpiresIn(token.getExpiresIn());
res.setScope(token.getScope().toString());

} catch (Exception e) {
log.warn("Fail to login of user {} for {}", req.getUsername(), e.getMessage());
}
return JsonUtil.toJsonString(res);
}

Spring Security OAuth2 - 自定义 OAuth2.0 令牌发放接口地址的更多相关文章

  1. IdentityServer4源码解析_4_令牌发放接口

    目录 identityserver4源码解析_1_项目结构 identityserver4源码解析_2_元数据接口 identityserver4源码解析_3_认证接口 identityserver4 ...

  2. Spring Security Oauth2 自定义 OAuth2 Exception

    付出就要得到回报,这种想法是错的. 前言 在使用Spring Security Oauth2登录和鉴权失败时,默认返回的异常信息如下 { "error": "unauth ...

  3. 朱晔和你聊Spring系列S1E10:强大且复杂的Spring Security(含OAuth2三角色+三模式完整例子)

    Spring Security功能多,组件抽象程度高,配置方式多样,导致了Spring Security强大且复杂的特性.Spring Security的学习成本几乎是Spring家族中最高的,Spr ...

  4. spring security使用自定义登录界面后,不能返回到之前的请求界面的问题

    昨天因为集成spring security oauth2,所以对之前spring security的配置进行了一些修改,然后就导致登录后不能正确跳转回被拦截的页面,而是返回到localhost根目录. ...

  5. spring security 3 自定义认证,授权示例

    1,建一个web project,并导入所有需要的lib. 2,配置web.xml,使用Spring的机制装载: <?xml version="1.0" encoding=& ...

  6. spring security采用自定义登录页和退出功能

    更新... 首先采用的是XML配置方式,请先查看  初识Spring security-添加security 在之前的示例中进行代码修改 项目结构如下: 一.修改spring-security.xml ...

  7. 阶段5 3.微服务项目【学成在线】_day16 Spring Security Oauth2_06-SpringSecurityOauth2研究-Oauth2授权码模式-申请令牌

    3.3 Oauth2授权码模式 3.3.1 Oauth2授权模式 Oauth2有以下授权模式: 授权码模式(Authorization Code) 隐式授权模式(Implicit) 密码模式(Reso ...

  8. 阶段5 3.微服务项目【学成在线】_day16 Spring Security Oauth2_07-SpringSecurityOauth2研究-Oauth2授权码模式-资源服务授权测试

    下面要完成  5.6两个步骤 3.3.4 资源服务授权 3.3.4.1 资源服务授权流程 资源服务拥有要访问的受保护资源,客户端携带令牌访问资源服务,如果令牌合法则可成功访问资源服务中的资 源,如下图 ...

  9. 阶段5 3.微服务项目【学成在线】_day16 Spring Security Oauth2_09-SpringSecurityOauth2研究-Oauth2密码模式授权

    密码模式(Resource Owner Password Credentials)与授权码模式的区别是申请令牌不再使用授权码,而是直接 通过用户名和密码即可申请令牌. 测试如下: Post请求:htt ...

  10. spring security 之自定义表单登录源码跟踪

    ​ 上一节我们跟踪了security的默认登录页的源码,可以参考这里:https://www.cnblogs.com/process-h/p/15522267.html 这节我们来看看如何自定义单表认 ...

随机推荐

  1. window使用VNC远程ubuntu16.04

    首先保证在同一局域网下 一.设置Ubuntu 16.04 允许进行远程控制 首先在ubuntu下找到下图图标 将[允许其他人查看您的桌面]这一项勾上,然后在安全那项,勾选[要求远程用户输入此密码],并 ...

  2. 云原生爱好者周刊:非容器化应用也需要 Docker Compose

    开源项目推荐 Process Compose Process Compose 是一个调度编排工具,不过不是用来调度容器的,而是用来调度非容器化的应用,可以定义进程的依赖性和启动顺序,也可以定义重启策略 ...

  3. 用easyVget下载B站油管视频

    B站油管等视频平台简直就是无所不有的宝库,动漫.番剧.纪录片.科普,更有海量的学习资源,可以极大地满足你的视觉欲和求知欲. 作为一只视频仓鼠,我热衷于下载自己感兴趣的视频到本地,不用担心视频被和谐.不 ...

  4. linux 基础(3)基本文件操作

    目录的基本操作 在 linux 文件系统里,以斜杠 / 开头的路径是绝对路径,从根目录开始寻找:其他的路径则都是相对路径,从当前目录(working directory)开始寻找. 相对目录中常用的符 ...

  5. Machine Learning Week_7 Support Vector Machines

    目录 1 Large Margin Classification 1.1 Optimization Objective 1.1 Logistic Regresson 1.2 Cost 1.3 Supp ...

  6. 顺序结构程序设计(python)

    文章目录 1.python运算符 1.1 python算数运算 1.2python比较运算符 1.3 Python赋值运算符 1.4 python逻辑运算符 1.5 python成员运算符 1.6py ...

  7. Docker-compose 常用命令和模板

    docker-compose logs -f ##查看该容器的启动的日志打印(日志从头打印 docker logs -f container_id ##查看某一容器的启动的日志打印(日志从头打印) d ...

  8. Power BI新卡片更改显示单位

    Power BI 不知道什么时候发布了新卡片,照现在官方来说,该视觉对象目前还属于预览版,但已经可以正常使用了,对比旧的卡片,显示效果个人觉得会友好一些,详见官方说明:创建"新"卡 ...

  9. Kriging 模型 —— 克里金法 —— 最优插值

  10. visual studio当中动态库和静态库的联系

    一.为什么要写这篇博客 公司需要调用MNN框架编译之后的动态库和静态库文件来在另外一台没有编译过MNN框架上的机器运行对应的程序,比如说人体关键点检测之类的程序,这个时候了解静态库和动态库的关系就很有 ...