我正在尝试将IdentityServer与Angularjs应用程序一起使用 . 当未经身份验证的用户尝试导航到应用程序的根URL时,Angularjs前端用于调用授权 endpoints . app.config有一个resolve属性,它将生成routeChangeError . 此事件触发重定向到OAuth2授权 endpoints (在我的情况下为IdentityServer,在Asp.Net MVC上运行) .
baseballApp.config(['$routeProvider', '$locationProvider', '$httpProvider', function($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.when('/players', {
resolve: {
auth: function ($q, $rootScope) {
var deferred = $q.defer();
if ($rootScope.token) {
deferred.resolve();
} else {
deferred.reject();
}
return deferred.promise;
}
},
templateUrl: '/FrontEnd/Templates/PlayerList.html',
controller: 'PlayerListController'
});
$routeProvider.otherwise({ redirectTo: '/players' });
var spinnerFunction = function (data, headersGetter) {
if (data) {
$('#spinner').show();
return data;
}
};
$httpProvider.defaults.transformRequest.push(spinnerFunction);
$httpProvider.interceptors.push('authInterceptor');}]).run(['$rootScope', '$location', 'authenticationService', function ($rootScope, $location, authenticationService) {
//authenticationService.getBearerToken().then(function(data) {
// $rootScope.token = data;
//});
debugger;
var generateRandomString = function() {
return (Math.random().toString(16) + "000000000").substr(2, 8);
}
var nonce = generateRandomString();
var state = generateRandomString();
$rootScope.$on('$routeChangeError', function () {
window.location = 'https://localhost:44301/identity/connect/authorize?client_id=baseballStats&redirect_uri=https%3a%2f%2flocalhost%3a44300%2f&response_type=id_token+token&scope=openid+profile+roles+baseballStatsApi&nonce=' + nonce + '&state=' + state;
});}]);
正如您所看到的,如果我没有令牌,我会重定向到授权 endpoints . 但是,在我登录授权 endpoints 后,我不清楚如何检索令牌 .
我已经指定了一个返回URL,并且在登录后它会重定向到应用程序,但是如何设置我的角度代码来检索应该在Authorize endpoints 上生成并发送回应用程序的令牌?
我见过很多人使用角度承载令牌认证的例子,但我没有看到有人使用Angular的OAuth2服务器的授权 endpoints . 在MVC中,有许多内置的回调来检索令牌 . 我正在寻找关于如何在角度中实现这一点的一些想法 .
能不能给我一个关于我做错的提示?
编辑
我还尝试在重定向uri中传递哈希导航标记,但从IdentityServer获取“错误未知客户端” . 请参阅下面的代码
$rootScope.$on('$routeChangeError', function () {
var returnUrl = encodeURIComponent('https://localhost:44300/#/players');
window.location = 'https://localhost:44301/identity/connect/authorize?client_id=baseballStats&redirect_uri=' + returnUrl + '&response_type=id_token+token&scope=openid+profile+roles+baseballStatsApi&nonce=' + nonce + '&state=' + state;
});
谁知道为什么?
2 回答
我假设您正在为spa js应用程序使用隐式流程授予?
在这种情况下,身份服务器在您登录后,会将访问令牌发送回您的spa应用程序的回拨URL . 使用该回调页面,您可以捕获到令牌,以便将其作为承载令牌传递到授权标头内的资源服务器 .
从Brock Allen查看此视频,非常好解释:https://vimeo.com/131636653
顺便说一下,你应该使用由Brock自己编写的oidc-token-manager . 它非常易于使用,它抽象了与身份服务器的所有通信 . 它也可以在凉亭上使用,因此您可以从那里抓取它 .
最后,我想指出我最近一直在努力的我自己的spa角度应用程序:https://github.com/GeertHuls/SecuredApi .
它实际上使用令牌管理器来获取访问令牌,自动刷新它们以在整个角度应用程序中公开它们 .
希望这会激发你一点点,以便将它与角度融为一体 .
我通过创建一个自定义ActionResult回避了这个问题,当用户已经通过.NET Auth cookie登录时,它会返回带有令牌的JSON响应,它有点像hacky,看起来像这样;