Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

State of the art authentication mit Java EE 8

655 views

Published on

Die Art und Weise der Client-Server-Authentifizierung hat in den vergangenen Jahren einen rasanten Wandel erfahren. Anmeldungen, z.B. über OAuth 2, sind Standard. Auch wenn Authentifizierungsmethoden wie Single-Sign-on (SSO) bereits seit mehreren Jahrzehnten Anforderungen von Unternehmen sind, gab es bisher im Enterprise-Java-Standard keine Lösungen dafür. Das hat sich mit Java EE 8 und der Version 1.0 der Security-API geändert.

Neben einem Blick auf die neuen Features der Security-API zeigt dieser Vortrag auch die Authentifizierung im Bereich der verteilten Systeme mit Hilfe von SSO über das JWT. Dabei wird darauf eingegangen, was der Standard nun bietet und was der Entwickler dazubauen muss.

Published in: Software
  • free download here Create DOWNLOAD for free book ===http://livresetops.icu/2212566603-Je-me-libre-du-sucre-Mon-programme-naturopathique-en-8-semaines.html
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • If you want to download or read this book, copy link or url below in the New tab ......................................................................................................................... DOWNLOAD FULL PDF EBOOK here { http://bit.ly/2m6jJ5M } .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • If you want to download or read this book, Copy link or url below in the New tab ......................................................................................................................... DOWNLOAD FULL PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

State of the art authentication mit Java EE 8

  1. 1. @_openknowledge #WISSENTEILEN SState of the Art Authentication mit Java EE 8
  2. 2. Ausführliches Beispiel mit Code Beispiel auf unserem Blog verfügbar. www.openknowledge.de/blog www.github.com/openknowledge @_openknowledge
  3. 3. ÜBER MICH • Software-Entwickler • Speaker • CI / CD Flüsterer • Angular(-ität) • Java EE Christian Schulz #WISSENTEILEN
  4. 4. ÜBER OPEN KNOWLEDGE Branchenneutrale Softwareentwicklung und IT-Beratung #WISSENTEILEN
  5. 5. Authentication JSON Web Token OpenID Connect Single-Sign On SAML
  6. 6. Am Anfang war …
  7. 7. … die web.xml <login-config> <auth-method> </auth-method> <realm-name>MyCustomRealm</realm-name> <form-login-config> <form-login-page>/login.xhtml</form-login-page> <form-error-page>/error.xhtml</form-error-page> </form-login-config> </login-config> FORM #WISSENTEILEN
  8. 8. Woher kommen die Login- Informationen?
  9. 9. JAAS LoginModule #WISSENTEILEN
  10. 10. JAAS LoginModule • Implementierung des Interfaces javax.security.auth.spi.LoginModule #WISSENTEILEN
  11. 11. JAAS LoginModule • Implementierung des Interfaces javax.security.auth.spi.LoginModule • Befüllen eines javax.security.auth.Subjects mit java.security.Principals #WISSENTEILEN
  12. 12. JAAS LoginModule • Implementierung des Interfaces javax.security.auth.spi.LoginModule • Befüllen eines javax.security.auth.Subjects mit java.security.Principals • Two-Phase-Authentication #WISSENTEILEN
  13. 13. JAAS LoginModule • Implementierung des Interfaces javax.security.auth.spi.LoginModule • Befüllen eines javax.security.auth.Subjects mit java.security.Principals • Two-Phase-Authentication • 1. Phase: Kann das Modul authentifizieren? #WISSENTEILEN
  14. 14. JAAS LoginModule • Implementierung des Interfaces javax.security.auth.spi.LoginModule • Befüllen eines javax.security.auth.Subjects mit java.security.Principals • Two-Phase-Authentication • 1. Phase: Kann das Modul authentifizieren? • 2. Phase: Login erfolgreich → Befüllen des Subjects #WISSENTEILEN
  15. 15. LoginModule in Tomcat META-INF/context.xml <Context> <Realm className="org.apache.catalina.realm.JAASRealm" appName="MyCustomLogin" ... /> </Context> jaas.config (Starten mit -Djava.security.auth.login.config=jaas.config) MyCustomLogin { de.openknowledge...CustomLoginModule required; }; #WISSENTEILEN
  16. 16. LoginModule in Tomcat META-INF/context.xml <Context> <Realm className="org.apache.catalina.realm.JAASRealm" appName="MyCustomLogin" ... /> </Context> jaas.config (Starten mit -Djava.security.auth.login.config=jaas.config) MyCustomLogin { de.openknowledge...CustomLoginModule required; }; #WISSENTEILEN
  17. 17. JAAS LoginModule – Nachteile #WISSENTEILEN
  18. 18. JAAS LoginModule – Nachteile • Umständliche API #WISSENTEILEN
  19. 19. JAAS LoginModule – Nachteile • Umständliche API Callback[] callbacks = new Callback [] { new NameCallback("Username"), new PasswordCallback("Password", false) }; callbackHandler.handle(callbacks); String username = ((NameCallback)callbacks[0]).getName(); String password = new String(((PasswordCallback)callbacks[1]).getPassword()); #WISSENTEILEN
  20. 20. JAAS LoginModule – Nachteile • Umständliche API • Container spezifische Konfiguration Callback[] callbacks = new Callback [] { new NameCallback("Username"), new PasswordCallback("Password", false) }; callbackHandler.handle(callbacks); String username = ((NameCallback)callbacks[0]).getName(); String password = new String(((PasswordCallback)callbacks[1]).getPassword()); #WISSENTEILEN
  21. 21. Und in der Cloud?
  22. 22. Java EE 8 – Security API 1.0
  23. 23. Java EE 8 – IdentityStore public interface IdentityStore { CredentialValidationResult validate(Credential credential); Set<String> getCallerGroups(CredentialValidationResult result); int priority(); Set<ValidationType> validationTypes(); enum ValidationType { VALIDATE, PROVIDE_GROUPS } } #WISSENTEILEN
  24. 24. Java EE 8 – IdentityStore @LdapIdentityStoreDefinition( url = "ldap://localhost:3268", bindDn = "readonly@openknownledge", bindDnPassword = "password" ) @DatabaseIdentityStoreDefinition( dataSourceLookup = "java:jboss/datasources/ExampleDS", callerQuery = "SELECT password from USERS where name = ?" ) #WISSENTEILEN
  25. 25. Java EE 8 – CredentialValidationResult public class CredentialValidationResult { public Status getStatus() {...} public CallerPrincipal getCallerPrincipal() {...} public Set<String> getCallerGroups() {...} public enum Status { NOT_VALIDATED, INVALID, VALID } } #WISSENTEILEN
  26. 26. Java EE 8 – HttpAuthenticationMechanism public interface HttpAuthenticationMechanism { AuthenticationStatus validateRequest( HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws Auth...Exception; AuthenticationStatus secureResponse(...) ... void cleanSubject(...); } #WISSENTEILEN
  27. 27. Java EE 8 – HttpAuthenticationMechanism #WISSENTEILEN
  28. 28. Java EE 8 – HttpAuthenticationMechanism • Ersetzt Eintrag in web.xml #WISSENTEILEN
  29. 29. Java EE 8 – HttpAuthenticationMechanism • Ersetzt Eintrag in web.xml • Standardimplementierungen via Annotation #WISSENTEILEN
  30. 30. Java EE 8 – HttpAuthenticationMechanism • Ersetzt Eintrag in web.xml • Standardimplementierungen via Annotation • BasicAuthenticationMechanism • FormAuthenticationMechanism • CustomFormAuthenticationMechanism #WISSENTEILEN
  31. 31. JASPIC #WISSENTEILEN
  32. 32. JASPIC • Java Authentication Service Provider Interface for Containers #WISSENTEILEN
  33. 33. JASPIC • Java Authentication Service Provider Interface for Containers • Container-unabhängiges Login möglich #WISSENTEILEN
  34. 34. JASPIC • Java Authentication Service Provider Interface for Containers • Container-unabhängiges Login möglich →Implementierung des Interfaces ServerAuthModule #WISSENTEILEN
  35. 35. JASPIC • Java Authentication Service Provider Interface for Containers • Container-unabhängiges Login möglich →Implementierung des Interfaces ServerAuthModule • Unterstützung verschiedener Kommunikations-Szenarien (neben HTTP noch RMI/Remote-EJB, JMS, ...) • Implementierung umständlich und aufwändig • In der Praxis selten genutzt #WISSENTEILEN
  36. 36. Java EE 8 – Security 1.0 #WISSENTEILEN
  37. 37. Java EE 8 – Security 1.0 • JSR 375 #WISSENTEILEN
  38. 38. Java EE 8 – Security 1.0 • JSR 375 • Aufsatz auf das JASPIC ServerAuthModule #WISSENTEILEN
  39. 39. Java EE 8 – Security 1.0 • JSR 375 • Aufsatz auf das JASPIC ServerAuthModule • dadurch Java EE 7 kompatibel #WISSENTEILEN
  40. 40. Java EE 8 – Security 1.0 • JSR 375 • Aufsatz auf das JASPIC ServerAuthModule • dadurch Java EE 7 kompatibel • Nutzt IdentityStore(Handler) #WISSENTEILEN
  41. 41. Java EE 8 – Security 1.0 • JSR 375 • Aufsatz auf das JASPIC ServerAuthModule • dadurch Java EE 7 kompatibel • Nutzt IdentityStore(Handler) • Nur für HTTP-Authentication #WISSENTEILEN
  42. 42. Java EE 8 – Security 1.0 • JSR 375 • Aufsatz auf das JASPIC ServerAuthModule • dadurch Java EE 7 kompatibel • Nutzt IdentityStore(Handler) • Nur für HTTP-Authentication • Referenzimplementierung Soteria von GlassFish #WISSENTEILEN
  43. 43. Was ist mit Token-basierten Authentifizierungsmethoden wie z.B. JSON Web Token?
  44. 44. Token-basierte Authentication #WISSENTEILEN
  45. 45. Warum JWT? • … vs. SWT • … vs. SAML • public / private Key-Pair • extrem kompakt • JSON #WISSENTEILEN
  46. 46. JSON Web Token #WISSENTEILEN
  47. 47. JSON Web Token #WISSENTEILEN
  48. 48. JSON Web Token #WISSENTEILEN
  49. 49. JSON Web Token #WISSENTEILEN
  50. 50. JSON Web Token #WISSENTEILEN
  51. 51. UND WIE JETZT IN JAVA EE?
  52. 52. Authentication Ablauf #WISSENTEILEN
  53. 53. Authentication Ablauf #WISSENTEILEN
  54. 54. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  55. 55. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  56. 56. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  57. 57. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  58. 58. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  59. 59. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  60. 60. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  61. 61. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  62. 62. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  63. 63. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  64. 64. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  65. 65. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  66. 66. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  67. 67. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  68. 68. Authentication AblaufHttpAuthenticationMechanism #WISSENTEILEN
  69. 69. JwtAuthenticationMechanism public AuthenticationStatus validateRequest( HttpServletRequest request, HttpServletResponse response, HttpMessageContext context) { if (!context.isProtected()) { // unprotected api call return context.doNothing(); } … #WISSENTEILEN
  70. 70. JwtAuthenticationMechanism public AuthenticationStatus validateRequest( HttpServletRequest request, HttpServletResponse response, HttpMessageContext context) { if (!context.isProtected()) { // unprotected api call return context.doNothing(); } … #WISSENTEILEN
  71. 71. JwtAuthenticationMechanism public AuthenticationStatus validateRequest( HttpServletRequest request, HttpServletResponse response, HttpMessageContext context) { if (!context.isProtected()) { // unprotected api call return context.doNothing(); } … #WISSENTEILEN
  72. 72. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header == null) { LOGGER.log(Level.WARNING, "Authorization header is missing"); return context.responseUnauthorized(); } … #WISSENTEILEN
  73. 73. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header == null) { LOGGER.log(Level.WARNING, "Authorization header is missing"); return context.responseUnauthorized(); } … #WISSENTEILEN
  74. 74. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … if (!isValidAuthorizationHeader(header)) { LOGGER.log(Level.WARNING, "Authorization header is invalid"); return context.responseUnauthorized(); } … #WISSENTEILEN
  75. 75. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … try { String[] headerComponents = header.split(" "); String token = headerComponents[1]; DecodedJWT jwt = tokenProvider.verifyAndDecodeJwt(token); return context.notifyContainerAboutLogin( jwt.getSubject(), new HashSet<>()); } catch (JWTVerificationException e) {…} return context.responseUnauthorized(); } #WISSENTEILEN
  76. 76. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … try { String[] headerComponents = header.split(" "); String token = headerComponents[1]; DecodedJWT jwt = tokenProvider.verifyAndDecodeJwt(token); return context.notifyContainerAboutLogin( jwt.getSubject(), new HashSet<>()); } catch (JWTVerificationException e) {…} return context.responseUnauthorized(); } #WISSENTEILEN
  77. 77. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … try { String[] headerComponents = header.split(" "); String token = headerComponents[1]; DecodedJWT jwt = tokenProvider.verifyAndDecodeJwt(token); return context.notifyContainerAboutLogin( jwt.getSubject(), new HashSet<>()); } catch (JWTVerificationException e) {…} return context.responseUnauthorized(); } #WISSENTEILEN
  78. 78. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … try { String[] headerComponents = header.split(" "); String token = headerComponents[1]; DecodedJWT jwt = tokenProvider.verifyAndDecodeJwt(token); return context.notifyContainerAboutLogin( jwt.getSubject(), new HashSet<>()); } catch (JWTVerificationException e) {…} return context.responseUnauthorized(); } #WISSENTEILEN
  79. 79. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … try { String[] headerComponents = header.split(" "); String token = headerComponents[1]; DecodedJWT jwt = tokenProvider.verifyAndDecodeJwt(token); return context.notifyContainerAboutLogin( jwt.getSubject(), new HashSet<>()); } catch (JWTVerificationException e) {…} return context.responseUnauthorized(); } #WISSENTEILEN
  80. 80. FAZIT AUTHENTICATION IN JAVA EE 8
  81. 81. FAZIT AUTHENTICATION IN JAVA EE 8 Eigene Nutzerquelle ohne Container-Config
  82. 82. FAZIT AUTHENTICATION IN JAVA EE 8 Eigene Nutzerquelle ohne Container-Config Standard-Mechanismen weiterhin möglich
  83. 83. FAZIT AUTHENTICATION IN JAVA EE 8 Eigene Nutzerquelle ohne Container-Config Standard-Mechanismen weiterhin möglich Support für RememberMe
  84. 84. FAZIT AUTHENTICATION IN JAVA EE 8 Eigene Nutzerquelle ohne Container-Config Standard-Mechanismen weiterhin möglich Support für RememberMe Leichte Erweiterbarkeit für HTTP-basierte Mechanismen
  85. 85. Authorization Domain-Object-Security Access-Control Lists
  86. 86. Beispielanwendung E-Learning Plattform
  87. 87. #WISSENTEILEN
  88. 88. Teacher 1 Users Student 1 ... #WISSENTEILEN
  89. 89. Teacher 1 Users Permissions Student 1 Read Course ... ... #WISSENTEILEN
  90. 90. Roles Teacher 1 Users Permissions Student 1 Read Course Teacher Student ... ... #WISSENTEILEN
  91. 91. Roles Teacher 1 Users Permissions Student 1 Read Course Teacher Student ... ... #WISSENTEILEN
  92. 92. Roles Teacher 1 Users Permissions Student 1 Read Course Teacher Student ... ... #WISSENTEILEN
  93. 93. Roles Teacher 1 Users Permissions Student 1 Read Course Teacher Student ... ... #WISSENTEILEN
  94. 94. Roles Teacher 1 Users Permissions Student 1 Read Course Teacher Student ... ... #WISSENTEILEN
  95. 95. Role based Access Control Roles Teacher 1 Users Permissions Student 1 Read Course Teacher Student ... ... #WISSENTEILEN
  96. 96. Role based Access Control Servlet Spec →Permissions für Web-Resources #WISSENTEILEN
  97. 97. Role based Access Control web.xml / Annotations <security-constraint> <web-resource-name>courses API</…> <url-pattern>/api/protected/courses</…> <auth-constraint> <role-name>TEACHER</…> </auth-constraint> </security-constraint> @ServletSecurity( @HttpConstraint(rolesAllowed = {"TEACHER"}) ) #WISSENTEILEN
  98. 98. Role based Access Control Servlet Spec →Permissions für Web-Resources #WISSENTEILEN
  99. 99. Role based Access Control Servlet Spec →Permissions für Web-Resources Java EE Security →Permissions für Klassen und Methoden via @RolesAllowed Standard unterstützt kein JAX-RS #WISSENTEILEN
  100. 100. Role based Access Control Servlet Spec →Permissions für Web-Resources Java EE Security →Permissions für Klassen und Methoden via @RolesAllowed Standard unterstützt kein JAX-RS Java EE 8 Security →Standard-Mapping für User und Rollen #WISSENTEILEN
  101. 101. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … try { … DecodedJWT jwt = tokenProvider.verifyAndDecodeJwt(token); return context.notifyContainerAboutLogin( jwt.getSubject(), new HashSet<>()); } catch (JWTVerificationException e) {…} … } #WISSENTEILEN
  102. 102. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … try { … DecodedJWT jwt = tokenProvider.verifyAndDecodeJwt(token); return context.notifyContainerAboutLogin( jwt.getSubject(), new HashSet<>()); } catch (JWTVerificationException e) {…} … } String username = jwt.getSubject(); List<String> roles = jwt.getClaim("roles").asList(String.class); return context.notifyContainerAboutLogin( username, new HashSet<>(roles)); } catch (JWTVerificationException e) {…} … } #WISSENTEILEN
  103. 103. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … try { … DecodedJWT jwt = tokenProvider.verifyAndDecodeJwt(token); return context.notifyContainerAboutLogin( jwt.getSubject(), new HashSet<>()); } catch (JWTVerificationException e) {…} … } String username = jwt.getSubject(); List<String> roles = jwt.getClaim("roles").asList(String.class); return context.notifyContainerAboutLogin( username, new HashSet<>(roles)); } catch (JWTVerificationException e) {…} … } #WISSENTEILEN
  104. 104. JwtAuthenticationMechanism public AuthenticationStatus validateRequest(…) { … try { … DecodedJWT jwt = tokenProvider.verifyAndDecodeJwt(token); return context.notifyContainerAboutLogin( jwt.getSubject(), new HashSet<>()); } catch (JWTVerificationException e) {…} … } String username = jwt.getSubject(); List<String> roles = jwt.getClaim("roles").asList(String.class); return context.notifyContainerAboutLogin( username, new HashSet<>(roles)); } catch (JWTVerificationException e) {…} … } #WISSENTEILEN
  105. 105. StudentResource #WISSENTEILEN
  106. 106. StudentResource • createStudent POST api/protected/students #WISSENTEILEN
  107. 107. StudentResource • createStudent POST api/protected/students • getStudents GET api/protected/students #WISSENTEILEN
  108. 108. StudentResource • createStudent POST api/protected/students • getStudents GET api/protected/students • zwei Rollen pro Methode in einer web.xml? #WISSENTEILEN
  109. 109. StudentResource • createStudent POST api/protected/students • getStudents GET api/protected/students • zwei Rollen pro Methode in einer web.xml? • Es gibt doch nur Pfade?! #WISSENTEILEN
  110. 110. Role based Access Control web.xml <security-constraint> <web-resource-name>studens API</…> <url-pattern>/api/protected/students</…> <auth-constraint> <role-name>TEACHER</…> <role-name>STUDENTS</…> </auth-constraint> </security-constraint> #WISSENTEILEN
  111. 111. Role based Access Control web.xml <security-constraint> <web-resource-name>studens API</…> <url-pattern>/api/protected/students</…> <auth-constraint> <role-name>TEACHER</…> <role-name>STUDENTS</…> </auth-constraint> </security-constraint> #WISSENTEILEN
  112. 112. Role based Access Control web.xml <security-constraint> <web-resource-name>studens API</…> <url-pattern>/api/protected/students</…> <auth-constraint> <role-name>TEACHER</…> <role-name>STUDENTS</…> </auth-constraint> </security-constraint> Rechtevergabe auf Methodenebene notwendig! #WISSENTEILEN
  113. 113. RolesAllowedFilter @Provider @Priority(Priorities.AUTHENTICATION) public class RolesAllowedFilter implements ContainerRequestFilter { @Context private ResourceInfo resourceInfo; @Inject private User user; @Override public void filter(ContainerRequestContext requestContext) { #WISSENTEILEN
  114. 114. RolesAllowedFilter @Provider @Priority(Priorities.AUTHENTICATION) public class RolesAllowedFilter implements ContainerRequestFilter { @Context private ResourceInfo resourceInfo; @Inject private User user; @Override public void filter(ContainerRequestContext requestContext) { #WISSENTEILEN
  115. 115. RolesAllowedFilter @Provider @Priority(Priorities.AUTHENTICATION) public class RolesAllowedFilter implements ContainerRequestFilter { @Context private ResourceInfo resourceInfo; @Inject private User user; @Override public void filter(ContainerRequestContext requestContext) { #WISSENTEILEN
  116. 116. RolesAllowedFilter @Provider @Priority(Priorities.AUTHENTICATION) public class RolesAllowedFilter implements ContainerRequestFilter { @Context private ResourceInfo resourceInfo; @Inject private User user; @Override public void filter(ContainerRequestContext requestContext) { #WISSENTEILEN
  117. 117. Java EE 8 Security Context • Pre Java EE 8: Jede Spec hat ihre eigene Variante • Servlet - HttpServletRequest#getUserPrincipal, HttpServletRequest#isUserInRole • EJB - EJBContext#getCallerPrincipal, EJBContext#isCallerInRole • JAX-WS - WebServiceContext#getUserPrincipal, WebServiceContext#isUserInRole • JAX-RS - SecurityContext#getUserPrincipal, SecurityContext#isUserInRole • JSF - ExternalContext#getUserPrincipal, ExternalContext#isUserInRole • CDI - @Inject Principal • WebSockets - Session#getUserPrincipal • Vereinheitlichung in Java EE 8 #WISSENTEILEN
  118. 118. Java EE 8 Security Context public interface SecurityContext { Principal getCallerPrincipal(); <T extends Principal> Set<T> getPrincipalsByType(Class<T> pType); boolean isCallerInRole(String role); boolean hasAccessToWebResource(String resource, String... methods); AuthenticationStatus authenticate(HttpServletRequest request, HttpServletResponse response, AuthenticationParameters parameters); } #WISSENTEILEN
  119. 119. RolesAllowedFilter @Provider @Priority(Priorities.AUTHENTICATION) public class RolesAllowedFilter implements ContainerRequestFilter { @Context private ResourceInfo resourceInfo; @Inject private SecurityContext securityContext; @Override public void filter(ContainerRequestContext requestContext) { #WISSENTEILEN
  120. 120. RolesAllowedFilter public void filter(ContainerRequestContext requestContext) { RolesAllowed rolesAllowed = resourceInfo.getResourceClass() .getAnnotation(RolesAllowed.class); RolesAllowed rolesAllowedMethod = resourceInfo.getResourceMethod() .getAnnotation(RolesAllowed.class); if (rolesAllowedMethod != null) { rolesAllowed = rolesAllowedMethod; } #WISSENTEILEN
  121. 121. RolesAllowedFilter public void filter(ContainerRequestContext requestContext) { RolesAllowed rolesAllowed = resourceInfo.getResourceClass() .getAnnotation(RolesAllowed.class); RolesAllowed rolesAllowedMethod = resourceInfo.getResourceMethod() .getAnnotation(RolesAllowed.class); if (rolesAllowedMethod != null) { rolesAllowed = rolesAllowedMethod; } #WISSENTEILEN
  122. 122. RolesAllowedFilter public void filter(ContainerRequestContext requestContext) { RolesAllowed rolesAllowed = resourceInfo.getResourceClass() .getAnnotation(RolesAllowed.class); RolesAllowed rolesAllowedMethod = resourceInfo.getResourceMethod() .getAnnotation(RolesAllowed.class); if (rolesAllowedMethod != null) { rolesAllowed = rolesAllowedMethod; } #WISSENTEILEN
  123. 123. RolesAllowedFilter public void filter(ContainerRequestContext requestContext) { RolesAllowed rolesAllowed = resourceInfo.getResourceClass() .getAnnotation(RolesAllowed.class); RolesAllowed rolesAllowedMethod = resourceInfo.getResourceMethod() .getAnnotation(RolesAllowed.class); if (rolesAllowedMethod != null) { rolesAllowed = rolesAllowedMethod; } #WISSENTEILEN
  124. 124. RolesAllowedFilter public void filter(ContainerRequestContext requestContext) { … if (rolesAllowed != null && Arrays .stream(rolesAllowed.value()) .noneMatch(s -> securityContext.isCallerInRole(s)) ) { requestContext.abortWith( Response.status(Response.Status.FORBIDDEN).build() ); } #WISSENTEILEN
  125. 125. RolesAllowedFilter public void filter(ContainerRequestContext requestContext) { … if (rolesAllowed != null && Arrays .stream(rolesAllowed.value()) .noneMatch(s -> securityContext.isCallerInRole(s)) ) { requestContext.abortWith( Response.status(Response.Status.FORBIDDEN).build() ); } #WISSENTEILEN
  126. 126. RolesAllowedFilter public void filter(ContainerRequestContext requestContext) { … if (rolesAllowed != null && Arrays .stream(rolesAllowed.value()) .noneMatch(s -> securityContext.isCallerInRole(s)) ) { requestContext.abortWith( Response.status(Response.Status.FORBIDDEN).build() ); } #WISSENTEILEN
  127. 127. RolesAllowedFilter #WISSENTEILEN
  128. 128. RolesAllowedFilter • Kein Standard https://github.com/eclipse-ee4j/jaxrs-api/issues/563 #WISSENTEILEN
  129. 129. RolesAllowedFilter • Kein Standard https://github.com/eclipse-ee4j/jaxrs-api/issues/563 • RESTeasy bringt Filter mit #WISSENTEILEN
  130. 130. RolesAllowedFilter • Kein Standard https://github.com/eclipse-ee4j/jaxrs-api/issues/563 • RESTeasy bringt Filter mit • Eigene Implementierung für andere JAX-RS Implementierungen möglich #WISSENTEILEN
  131. 131. Kurs anlegen @RolesAllowed("TEACHER") public Course create(Teacher lecturer, …) { Course course = new Course(lecturer, …); entityManager.persist(course); return course; } #WISSENTEILEN
  132. 132. Kurs anlegen @RolesAllowed("TEACHER") public Course create(Teacher lecturer, …) { Course course = new Course(lecturer, …); entityManager.persist(course); return course; } #WISSENTEILEN
  133. 133. Kurs anlegen @RolesAllowed("TEACHER") public Course create(Teacher lecturer, …) { Course course = new Course(lecturer, …); entityManager.persist(course); return course; } Role Based Access Control reicht nicht aus! #WISSENTEILEN
  134. 134. Kurs anlegen @Inject private Principal currentPrincipal; public Course create(Teacher lecturer, …) { if (!lecturer.equals(currentPrincipal)) { throw new SecurityException(…); } … } #WISSENTEILEN
  135. 135. Kurs anlegen @Inject private Principal currentPrincipal; public Course create(Teacher lecturer, …) { if (!lecturer.equals(currentPrincipal)) { throw new SecurityException(…); } … } Sicherheitsüberprüfungen im Code verteilt!  #WISSENTEILEN
  136. 136. Gibt es Alternativen zu Role Based Access Control?
  137. 137. SAUTHORIZATION – Ausblick
  138. 138. SAUTHORIZATION – Ausblick Role-Based – Java EE Standard
  139. 139. SAUTHORIZATION – Ausblick Role-Based – Java EE Standard Access-Control-Lists – Spring Security
  140. 140. SAUTHORIZATION – Ausblick Role-Based – Java EE Standard Access-Control-Lists – Spring Security Method-Based – Spring & Deltaspike Security
  141. 141. SAUTHORIZATION – Ausblick Role-Based – Java EE Standard Access-Control-Lists – Spring Security Method-Based – Spring & Deltaspike Security Domain-Object-Based – Deltaspike & JPA Security
  142. 142. ACCESS-CONTROL LIST Object Access-Control List #WISSENTEILEN
  143. 143. ACCESS-CONTROL LIST Object Entry Access-Control List ...... User 1 User 2 User 3 #WISSENTEILEN
  144. 144. DeltaSpike Security @Create public Course create( @Owner Teacher lecturer, …) { Course course = new Course(lecturer, …); entityManager.persist(course); return course; } #WISSENTEILEN
  145. 145. DeltaSpike Security @Create public Course create( @Owner Teacher lecturer, …) { Course course = new Course(lecturer, …); entityManager.persist(course); return course; } #WISSENTEILEN
  146. 146. DeltaSpike Security @Create public Course create( @Owner Teacher lecturer, …) { Course course = new Course(lecturer, …); entityManager.persist(course); return course; } #WISSENTEILEN
  147. 147. Eigene Security-Annotation @SecurityBindingType @Retention(RUNTIME) public @interface Create { } @SecurityParameterBinding @Retention(RUNTIME) public @interface Owner { } #WISSENTEILEN
  148. 148. Eigene Security-Annotation @SecurityBindingType @Retention(RUNTIME) public @interface Create { } @SecurityParameterBinding @Retention(RUNTIME) public @interface Owner { } #WISSENTEILEN
  149. 149. Separate Logik-Implementierung public class SecurityRules { @Secures @Create public boolean checkOwner(@Owner User owner, Identity user) { return owner.equals(user); } } #WISSENTEILEN
  150. 150. Separate Logik-Implementierung public class SecurityRules { @Secures @Create public boolean checkOwner(@Owner User owner, Identity user) { return owner.equals(user); } } #WISSENTEILEN
  151. 151. Separate Logik-Implementierung public class SecurityRules { @Secures @Create public boolean checkOwner(@Owner User owner, Identity user) { return owner.equals(user); } } #WISSENTEILEN
  152. 152. Separate Logik-Implementierung public class SecurityRules { @Secures @Create public boolean checkOwner(@Owner User owner, Identity user) { return owner.equals(user); } } #WISSENTEILEN
  153. 153. JPA Security Security Framework für JPA https://github.com/ArneLimburg/jpasecurity • Pluggable Authentication • Authorization • Access-Check bei CRUD-Operationen • In-Database-Filtern von Queries (JPQL und Criteria) #WISSENTEILEN
  154. 154. @Permit(access = AccessType.CREATE, rule = "lecturer = CURRENT_PRINCIPAL") @Entity public Course { … } Entity-Security mit JPA Security #WISSENTEILEN
  155. 155. @Permit(access = AccessType.CREATE, rule = "lecturer = CURRENT_PRINCIPAL") @Entity public Course { … } Entity-Security mit JPA Security #WISSENTEILEN
  156. 156. @Permit(access = AccessType.CREATE, rule = "lecturer = CURRENT_PRINCIPAL") @Entity public Course { … } Entity-Security mit JPA Security #WISSENTEILEN
  157. 157. @Permit(access = AccessType.CREATE, rule = "lecturer = CURRENT_PRINCIPAL") @Entity public Course { … } Entity-Security mit JPA Security #WISSENTEILEN
  158. 158. @Permit(access = AccessType.CREATE, rule = "lecturer = CURRENT_PRINCIPAL") @Entity public Course { … } Automatischer Check bei entityManager.persist(…) oder entityManager.merge(…) oder bei Cascading! Entity-Security mit JPA Security #WISSENTEILEN
  159. 159. Entity-Security mit JPA Security public List<Student> findAll() { TypedQuery<Student> query = entityManager.createQuery("SELECT s FROM Student s", …); return query.getResultList(); } #WISSENTEILEN
  160. 160. Entity-Security mit JPA Security public List<Student> findAll() { TypedQuery<Student> query = entityManager.createQuery("SELECT s FROM Student s", …); return query.getResultList(); } Lehrer darf nur Studenten aus seinen eigenen Kursen sehen. #WISSENTEILEN
  161. 161. Entity-Security mit JPA Security public List<Student> findAll() { TypedQuery<Student> query = entityManager.createNamedQuery(…, …); return query.getResultList(); } Automatische Filterung von JPA Queries und Criterias! #WISSENTEILEN
  162. 162. @PermitAny({ @Permit(access = AccessType.READ, rule = "this IN (SELECT p" + " FROM Course course" + " JOIN course.participants p" + " WHERE course.lecturer" + " = CURRENT_PRINCIPAL)"), @Permit(…)}) @Entity public Student { … Entity-Security mit JPA Security #WISSENTEILEN
  163. 163. Entity-Security mit JPA Security public List<Student> findAll() { TypedQuery<Student> query = entityManager.createQuery("SELECT s FROM Student s", …); return query.getResultList(); } erzeugt SELECT s FROM Student s WHERE s IN (SELECT p FROM Course course JOIN course.participants p WHERE course.lecturer = CURRENT_PRINCIPAL) … #WISSENTEILEN
  164. 164. SAUTHORIZATION – Fazit
  165. 165. SAUTHORIZATION – Fazit Role-Based – Java EE Standard
  166. 166. SAUTHORIZATION – Fazit Role-Based – Java EE Standard Access-Control-Lists – Spring Security
  167. 167. SAUTHORIZATION – Fazit Role-Based – Java EE Standard Access-Control-Lists – Spring Security Method-Based – Spring & Deltaspike Security
  168. 168. SAUTHORIZATION – Fazit Role-Based – Java EE Standard Access-Control-Lists – Spring Security Method-Based – Spring & Deltaspike Security Domain-Object-Based – Deltaspike & JPA Security
  169. 169. FRAGEN @_openknowledge#WISSENTEILEN
  170. 170. KONTAKT Christian Schulz, Enterprise Developer christian.schulz@openknowledge.de +49 (0)441 4082 – 146 Icons in this presentation designed by “Freepik”, “Nice and Serious” and “Elegant Themes” from www.flaticon.com. OFFENKUNDIGGUT #WISSENTEILEN

×