Skip to main content

简单实现OAuth2.0

一、开启OAuth2.0

  1. 进入管理员页面进入OAuth2.0配置
  2. 设置域名为127.0.0.1:8080(我的服务就是这个地址)
  3. 记录下来你的重定向URL模版以后有用
  4. 保存 开启/配置OAuth2方法

二、实现免密登录

纯前端实现 (注意这是不安全的行为,仅限于本地开发测试使用)

可以复制代码后直接运行
<html>
<!---->
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<body>
<div>
<button onclick="getToken()">step 1 -> get Token</button>
<button onclick="redirectToDashboard()">step 2 -> login</button>
<span id='token'></span>
</div>
</body>
<script>
let HOST = "https://tb.javabase.cn";
let token = '';
// 登录成功后进行页面跳转
function redirectToDashboard() {
if(token ===''){
alert('先获取token');
return;
}
window.location.href = `${HOST}/login/oauth2/code?accessToken=${token}`;
}

function getToken(){
$('#token').text("正在获取Token.....")
// 发送登录请求
$.ajax({
url: `${HOST}/api/auth/login`,
method: 'POST',
contentType:"application/json",
data: JSON.stringify({
username: 'demo@jb.cn',
password: '123456'
}),
success: function(response) {
$('#token').text(JSON.stringify(response));
token = response.token;
// 登录成功的处理逻辑
//console.log('登录成功');
//redirectToDashboard(); // 跳转到仪表盘页面
},
error: function(error) {
// 登录失败的处理逻辑
console.error('登录失败', error);
}
});
}
</script>
</html>

后端实现

Controller类实现,其它代码省略(这种方式比较安全,但这只是最简单的实现)
/**
* Copyright (c) 2020-2038, Jiangguiqi 齐 (author@tyuan.design).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.demo.thingsboard;

import com.alibaba.fastjson.JSONObject;
import com.demo.utils.HttpClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
* @author jiangguiqi@aliyun.com
* @version 1.0
* @date 2023/7/2 14:57
*/
@Controller
@RequestMapping("/thingsboard")
public class LoginAuthApiTestController {

RestTemplate restTemplate = HttpClient.getHttpClient();

@GetMapping(value = {"", "/"})
public void login(HttpServletResponse response) throws IOException {
Map map = new HashMap();
map.put("username", "demo@jb.cn");
map.put("password", "123456");
ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("http://127.0.0.1:8080/api/auth/login", map, String.class);
String body = stringResponseEntity.getBody();
JSONObject jsonObject = JSONObject.parseObject(body);
response.sendRedirect("http://127.0.0.1:8080/login/oauth2/code?accessToken=" + jsonObject.getString("token"));
return;
}
}

古之欲明德于天下者,先治其国;欲治其国者,先齐其家;欲齐其家者,先修其身;欲修其身者,先正其心,欲正其心者,先诚其意;欲诚其意者,先致其知;致知在格物。——礼记