redirect_uri是问前端要的中转页面
【把自己写的子系统集成到大的门户网站里】
当在门户网站登录后,点击其下某个子系统后应该不需要再次登录才符合实际应用场景。
在门户网站点击后会跳转到redirect_uri页面,前端在此页面要发送请求/tea/othau2/login,后端验证通过后直接返回内容 无需登录
@RequestMapping("/tea/oauth2")
@RestController
@RequiredArgsConstructor
@EnableCountTime
@Slf4j
@EnableGetInputInfo
public class TeacherOAuth2Controller {
private final RestTemplate restTemplate;
@Autowired
private TeacherService teacherService;
@Value("${oauth2.get_token_url}")
private String getTokenUrl;
@Value("${oauth2.analysis_token_url}")
private String analysisTokenUrl;
@Value("${oauth2.client_id}")
private String clientId;
@Value("${oauth2.client_secret}")
private String clientSecret;
@Value("${oauth2.redirect_uri}")
private String redirectUri;
@GetMapping("login")
public R login(@RequestParam("code") String code) {
ResponseEntity<String> tokenResponse = restTemplate.postForEntity(
getTokenUrl + "?" +
"client_id=" + clientId +
"&client_secret=" + clientSecret +
"&tokencode=" + code +
"&grant_type=" + "authorization_code" +
"&redirect_uri=" + redirectUri,
"",
String.class
);
if (!tokenResponse.getStatusCode().is2xxSuccessful()) {
return R.error(tokenResponse.getStatusCode());
}
log.info("token response: {}", tokenResponse.getBody());
JSONObject tokenJson = JSONObject.parseObject(tokenResponse.getBody());
assert tokenJson != null;
if (tokenJson.containsKey("error")) {
return R.error(tokenJson.getString("error"));
}
String accessToken = tokenJson.getString("access_token");
ResponseEntity<String> userResponse = restTemplate.getForEntity(
analysisTokenUrl + "?" +
"access_token=" + accessToken,
String.class
);
log.info("user response: {}", userResponse.getBody());
JSONObject userJson = JSONObject.parseObject(userResponse.getBody());
assert userJson != null;
if (userJson.containsKey("error_description")) {
return R.error(userJson.getString("error_description"));
}
// String username = userJson.getString("username");
String phone = userJson.getString("mobile");
// log.info("username: {}", username);
log.info("phone: {}", phone);
// User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
LambdaQueryWrapper<Teacher> w = new LambdaQueryWrapper<>();
// w.eq(Teacher::getPhone,username);
w.eq(Teacher::getPhone,phone);
Teacher teacher = teacherService.getOne(w);
if (teacher == null) {
return R.error("用户不存在!");
}
Object roleList = getRoleList(teacher);//这里是之前写的用于正常账号密码登录时所返回的内容
return R.ok().message("登录成功").data("roleList",roleList);
}