前言
之前文章講到如何使用Node.js+Express構建JavaScript客戶端,實現前后端分離。本節將介紹如何使用Vue實現前后端分離,文中介紹Vue的知識比較基礎,適合新手學習。
一、搭建Vue項目
前提條件:安裝nodejs、webpack和vue-cli。這個網上很多教程,這里不多說。
(1)新建Vue項目
Cmd進入創建項目的路徑,輸入:vue init webpack VueJS_Client
新建vuejs_client的Vue項目,安裝npm。
(2)安裝oidc-client庫
使用VSCode打開vuejs_client項目所在的文件夾
Ctrl + ~ 打開控制控制台,輸入:npm install oidc-client
(3)實現自動跳轉登錄頁面
在src文件夾中打開HelloWorld.vue文件,導入oidc-client模塊,若在未登錄情況,在組件創建前跳轉登錄頁面。代碼很簡單,直接調用登錄函數。
<template></template> <script> import Oidc from "oidc-client"; var config = { authority: "http://localhost:5000", client_id: "js", redirect_uri: "http://localhost:5003/CallBack", response_type: "id_token token", scope: "openid profile api1", post_logout_redirect_uri: "http://localhost:5003/" }; var mgr = new Oidc.UserManager(config); export default { beforeCreate() { mgr.signinRedirect(); } }; </script>
(4)指定重定向頁面
可以看到上面的配置,一旦用戶登錄到IdentityServer,CallBack就是指定的redirect_uri頁面。
在components文件夾中新建CallBack.vue文件,調用UserManager函數,實現頁面跳轉。
<template> </template> <script> import Oidc from "oidc-client"; new Oidc.UserManager() .signinRedirectCallback() .then(function() { window.location = "/#/Home"; }) .catch(function(e) { }); export default{} </script>
(5)編寫Home組件
在CallBack中,重定向了Home組件,此時可以獲取到登錄用戶的屬性和調用接口所需的access_token等。
<template> <div> <button @click="api">調用API</button> <button @click="logout">退出登錄</button> <pre>{{res}}</pre> </div> </template> <script> import Oidc from "oidc-client"; var config = { authority: "http://localhost:5000", client_id: "js", redirect_uri: "http://localhost:5003/CallBack", response_type: "id_token token", scope: "openid profile api1", post_logout_redirect_uri: "http://localhost:5003/" }; var mgr = new Oidc.UserManager(config); export default { name: "Home", data() { return { res: "My Home" }; }, methods: { api() { var that=this; mgr.getUser().then(function(user) { var url = "http://localhost:5001/identity"; var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.onload = function() { that.res = (xhr.status, JSON.parse(xhr.responseText)) }; xhr.setRequestHeader("Authorization", "Bearer " + user.access_token); xhr.send(); }); }, logout() { mgr.signoutRedirect(); } }, mounted() { var that=this; mgr.getUser().then(function(user) { if (user) { // this.res = ("User logged in", user.profile);注意閉包 that.res = ("User logged in", user.profile); } else { that.res = ("User not logged in"); } }); } }; </script> <style scoped> </style>
(6)最后,在Router中添加新建的路由並修改程序啟動端口為5003
二、修改授權服務配置,資源服務器允許跨域調用API
(1)修改授權服務配置
在AuthServer項目,打開Config.cs文件,在GetClients中添加JavaScript客戶端配置
// JavaScript Client new Client { ClientId = "js", ClientName = "JavaScript Client", AllowedGrantTypes = GrantTypes.Implicit, AllowAccessTokensViaBrowser = true, RedirectUris = { "http://localhost:5003/CallBack" }, PostLogoutRedirectUris = { "http://localhost:5003 " }, AllowedCorsOrigins = { "http://localhost:5003" }, AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, "api1" }, }
(2)在資源服務配置允許跨域調用api
在ResourceAPI項目,打開Startup.cs文件中的ConfigureServices方法,配置CORS,允許Ajax調用從http://localhost:5003調用http://localhost:5001的Web API。
//JS-allow Ajax calls to be made from http://localhost:5003 to http://localhost:5001. services.AddCors(options => { //this defines a CORS policy called "default" options.AddPolicy("default", policy => { policy.WithOrigins("http://localhost:5003") .AllowAnyHeader() .AllowAnyMethod(); }); });
在Configure方法中將CORS中間件添加到管道中
//JS-Add the CORS middleware to the pipeline in Configure: app.UseCors("default");
(3)添加測試用的api接口
添加IdentityController控制器
[Route("[controller]")] public class IdentityController : ControllerBase { [Authorize(Roles ="admin")] [HttpGet] public IActionResult Get() { return new JsonResult(from c in User.Claims select new { c.Type, c.Value }); } }
(4)測試
運行AuthServer項目,運行ResourceAPI項目。
在VSCode終端輸入:npm run dev
打開瀏覽器:http://localhost:5003/ 自動跳轉到登錄頁面
賬號:zhubingjian 密碼:123 登錄。跳轉到Home頁面並獲取到用戶的屬性信息。
調用API,滿足授權條件,成功獲取數據。
總結:
本節代碼盡量簡單化了,並有加太多東西進去。關於IdentityServer4的相關知識和教程,可以看我前面幾篇博客,都有詳細的教程。
授權服務和資源服務源碼地址: https://github.com/Bingjian-Zhu/Mvc-HybridFlow.git
Vue Demo源碼地址:https://github.com/Bingjian-Zhu/Identity_Vue_Client