Cor*_*eus 14 azure node.js azure-active-directory vue.js vuejs2
我正在使用VueJS 2.x框架设置应用程序,它需要通过Azure Active Directory服务对用户进行身份验证.我已经拥有该服务的"登录信息"(Auth和令牌URL).
到目前为止,我只遇到过一篇文章,显示了VueJS中的设置,但它依赖于第三方服务(Auth0) - 在此过程中添加了不必要的卷积.
当没有任何VueJS npm模块允许轻松进行身份验证时,如何继续?或者您是否必须依赖Vue之外的图书馆,如Adal JS?
任何的意见都将会有帮助.
mat*_*son 15
为了解决这个问题,我倾向于使用ADAL JS.我做了一个Vue公司+ Vue公司-路由器示例应用程序可在这里 -但我会包括以下重要棋子.
"dependencies": {
"adal-angular": "^1.0.15",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
Run Code Online (Sandbox Code Playgroud)
import AuthenticationContext from 'adal-angular/lib/adal.js'
const config = {
tenant: 'your aad tenant',
clientId: 'your aad application client id',
redirectUri: 'base uri for this application',
cacheLocation: 'localStorage'
};
export default {
authenticationContext: null,
/**
* @return {Promise}
*/
initialize() {
this.authenticationContext = new AuthenticationContext(config);
return new Promise((resolve, reject) => {
if (this.authenticationContext.isCallback(window.location.hash) || window.self !== window.top) {
// redirect to the location specified in the url params.
this.authenticationContext.handleWindowCallback();
}
else {
// try pull the user out of local storage
let user = this.authenticationContext.getCachedUser();
if (user) {
resolve();
}
else {
// no user at all - go sign in.
this.signIn();
}
}
});
},
/**
* @return {Promise.<String>} A promise that resolves to an ADAL token for resource access
*/
acquireToken() {
return new Promise((resolve, reject) => {
this.authenticationContext.acquireToken('<azure active directory resource id>', (error, token) => {
if (error || !token) {
return reject(error);
} else {
return resolve(token);
}
});
});
},
/**
* Issue an interactive authentication request for the current user and the api resource.
*/
acquireTokenRedirect() {
this.authenticationContext.acquireTokenRedirect('<azure active directory resource id>');
},
/**
* @return {Boolean} Indicates if there is a valid, non-expired access token present in localStorage.
*/
isAuthenticated() {
// getCachedToken will only return a valid, non-expired token.
if (this.authenticationContext.getCachedToken(config.clientId)) { return true; }
return false;
},
/**
* @return An ADAL user profile object.
*/
getUserProfile() {
return this.authenticationContext.getCachedUser().profile;
},
signIn() {
this.authenticationContext.login();
},
signOut() {
this.authenticationContext.logOut();
}
}
Run Code Online (Sandbox Code Playgroud)
import Vue from 'vue'
import App from './App'
import router from './router'
import authentication from './authentication'
// Init adal authentication - then create Vue app.
authentication.initialize().then(_ => {
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
});
});
Run Code Online (Sandbox Code Playgroud)
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import authentication from '../authentication'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
meta: {
requiresAuthentication: true
}
}
]
})
// Global route guard
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuthentication)) {
// this route requires auth, check if logged in
if (authentication.isAuthenticated()) {
// only proceed if authenticated.
next();
} else {
authentication.signIn();
}
} else {
next();
}
});
export default router;
Run Code Online (Sandbox Code Playgroud)
import authentication from './authentication'
...
computed: {
isAuthenticated() {
return authentication.isAuthenticated();
}
},
methods: {
logOut() {
authentication.signOut();
}
}
Run Code Online (Sandbox Code Playgroud)
以下是vue-resource http拦截器的示例,但任何方法都可以.
Vue.http.interceptors.push(function (request, next) {
auth.acquireToken().then(token => {
// Set default request headers for every request
request.headers.set('Content-Type', 'application/json');
request.headers.set('Ocp-Apim-Subscription-Key', 'api key');
request.headers.set('Authorization', 'Bearer ' + token)
// continue to next interceptor
next();
});
});
Run Code Online (Sandbox Code Playgroud)
希望这能节省一些时间:)
我不确定是否有一个库可以帮助确保 Vue 应用程序的安全性。但是,我们可以轻松利用 Adal.js 进行身份验证。
我写了一个简单的demo供大家参考:
索引.html:
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<script src="node_modules\adal-angular\lib\adal.js"></script>
<script src="config.js"></script>
<script>
var authContext = new AuthenticationContext(config);
function login() {
authContext.login();
}
function init(configOptions) {
if (configOptions) {
// redirect and logout_redirect are set to current location by default
var existingHash = window.location.hash;
var pathDefault = window.location.href;
if (existingHash) {
pathDefault = pathDefault.replace(existingHash, "");
}
configOptions.redirectUri = configOptions.redirectUri || pathDefault;
configOptions.postLogoutRedirectUri =
configOptions.postLogoutRedirectUri || pathDefault;
// create instance with given config
} else {
throw new Error("You must set configOptions, when calling init");
}
// loginresource is used to set authenticated status
updateDataFromCache(authContext.config.loginResource);
}
var _oauthData = {
isAuthenticated: false,
userName: "",
loginError: "",
profile: ""
};
var updateDataFromCache = function(resource) {
// only cache lookup here to not interrupt with events
var token = authContext.getCachedToken(resource);
_oauthData.isAuthenticated = token !== null && token.length > 0;
var user = authContext.getCachedUser() || { userName: "" };
_oauthData.userName = user.userName;
_oauthData.profile = user.profile;
_oauthData.loginError = authContext.getLoginError();
};
function saveTokenFromHash() {
var hash = window.location.hash;
var requestInfo = authContext.getRequestInfo(hash);
if (authContext.isCallback(hash)) {
// callback can come from login or iframe request
var requestInfo = authContext.getRequestInfo(hash);
authContext.saveTokenFromHash(requestInfo);
window.location.hash = "";
if (requestInfo.requestType !== authContext.REQUEST_TYPE.LOGIN) {
authContext.callback = window.parent.AuthenticationContext().callback;
}
}
}
function isAuthenticate() {
return _oauthData.isAuthenticated;
}
saveTokenFromHash();
init(config);
</script>
</head>
<body>
<div id="app">
<p v-if="_oauthData.isAuthenticated">Hello {{ oauthData.userName }}</p>
<button onclick="login()" v-else>Login</button>
</div>
<script>
var app = new Vue({
el: "#app",
data: {
oauthData: _oauthData
}
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
配置文件:
var config = {
tenant: 'xxx.onmicrosoft.com',
clientId: '',
redirectUri: '',
cacheLocation: 'localStorage'
};
Run Code Online (Sandbox Code Playgroud)
免责声明:我是这个插件的作者。
通过npm 使用vue-adal:
npm install vue-adal
Run Code Online (Sandbox Code Playgroud)
基本用法
import Adal from 'vue-adal'
Vue.use(Adal, {
// This config gets passed along to Adal, so all settings available to adal can be used here.
config: {
// 'common' (multi-tenant gateway) or Azure AD Tenant ID
tenant: '<guid>',
// Application ID
clientId: '<guid>',
// Host URI
redirectUri: '<host addr>',
cacheLocation: 'localStorage'
},
// Set this to true for authentication on startup
requireAuthOnInitialize: true,
// Pass a vue-router object in to add route hooks with authentication and role checking
router: router
})
```
Run Code Online (Sandbox Code Playgroud)
重要提示:请确保将路由器上的模式设置为“历史记录”,以免使用哈希!这将对服务器端产生影响。
new Router({
mode: 'history', // Required for Adal library
... // Rest of router init
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9043 次 |
| 最近记录: |