Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Mobile-Client-Security: Authentifizierung, Auto...

Mobile-Client-Security: Authentifizierung, Autorisierung, Personalisierung

Selbstverständlich müssen wir unsere mobilen Apps – bzw. die dahinter liegenden Web-APIs – absichern. Wenn wir in klassischen Systemen bisher mit "Username/Passwort" in der Anwendung gedacht haben, so müssen wir dies bei modernen Business- und mobilen Apps ändern. In dieser Session zeigen Dominick Baier und Christian Weyer architekturelle Wege und Implementierungen auf, um Authentifizierung und Autorisierung sicher über OAuth-2.0-basierte Ansätze abzuwickeln. Darauf aufbauend sehen Sie auch, wie mit der Idee von Tokens und Claims eine für Benutzer einfache Personalisierbarkeit Ihrer App realisiert werden kann – so schlagen Sie zwei Fliegen mit einer Klappe.

Christian Weyer

February 26, 2014
Tweet

More Decks by Christian Weyer

Other Decks in Programming

Transcript

  1. Agenda • Mobile (web-based) client apps • Classic browser authentication

    • Moving to explicit authentication • OAuth2 Resource owner password flow • OAuth2 Implicit flow • Personalization 2
  2. Mobile client apps • 'Mobile' is not just about devices

    – instead refers to a new way of working without being tied to a desktop in an office – users expect modern business applications to work on multiple devices, at multiple locations, online and offline • Mobile spans the whole stack – from native Windows 8 applications on laptop and tablets – to modern HTML5-based desktop applications – to classic Windows clients developed with WPF – to native applications developed for iPhone, iPad, Android and Windows Phone 3
  3. Web-based single page applications (SPA) • Modern web-based applications are

    “the new smart client” – client assets (markup, styles & code) run in the browser (shell) • Similar features and behavior as a Windows application – page as shell, with views and routing • The client (aka the actions through the client) is untrusted • Native apps can use web view component to leverage security solutions 5
  4. Application (Domain) Authentication Implicit browser authentication • Web APIs share

    security settings of host application – e.g. cookies, Windows/Basic authentication, client certs... Pages Web APIs $.ajax 6
  5. 7

  6. CSRF – the problem Browser Tab/Process Tab/Process Login, get authentication

    cookie http://app.com http://app.com/delete/5 send authentication cookie 8
  7. Anti-CSRF – traditional approach Server [ValidateHttpAntiForgeryToken] render page & anti-forgery

    cookie <form> <input type="hidden" value="anti-forgery token" /> </form> <script>…</script> post-back: cookie + hidden field Page web api call: cookie + header 9
  8. CSRF protection // Configure Web API to use only bearer

    token authentication config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter( OAuthDefaults.AuthenticationType)); WebApiConfig.cs protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { SetCurrentPrincipalToAnonymous(request); return await base.SendAsync(request, cancellationToken); } PassiveAuthenticationMessageHandler.cs 10
  9. Modern application security • Works across any platforms & systems

    – common denominator technologies • Factoring out authentication & authorization – separation of concerns – decoupling of technical details 11
  10. 13

  11. OAuth2 approach Web APIs Authorization Server Scopes: read, write, delete,

    search… client_id=client1, scope=search read access token access token { "iss": "myAuthzServer", "aud": "application", "exp": 192990121, "sub": "Bob", "client_id": "client1", "scope": [ "search", "read" ] } Bob 15
  12. OAuth2 flows (relevant) • Resource Owner Password Credential Flow –

    "Trusted clients" 1. Request token with resource owner credentials 2. Access resource • Implicit Flow – Native / local clients 1. Request authorization & token 2. Access resource 16
  13. Step 1a: Token Request Resource Owner Client Authorization Server POST

    /token Authorization: Basic (client_id:secret) grant_type=password& scope=read& username=owner& password=password& Resource Server 17
  14. Step 1b: Token Response Resource Owner Client Authorization Server {

    "access_token" : "abc", "expires_in" : "3600", "token_type" : "Bearer", "refresh_token" : "xyz" } Resource Server 18
  15. OWIN embedded Autorization Server public void Configuration(IAppBuilder app) { //

    token generation app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromHours(8), Provider = new SimpleAuthorizationServerProvider() }); // token consumption app.UseOAuthBearerAuthentication( new OAuthBearerAuthenticationOptions()); app.UseWebApi(WebApiConfig.Register()); } 20
  16. Client requests token - AngularJS var postData = $.param({ grant_type:

    "password", username: username, password: password }); return $http({ method: "POST", url: that.url, data: postData, headers: { "Content-Type": "application/x-www-form-urlencoded" } }) .success(function (tokenData) { setToken(tokenData); }); 21
  17. Client calls service - AngularJS function setToken(tokenData) { var sessionTokenValue

    = "Bearer " + tokenData.access_token; $http.defaults.headers.common["Authorization"] = sessionTokenValue; store.setItem(key, JSON.stringify(tokenData)); } this.getArticleDetails = function (id) { return $http({ method: "GET", url: ttTools.baseUrl + "api/articles/" + id }); }; 22
  18. Resource Owner Flow recap • Allows exchanging a password with

    a token – short lived or long lived • Better than dealing with passwords directly – e.g. storing the password – client still can "see" the password – maybe not what you want 23
  19. Step 1a: Authorization request Resource Server Resource Owner Client GET

    /authorize? client_id=nativeapp& scope=resource& redirect_uri=http://localhost/cb& response_type=token& state=123 Authorization Server 26
  20. Step 1b: Token response Resource Owner Client GET /cb# access_token=abc&

    expires_in=3600& state=123 Authorization Server Resource Server 27
  21. Implicit Flow with AngularJS • Use e.g. angularOauth and configure

    client settings • Trigger login/token retrieval – and set token on HTTP header TokenProvider.extendConfig({ authorizationEndpoint: 'https://windows8vm/as/todos/oauth/authorize', clientId: "implicitclient", redirectUri: baseUrl + "oauth2callback.html", scopes: ["read"], verifyFunc: TokenNonVerifier }); $scope.login = function () { Token.getTokenByPopup() .then(function (params) { Token.set(params.access_token); $http.defaults.headers.common["Authorization"] = "Bearer " + params.access_token; }, function () { alert("Failed to get token."); }); }; 29
  22. Implicit Flow recap • User enters credentials at the authorization

    server – not at the client • authorization server returns (short lived) access token – to reduce exposure of token • Often combined with OS helper mechanisms – cookie container – native APIs 30
  23. Personalization • Need for “authorization” in the UI layer –

    which user can see or do what in the client application? – authorization always has to happen on the server, anyway • Technical concept of authorization morphs into user- oriented concept of personalization – features – capabilities – constraints 31
  24. Implementing personalization with Web API • Model personalization data and

    populate from server-side repository public class PersonalizationController : ApiController { public PersonalizationData GetPersonalizationData() { var persData = new PersonalizationData { Features = GetFeatures().Where(m => m.Users.Contains(User.Identity.Name)), UiClaims = new UiClaimsData { UserName = User.Identity.Name, Capabilities = GetCapabilities(User), Constraints = GetConstraints(User), NameValueClaims = GetNameValueClaims(User) } }; return persData; } 34
  25. Implementing personalization with AngularJS • Get personalization data upon successful

    authentication • Implement AngularJS service to inject personalization data into controllers • Data-bind to e.g. capabilities on $scope • Fully-fledged solution may include custom directives $http({ method: "GET", url: ttTools.baseUrl + "api/personalization" }) .success(function (data) { tt.personalization.data = data; // populate routes from features… $rootScope.$broadcast(tt.personalization.constants.dataLoaded); }); app.factory("personalizationService", function () { return tt.personalization; }); 35
  26. Agenda • Mobile (web-based) client apps • Classic browser authentication

    • Moving to explicit authentication • OAuth2 Resource owner password flow • OAuth2 Implicit flow • Personalization 36
  27. Resources • [email protected][email protected] • http://www.thinktecture.com • Thinktecture Authorization

    Server – https://github.com/thinktecture/Thinktecture.AuthorizationServer • Thinktecture’s GitHub Repositories – https://github.com/thinktecture • Christian Weyer’s GitHub Repositories – https://github.com/ChristianWeyer 37