Commit 0db799cd authored by zhangjianqian's avatar zhangjianqian

集成门户一键登录

parent 3943b972
package com.zehong.web.controller.api;
import com.alibaba.fastjson.JSONObject;
import com.zehong.common.core.domain.AjaxResult;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/getout")
public class OutController {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class);
/**
* 返回成功状态码
*/
private static final int SUCCESS_CODE = 200;
@GetMapping(value = "/{token}")
public AjaxResult getindex(@PathVariable String token) throws Exception{
String accessKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3Z0cqRQ8HtDnuTy1bEow" +
"XUZD8yG6aXW/nSIMoCLJGD0MMJpx/1SokTksPeJdUDrPZpDk+DJAohEtO2JjOuTj" +
"1DPMEhSPYnyogNumECnxCL5t/cnVNaPCIdHvQjXT4McvICys7eqw1gJ64I9vM1jx" +
"yIBEiSMurU84c3XAlPwoXHDtNmEIT91vZr+zSfXpGog9SIOP68oBFX+U98WgVUSY" +
"w9icXlDByjVJhBK/7vpa8rkT8psgxSrDpiOpUx2aQQo45vuPGgk1mJUXW/PfE9wD" +
"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EA5MJOjk9TXn7RZXFTiizgMNJMQsKg0KPG" +
"vP0NwnHskialL8vnefknMXfTNhGjV2krCppj00efEhfE+S7shZ4mil7PRWoH/YET" +
"uLTbhHmy6ZhcMigJWSjHO3sWKaaR406So2lWSfSluw6XsK27Cj3f3+tKQC7GgxuX" +
"QS27bekM1/MCgYAicoh1Wn/zhqUdReDVkWU8BIwrHTPKKnX6oBi/Al392JqHvNUI" +
"sn1HrMGT0KORs0dTYvKVuotIlH806AM7IlGZUb4dr2uZR3ImYo/o7sY5rsFqDFJs" +
"hycHqjsHgYl+oUvWzue/4SkpZDDbVeaqhLPqrWlvBuX+cpI5tHT2LroeeQKBgQDR" +
"VY4VZDniSyLLNb1AwHgXtRncLcaDppuC7f7dZOsbgwm+h1U3pOxctE4vOEzE/JRK" +
"i6W1/eBu6hlx/aKrU2HpVYFPAAx3ytqFN9t5ivRSFv6nV0PWtx46LBTH4Im3/Hrr" +
"1sUDwEC4wE3He/OhF6X6fpHf0e4Oo/zxxCu0FIOQSQKBgQDLm4jfsykntDeViy/W" +
"KzxnhMStIyEhRAJT66aveX1R6k11lTlO3aArTzfiaHiDne6R/4LTfWuHq7gyy84E" +
"NFJBb7kGe1c2zOIFQ/wuVyA7KR6aN6YeTdJHYhV7RsHH4vLfwb0SBqEtBePqxKkV" +
"xznrDUoIkeDx0+R/fD8uMNnRRQ==";
// 10 位随机字符串
String randomStr = randomstring(10);
// 获取当前时间戳
String timeStamp = String.valueOf(System.currentTimeMillis());
String data = String.format("%s%s%s", accessKey, randomStr, timeStamp);
String signMsg = "";
try {
byte[] keyBytes = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(key);
signature.update(data.getBytes(StandardCharsets.UTF_8));
signMsg = Base64.getEncoder().encodeToString(signature.sign());
} catch (Exception e) {
e.printStackTrace();
}
// 打印结果
System.out.println("x-access-key = " + accessKey);
System.out.println("x-random-str = " + randomStr);
System.out.println("x-time-stamp = " + timeStamp);
System.out.println("x-access-sign = " + signMsg);
Map<String,Object> map = new HashMap<>();
map.put("x-access-key" , accessKey);
map.put("x-random-str" , randomStr);
map.put("x-time-stamp" , timeStamp);
map.put("x-access-sign" , signMsg);
String a = sendPostJson("",map,token);
return AjaxResult.success(a);
}
public String sendPostJson(String url, Map<String,Object> map, String token) throws Exception{
url = "http://61.240.155.30:30539/uni/uniauth/auth/getUserInfoByTicket?ticket="+token;
JSONObject jsonObject = null;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
/**
* 创建一个httpclient对象
*/
client = HttpClients.createDefault();
/**
* 创建一个post对象
*/
HttpGet post = new HttpGet(url);
/**
* 设置请求的报文头部的编码
*/
//post.setHeader(new BasicHeader("Content-Type", "application/json; charset=utf-8"));
/**
* 设置请求的报文头部的编码
*/
post.setHeader(new BasicHeader("x-access-key", (String) map.get("accessKey")));
post.setHeader(new BasicHeader("x-random-str", (String) map.get("randomStr")));
post.setHeader(new BasicHeader("x-time-stamp", (String) map.get("timeStamp")));
post.setHeader(new BasicHeader("x-access-sign", (String) map.get("signMsg")));
/**
* 执行post请求
*/
response = client.execute(post);
/**
* 获取响应码
*/
int statusCode = response.getStatusLine().getStatusCode();
if (SUCCESS_CODE == statusCode){
/**
* 通过EntityUitls获取返回内容
*/
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
/**
* 转换成json,根据合法性返回json或者字符串
*/
try{
jsonObject = (JSONObject) com.alibaba.fastjson.JSONObject.parseObject(result);
Map<String,Object> usermap = (Map<String,Object>)jsonObject.get("result");
return (String) usermap.get("tel");
}catch (Exception e){
return result;
}
}else{
LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");
}
}catch (Exception e){
LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);
}finally {
response.close();
client.close();
}
return null;
}
public String randomstring(int num){
String str ="";
// 获取0到n之间的随机整数
int n = 9; // 上限值
for(int i=0;i<num;i++){
str =str+(int)(Math.random() * n);
}
return str;
}
}
......@@ -98,7 +98,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
// 过滤请求
.authorizeRequests()
// 对于登录login 验证码captchaImage 允许匿名访问
.antMatchers("/login", "/captchaImage","/websocket/**","/websocketServer", "/detector/detectorReport/**").anonymous()
.antMatchers("/login", "/captchaImage","/websocket/**","/websocketServer", "/detector/detectorReport/**","/getout/**").anonymous()
.antMatchers(
HttpMethod.GET,
"/*.html",
......@@ -153,7 +153,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
*/
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/static/**","/index.html","/login");
web.ignoring().antMatchers("/static/**","/index.html","/login","/onelogin");
}
}
......@@ -37,8 +37,11 @@ public class UserDetailsServiceImpl implements UserDetailsService
if(username.length()>4&&username.substring(0,4).equals("APP_")){//小程序登录标记
user = userService.selectXunjianByUserName(username.substring(4));
username = username.substring(4);
}if(username.length()>4&&username.substring(0,4).equals("ONE_")){
user = userService.selectUserByUserName(username.substring(4));
user.setPassword("$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2");
}else {
user = userService.selectUserByUserName(username);;
user = userService.selectUserByUserName(username);
}
//SysUser user = userService.selectUserByUserName(username);
if (StringUtils.isNull(user))
......
......@@ -37,4 +37,15 @@ export function getCodeImg() {
url: '/captchaImage',
method: 'get'
})
}
\ No newline at end of file
}
export function outlogin(token) {
return request({
url: '/getout/'+token,
headers: {
isToken: false
},
method: 'get',
})
}
......@@ -7,7 +7,7 @@ import { getToken } from "@/utils/auth";
NProgress.configure({ showSpinner: false });
const whiteList = ["/login", "/auth-redirect", "/bind", "/register"];
const whiteList = ["/login", "/auth-redirect", "/bind", "/register","/outindex"];
// 路由前置守卫
router.beforeEach((to, from, next) => {
......
......@@ -59,6 +59,11 @@ export const constantRoutes = [
component: (resolve) => require(['@/views/bigWindow'], resolve),
hidden: true
},
{
path: '/outindex',
component: (resolve) => require(['@/views/onelogin'], resolve),
hidden: true
},
{
path: '',
component: Layout,
......
<template>
<div class="login" v-show="false">
<el-form
ref="loginForm"
:model="loginForm"
:rules="loginRules"
class="login-form"
>
<h3 class="title">智慧燃气后台管理系统</h3>
<el-form-item prop="username">
<el-input
v-model="loginForm.username"
type="text"
auto-complete="off"
placeholder="账号"
>
<svg-icon
slot="prefix"
icon-class="user"
class="el-input__icon input-icon"
/>
</el-input>
</el-form-item>
<el-form-item prop="password">
<el-input
v-model="loginForm.password"
type="password"
auto-complete="off"
placeholder="密码"
@keyup.enter.native="handleLogin"
>
<svg-icon
slot="prefix"
icon-class="password"
class="el-input__icon input-icon"
/>
</el-input>
</el-form-item>
<!--<el-form-item prop="code">-->
<!--<el-input-->
<!--v-model="loginForm.code"-->
<!--auto-complete="off"-->
<!--placeholder="验证码"-->
<!--style="width: 63%"-->
<!--@keyup.enter.native="handleLogin"-->
<!--&gt;-->
<!--<svg-icon-->
<!--slot="prefix"-->
<!--icon-class="validCode"-->
<!--class="el-input__icon input-icon"-->
<!--/>-->
<!--</el-input>-->
<!--<div class="login-code">-->
<!--<img :src="codeUrl" @click="getCode" class="login-code-img" />-->
<!--</div>-->
<!--</el-form-item>-->
<!--<el-checkbox-->
<!--v-model="loginForm.rememberMe"-->
<!--style="margin: 0px 0px 25px 0px"-->
<!--&gt;记住密码</el-checkbox-->
<!--&gt;-->
<el-form-item style="width: 100%">
<el-button
:loading="loading"
size="medium"
type="primary"
style="width: 100%"
@click.native.prevent="handleLogin"
>
<span v-if="!loading">登 录</span>
<span v-else>登 录 中...</span>
</el-button>
</el-form-item>
</el-form>
<!-- 底部 -->
<div class="el-login-footer">
<span> </span>
</div>
</div>
</template>
<script>
import { getCodeImg,getInfo ,outlogin} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import axios from 'axios'
export default {
name: "Login",
data() {
return {
codeUrl: "",
cookiePassword: "",
loginForm: {
username: "",
password: "",
rememberMe: false,
code: "",
uuid: "",
},
loginRules: {
username: [
{ required: true, trigger: "blur", message: "用户名不能为空" },
],
password: [
{ required: true, trigger: "blur", message: "密码不能为空" },
],
code: [
{ required: true, trigger: "change", message: "验证码不能为空" },
],
},
loading: true,
redirect: undefined,
};
},
watch: {
$route: {
handler: function (route) {
this.redirect = route.query && route.query.redirect;
},
immediate: true,
},
},
created() {
this.getphone()
// var url = "http://localhost:8905/gassafety/getout"
// axios({
// method: 'get',
// url: url,
// responseType: 'blob',
// headers: {
// "Content-Type":"application/json"
// }
// }).then(res => {
// console.log(res);
// this.getphone(res.data)
// })
// if(paramValue!=null&&paramValue!=undefined){
// this.loginForm.username = paramValue
// this.loginForm.password = "admin123"
// this.loginForm.code = -1;
// this.$store
// .dispatch("Login", this.loginForm)
// .then((res) => {
// console.log("登录", res);
// // 获取权限
// return getInfo();
// })
// .then((res) => {
// const roles = res.user.deptId;
// let path = "/";
// // 如果是最高权限,就进入大屏
// if (roles == -2) {
// path = "/bigWindow";
// }
// this.$router.push({ path }).catch(() => {});
// })
//
// }else{
// this.getCode();
// this.getCookie();
// }
},
methods: {
getphone(map){
const urlParams = new URLSearchParams(window.location.search);
const paramValue = urlParams.get('ticket');
console.log(paramValue)
outlogin(paramValue).then(res => {
console.log(res);
this.togologin("ONE_"+res.msg)
});
//var url = "http://localhost:8905/gassafety/getout/"+paramValue
// axios({
// method: 'get',
// url: url,
//
// }).then(res => {
// console.log(res)
// if(res.data.code==200){
//
// this.togologin("ONE_"+res.data.msg)
// }
// })
},
togologin(username){
this.loginForm.username = username
this.loginForm.password = "admin123"
this.loginForm.code = -1;
this.$store
.dispatch("Login", this.loginForm)
.then((res) => {
console.log("登录", res);
// 获取权限
return getInfo();
})
.then((res) => {
const roles = res.user.deptId;
let path = "/";
// 如果是最高权限,就进入大屏
if (roles == -2) {
path = "/bigWindow";
}
this.$router.push({ path }).catch(() => {});
})
},
getCode() {
getCodeImg().then((res) => {
this.codeUrl = "data:image/gif;base64," + res.img;
this.loginForm.uuid = res.uuid;
});
},
getCookie() {
const username = Cookies.get("username");
const password = Cookies.get("password");
const rememberMe = Cookies.get("rememberMe");
this.loginForm = {
username: username === undefined ? this.loginForm.username : username,
password:
password === undefined ? this.loginForm.password : decrypt(password),
rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
};
},
handleLogin() {
this.$refs.loginForm.validate((valid) => {
if (valid) {
this.loading = true;
if (this.loginForm.rememberMe) {
Cookies.set("username", this.loginForm.username, { expires: 30 });
Cookies.set("password", encrypt(this.loginForm.password), {
expires: 30,
});
Cookies.set("rememberMe", this.loginForm.rememberMe, {
expires: 30,
});
} else {
Cookies.remove("username");
Cookies.remove("password");
Cookies.remove("rememberMe");
}
this.$store
.dispatch("Login", this.loginForm)
.then((res) => {
console.log("登录", res);
// 获取权限
return getInfo();
})
.then((res) => {
const roles = res.user.deptId;
let path = "/";
// 如果是最高权限,就进入大屏
if (roles == -2) {
path = "/bigWindow";
}
this.$router.push({ path }).catch(() => {});
})
.catch(() => {
this.loading = false;
this.getCode();
});
}
});
},
},
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.login {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
background-image: url("../assets/images/login-background.jpg");
background-size: cover;
}
.title {
margin: 0px auto 30px auto;
text-align: center;
color: #707070;
}
.login-form {
border-radius: 6px;
background: #ffffff;
width: 400px;
padding: 25px 25px 5px 25px;
.el-input {
height: 38px;
input {
height: 38px;
}
}
.input-icon {
height: 39px;
width: 14px;
margin-left: 2px;
}
}
.login-tip {
font-size: 13px;
text-align: center;
color: #bfbfbf;
}
.login-code {
width: 33%;
height: 38px;
float: right;
img {
cursor: pointer;
vertical-align: middle;
}
}
.el-login-footer {
height: 40px;
line-height: 40px;
position: fixed;
bottom: 0;
width: 100%;
text-align: center;
color: #fff;
font-family: Arial;
font-size: 12px;
letter-spacing: 1px;
}
.login-code-img {
height: 38px;
}
</style>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment