2017-02-03 19 views
0

Итак, еще раз у меня есть tome, чтобы переместиться в Security. И я так сильно хочу понять, как заставить мой AngularJS SPA позвонить на мой API через безопасную среду.Проблемы с OAuth2 Adal Angularjs Web APi функциональность - Web APi не авторизован

То, что я с трудом хватаю, это путь маркера безопасности, который я думаю.

Таким образом, мне удалось защитить мой AngularJS SPA с помощью OAuth2 с помощью одного из руководств Microsoft в руководствах разработчика Azure Active Directory.

GUIDE HERE

теперь я могу войти и стать уполномоченным войти в SPA, но когда я делаю мои звонки в API, где различные конечные точки API имеют тег Авторизовать над ними, я получаю Несанкционированное, желание понятно из курс.

Это приводит меня к моей следующей проблеме. Прежде всего, я, вероятно, не имею ничего, чтобы справиться с авторизацией в моем веб-API, а также как заставить мой API разрешать вызовы из моего AngularJS SPA, когда его конечные точки вызываются или обрабатываются.

Каков следующий шаг и что мне нужно знать, чтобы понять и реализовать правильный поток между/через оба приложения.

______________________UPDATE____________________________

Так я пришел немного дальше. но теперь я получаю 401 несанкционированный доступ, поэтому мой Angular SPA can not проходит через тег авторизации. Я что-то упускаю?

Javacript app.js:

var app = angular.module('app', ['AdalAngular']); 
app.config(['$httpProvider', 'adalAuthenticationServiceProvider', function ($httpProvider, adalProvider) { //$routeProvider, 

    $httpProvider.defaults.withCredentials = true; 

    var endpoints = { 
     "https://localhost:44376/": "http://oauthsolutionadtest.onmicrosoft.com/theapi" 
    }; 

    adalProvider.init(
    { 
     instance: 'https://login.microsoftonline.com/', 
     tenant: 'oauthsolutionadtest.onmicrosoft.com', 
     clientId: 'CLIENT-ID', 
     endpoints: endpoints, 
    }, 
     $httpProvider 
    ); 

}]); 

var sampleController = app.controller("sampleController", ["$scope", "$http", "adalAuthenticationService", function ($scope, $http, adalService) { 

    $scope.login = login; 
    $scope.logout = logout; 
    $scope.onlyAdmin = onlyAdmin; 

    function login(){ 
     adalService.login(); 
    }; 

    function logout(){ 
     adalService.logOut(); 
    }; 

    function onlyAdmin() { 
     alert("INNE_1"); 

    $http.get("https://localhost:44376/api/testmessage") 
     .success(
     function (data, status, headers, config, response) { 
      alert("INNE_2"); 
      $scope.admin = true; 
      console.log(data, status, headers, config, response); 
     }).error(
      function (response) { 
       alert("INNE_3 " + response); 
       console.log(response); 
      } 
     ) 

    } 


}]) 

HTML:

<!DOCTYPE html> 
<html ng-app="app"> 
<head> 
    <title>Sample SPA (AngularJs) And Azure AD</title> 
    <meta charset="utf-8" /> 

    <link href="Content/bootstrap.min.css" rel="stylesheet" /> 
    <link href="Content/toaster.css" rel="stylesheet" /> 
    <link href="Content/loading-bar.min.css" rel="stylesheet" /> 

</head> 
<body ng-controller="sampleController"> 
    <!--<div data-ng-view=""></div>--> 

    <div> 
     <button ng-click="login()" ng-hide="userInfo.isAuthenticated">Login</button> 

     <button ng-click="logout()" ng-show="userInfo.isAuthenticated">Logout</button> 

     <button ng-click="onlyAdmin()"> 
      Admin 
     </button> 

     {{admin}} 

     <pre> 
     {{userInfo}} 
     </pre> 
    </div> 


    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 

    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.13/js/adal.min.js"></script> 
    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.13/js/adal-angular.min.js"></script> 
    <script type="text/javascript" src="App/app.js"></script> 

</body> 
</html> 

WebAPI Контроллер:

using System; 
using System.Configuration; 
using System.Linq; 
using System.Security.Claims; 
using System.Web.Http; 
using System.Web.Http.Cors; 


namespace OAuthSolution.API.Controllers 
{ 
    public class ContactController : ApiController 
    { 


     [Route("api/testmessage")] 
     [HttpGet] 
     [EnableCors(origins: "https://localhost:44311", headers: "*", methods: "GET, POST, OPTIONS", SupportsCredentials =true)] 
     [Authorize] 
     public string testMessage() 
     { 

      return "You got the Test Message"; 
     } 


     [Route("api/theGet")] 
     [HttpGet] 
     [EnableCors(origins: "https://localhost:44311", headers: "*", methods: "*", SupportsCredentials = true)] 
     [Authorize] 
     public IHttpActionResult Get() 
     { 
      var adminGroupId = ConfigurationManager.AppSettings["adminGroupId"]; 

      Claim groupAdmin = ClaimsPrincipal.Current.Claims.FirstOrDefault(x => x.Type == "groups" && x.Value.Equals(adminGroupId, StringComparison.CurrentCultureIgnoreCase)); 

      if(groupAdmin != null) 
      { 
       return Ok("Admin"); 
      } 

      return Unauthorized(); 
     } 
    } 
} 

WebAPI Startup.cs:

/////STARTUP.CS 

using Microsoft.Owin; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using Owin; 
using Microsoft.Owin.Security.ActiveDirectory; 
using System.Configuration; 
using System.Web.Http; 
using Microsoft.Owin.Security.OAuth; 

[assembly: OwinStartup(typeof(OAuthSolution.API.Startup))] 

namespace OAuthSolution.API 
{ 
    public partial class Startup 
    { 
     public void Configuration (IAppBuilder app) 
     { 
      ConfigureAuth(app); 
      app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); 

     } 

     private void ConfigureAuth(IAppBuilder app) 
     { 
      var azureADBearerAuthOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions 
      { 
       Tenant = ConfigurationManager.AppSettings["ida:Tenant"], 
      }; 

      azureADBearerAuthOptions.TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() 
      { 
       ValidAudience = ConfigurationManager.AppSettings["ida:Audience"], 
      }; 

      app.UseWindowsAzureActiveDirectoryBearerAuthentication(azureADBearerAuthOptions); 

     } 
    } 
} 

WebApiConfig.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Http; 
using System.Web.Http.Cors; 

namespace OAuthSolution.API 
{ 
    public static class WebApiConfig 
    { 
     public static void Register(HttpConfiguration config) 
     { 

      // Web API configuration and services 
      config.EnableCors(); 

      // Web API routes 
      config.MapHttpAttributeRoutes(); 

      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 
     } 
    } 
} 

Web.Config: enter image description here

Заголовок: enter image description here

Маркер расшифрованы из jwt.io:

{ 
 
    "typ": "JWT", 
 
    "alg": "RS256", 
 
    "x5t": "Y4ueK2oaINQiQb5YEBSYVyDcpAU", 
 
    "kid": "Y4ueK2oaINQiQb5YEBSYVyDcpAU" 
 
} 
 

 
{ 
 
    "aud": "http://oauthsolutionadtest.onmicrosoft.com/theapi", 
 
    "iss": "https://sts.windows.net/f2f535e0-294f-4704-befc-8ce754f10bd7/", 
 
    "iat": 1486134484, 
 
    "nbf": 1486134484, 
 
    "exp": 1486138384, 
 
    "acr": "1", 
 
    "amr": [ 
 
    "pwd" 
 
    ], 
 
    "appid": "a9d7f295-1c8e-43bc-9600-bdc0bff1d567", 
 
    "appidacr": "0", 
 
    "e_exp": 10800, 
 
    "family_name": "admin", 
 
    "given_name": "admin", 
 
    "groups": [ 
 
    "f929d8fd-e361-473d-8325-6e8d1ccba5a0" 
 
    ], 
 
    "ipaddr": "90.224.252.71", 
 
    "name": "admin", 
 
    "oid": "251df8ba-112b-4c06-af7e-4c0899f0118b", 
 
    "platf": "3", 
 
    "scp": "user_impersonation", 
 
    "sub": "Ih0hL_bmMPuMeYk3R_gEWZZmUteJfL0F1afFhiPYUFU", 
 
    "tid": "f2f535e0-294f-4704-befc-8ce754f10bd7", 
 
    "unique_name": "[email protected]", 
 
    "upn": "[email protected]", 
 
    "ver": "1.0" 
 
}

+0

Является ли ваше Угловое приложение в том же домене, что и API? Какова ваша настройка конфигурации Аудитории, установленная в API? – juunas

+0

Я отправлю еще одно обновление, я думаю, вы хотите получить информацию о web.config? Спасибо за ваш быстрый ответ Юунас. :) – John

+0

@juunas Они находятся на одном компьютере (localHost), но они зарегистрированы в одном и том же лазурном объявлении. если это то, что вы просите. Также в том же решении, если это какая-то помощь. – John

ответ

0

Я думаю, что нашел решение моей проблемы ...

мне пришлось добавить эту строку:

config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 

И это пространство имен:

using Microsoft.Owin.Security.OAuth; 

(также NuGet для этой работы: Microsoft.Owin.Host.SystemWeb)

в мой файл WebApiConfig.cs, внутри метода Register.

Теперь я могу назвать свой API через CORS.

Надеюсь, это поможет кому-то еще.

Также, спасибо за помощь!