Spring Framework - Spring Security

Embed Size (px)

DESCRIPTION

Introduction to Spring Security Framework

Citation preview

  • 1.Spring Framework - SecuritySPRING FRAMEWORKDmitry Noskov Spring Security 3.0

2. Application security Security is arguably one of the most criticalarchitectural components of any application writtenin the 21st century Spring Framework - Security Dmitry Noskov 3. What is Spring Security a powerful and highly customizable authenticationand access-control framework build on top of Spring Framework de-facto standard for securing Spring-basedapplications Spring Framework - Security Dmitry Noskov 4. Fundamentals (1) principal user that performs the action authentication confirming truth of credentials authorization define access policy for principalSpring Framework - Security Dmitry Noskov 5. Fundamentals (2) Authentication the principal in a Spring Security-specific manner GrantedAuthority application-wide permissions granted to a principal SecurityContext hold the Authentication and other security information SecurityContextHolder provide access to SecurityContextSpring Framework - Security Dmitry Noskov 6. SecurityContextHolder provide access to SecurityContext strategies ThreadLocal InreritableThreadLocal Global Spring Framework - Security Dmitry Noskov 7. Getting started SecurityContext context = SecurityContextHolder.getContext(); Object principal = context.getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { String username = ((UserDetails)principal).getUsername(); } else { String username = principal.toString(); } Spring Framework - Security Dmitry Noskov 8. Use case Spring Framework - Security Dmitry Noskov 9. Namespace Spring Framework - Security Dmitry Noskov 10. FiltersSpring Framework - Security Dmitry Noskov 11. Security filterspringSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy springSecurityFilterChain/* Spring Framework - Security Dmitry Noskov 12. Filter chain Spring Framework - Security Dmitry Noskov 13. Filter chain (2)Spring Framework - Security Dmitry Noskov 14. Basic filtersFilter DescriptionChannelProcessingFilterensures that a request is being sent over HTTP or HTTPSSecurityContextPersistentFilterPopulates the security context using information obtained from the repository (http session)LogoutFilter Used to log a user out of the applicationUsernamePasswordAuthenticationFilter Accepts the users principal and credentials and attempts to authenticate the userBasicAuthenticationFilterAttempts to authenticate a user by processing an HTTP Basic authenticationExceptionTranslationFilter Handles any AccessDeniedException or AuthenticationExceptionFilterSecurityInterceptorDecides whether or not to allow access to a secured resourcehttp://static.springsource.org/spring-security/site/docs/3.0.x/reference/ns-config.html#ns-custom-filters Spring Framework - Security Dmitry Noskov 15. Authentication Spring Framework - Security Dmitry Noskov 16. Authentication variants credential-based two-factor hardware other Spring Framework - Security Dmitry Noskov 17. Authentication mechanisms basic form x.509 JAAS etc. Spring Framework - Security Dmitry Noskov 18. Authentication storage RDMBS LDAP custom storage etc. Spring Framework - Security Dmitry Noskov 19. FundamentalsFilterManagerProviderAuthenticationUserDetails Spring Framework - Security Dmitry Noskov 20. HTML formLogin:Password:Spring Framework - Security Dmitry Noskov 21. Username-password filter Spring Framework - Security Dmitry Noskov 22. Core authentication services AuthenticationManager handles authentication requests AuthenticationProvider performs authentication UserDetailsService responsible for returning an UserDetails object UerDetails provides the core user information Spring Framework - Security Dmitry Noskov 23. AuthenticationManagerpublic interface AuthenticationManager {/* Attempts to authenticate the passed Authentication object,* returning a fully populated Authentication object (including* granted authorities) if successful.* @param authentication the authentication request object* @return a fully authenticated object including credentials* @throws AuthenticationException if authentication fails */Authentication authenticate(Authentication authentication) throws AuthenticationException;}Spring Framework - Security Dmitry Noskov 24. AuthenticationProviderpublic interface AuthenticationProvider {/* Performs authentication.* @param authentication the authentication request object.* @return a fully authenticated object including credentials.* @throws AuthenticationException if authentication fails.*/Authentication authenticate(Authentication authentication) throws AuthenticationException;/*Returns true if this provider supports the indicated*Authentication object.*/boolean supports(Class clazz);int vote(Authentication authentication, Object object, Collection attributes);}Spring Framework - Security Dmitry Noskov 47. Basic expressionsExpressionDescriptionhasRole(ROLE_USER)Returns true if the current principal has the specified rolehasAnyRole(ROLE_USER, ROLE_ADMIN) Returns true if the current principal has any of the rolesprincipal Allows direct access to the principal object representingthe current userauthenticationAllows direct access to the current Authentication objectobtained from the SecurityContextpermitAll Always evaluates to truedenyAll Always evaluates to falseisAnonymous() Returns true if the current principal is an anonymous userisRememberMe()Returns true if the current principal is a remember-me userSpring Framework - Security Dmitry Noskov 48. WEB authorizationSpring Framework - Security Dmitry Noskov 49. Web authorization Spring Framework - Security Dmitry Noskov 50. WEB authorization with magic tags Spring Framework - Security Dmitry Noskov 51. WEB authorizationSpring Framework - Security Dmitry Noskov 52. Custom expression rootpublic class CustomWebSecurityExpressionRoot extends WebSecurityExpressionRoot {public CustomWebSecurityExpressionRoot(Authentication a, FilterInvocation fi) {super(a, fi);}public boolean hasAllRoles(String... roles) {return false;}}Spring Framework - Security Dmitry Noskov 53. Custom expression handlerpublic class CustomWebSecurityExpressionHandlerextends DefaultWebSecurityExpressionHandler {@Overridepublic EvaluationContext createEvaluationContext(Authentication a, FilterInvocation fi) {StandardEvaluationContext ctx =(StandardEvaluationContext)super.createEvaluationContext(a, fi);SecurityExpressionRoot root =new CustomWebSecurityExpressionRoot(a, fi);ctx.setRootObject(root);return ctx;}} Spring Framework - Security Dmitry Noskov 54. Method authorizationSpring Framework - Security Dmitry Noskov 55. Method authorization annotation driven voting based - @Secured expression based - @Pre/@Post JSR-250 - @RolesAllowed xml drivenSpring Framework - Security Dmitry Noskov 56. Configuration access-decision-manager-ref="accessDecisionManager" jsr250-annotations="disabled" pre-post-annotations="disabled" secured-annotations="enabled"Spring Framework - Security Dmitry Noskov 57. Annotation driven (voting) voting@Secured({"ROLE_USER"})void create(Customer customer); jsr-250@RolesAllowed({"ROLE_USER"})void create(Customer customer);Spring Framework - Security Dmitry Noskov 58. Annotation driven (expression) 1@PreAuthorize("hasRole(ROLE_USER)")void create(Customer customer); 2@PreAuthorize("hasRole(ROLE_USER) and hasRole(ROLE_ADMIN)")void create(Customer customer); 3@PreAuthorize("hasAnyRole(ROLE_USER, ROLE_ADMIN)")void create(Customer customer);Spring Framework - Security Dmitry Noskov 59. XML driven authorization (1)org.training.AccountService.createAccount=ROLE_USERorg.training.AccountService.delete*=ROLE_ADMINSpring Framework - Security Dmitry Noskov 60. XML driven authorization (2) Spring Framework - Security Dmitry Noskov 61. Domain Object SecuritySpring Framework - Security Dmitry Noskov 62. ACL DB schemeSpring Framework - Security Dmitry Noskov 63. ACL_CLASS ACL_SID ACL_OBJECT_IDENTITY ACL_ENTRYSpring Framework - Security Dmitry Noskov 64. Basic classes Acl AccessControlEntry Permission Sid ObjectIdentity represents the identity of an individual domain object Spring Framework - Security Dmitry Noskov 65. Basic ACL services AclService MutableAclService LookupStrategy ObjectIdentityRetrievalStrategy SidRetrievalStrategy Spring Framework - Security Dmitry Noskov 66. Permissions base permissions read (1) write (2) create (4) delete (8) administration (16) custom permissionsSpring Framework - Security Dmitry Noskov 67. Spring Framework - Security Dmitry Noskov 68. Configuration (voting) Spring Framework - Security Dmitry Noskov 69. @Secured annotation@Secured("ACL_CUSTOMER_READ")public Customer getProjectsByCustomer(Customer customer) {} voterSpring Framework - Security Dmitry Noskov 70. Configuration (expressions)Spring Framework - Security Dmitry Noskov 71. Permission evaluatorpublic interface PermissionEvaluator {boolean hasPermission(Authentication authentication,Object targetDomainObject,Object permission);boolean hasPermission(Authentication authentication,Serializable targetId,String targetType,Object permission);}Spring Framework - Security Dmitry Noskov 72. @PreAuthorize by domain object@PreAuthorize("hasPermission(#customer, delete)")public void delete(Customer customer); by identifier@PreAuthorize("hasPermission(#id, org.training.Customer, read) or " +"hasPermission(#id, org.training.Customer, admin)")public Customer getById(Long id); hardcode@PreAuthorize("#customer.owner.id == principal.id")public void create(Customer customer);Spring Framework - Security Dmitry Noskov 73. @PreFilter single parameter@PreFilter("hasPermission(filterObject, read)")public List filterCustomers(List customers) {return customers;} multiple parameters@PreFilter(filterTarget = "customers", value = "hasPermission(filterObject, update)")public void updateCustomers(List customers, State st) {}Spring Framework - Security Dmitry Noskov 74. Additional featuresSpring Framework - Security Dmitry Noskov 75. RunAsManager/*Creates a new temporary Authentication object.*/public interface RunAsManager {/ *Returns a replacement Authentication object for the current *secure object, or null if replacement not required*/Authentication buildRunAs(Authentication authentication,Object object,Collection attr);boolean supports(ConfigAttribute attribute);boolean supports(Class clazz);}Spring Framework - Security Dmitry Noskov 76. RunAs configuration (1)Spring Framework - Security Dmitry Noskov 77. RunAs configuration (2) magic tag interceptor beanSpring Framework - Security Dmitry Noskov 78. After invocationSpring Framework - Security Dmitry Noskov 79. Basic servicespublic interface AfterInvocationManager {Object decide(Authentication authentication, Object object, Collection attributes, Object returnedObject) throws AccessDeniedException;boolean supports(ConfigAttribute attribute);boolean supports(Class clazz);}public interface AfterInvocationProvider {Object decide(Authentication authentication, Object object,Collection attributes,Object returnedObject) throws AccessDeniedException;boolean supports(ConfigAttribute attribute);boolean supports(Class clazz);}Spring Framework - Security Dmitry Noskov 80. Configuration custom provider custom managerSpring Framework - Security Dmitry Noskov 81. @Post @PostAuthorize@PreAuthorize("hasRole(ROLE_USER)")@PostAuthorize("hasPermission(returnObject, read)")public Employee getEmployeeByName(String name) {} @PostFilter@PreAuthorize("hasRole(ROLE_USER)")@PostFilter("hasPermission(filterObject, read)")public List getEmployees() {}Spring Framework - Security Dmitry Noskov 82. JSP tag library Spring Framework - Security Dmitry Noskov 83. Authentication

Logged in: ${user.name}

Spring Framework - Security Dmitry Noskov 84. Authorize (1)Spring Framework - Security Dmitry Noskov 85. Authorize (2) This content will only be visible to users who have the "supervisor" authority in their list of GrantedAuthoritys.Spring Framework - Security Dmitry Noskov 86. Authorize (3) JSPThis content will only be visible to users who are authorizedto send requests to the "/admin" URL. security interceptor Spring Framework - Security Dmitry Noskov 87. ACL This will be shown if the user has either of the permissions represented by the values "1" or "2" on the given object. Spring Framework - Security Dmitry Noskov 88. SummarySpring Framework - Security Dmitry Noskov 89. Separation of concerns business logic is decoupled from security concern authentication and authorization are decoupledSpring Framework - Security Dmitry Noskov 90. Flexibility authentication mechanisms basic, form, cookies, SSO user data storage RDBMS, LDAP, etc. based on SpringSpring Framework - Security Dmitry Noskov 91. Portability portable across containers can be deployed as-is runs in standalone environment Spring Framework - Security Dmitry Noskov 92. BooksSpring Framework - Security Dmitry Noskov 93. Links main featureshttp://static.springsource.org/spring-security/site/features.html articleshttp://static.springsource.org/spring-security/site/articles.html referencehttp://static.springsource.org/spring-security/site/docs/3.0.x/reference/springsecurity.html bloghttp://blog.springsource.com/category/security/ refcardzhttp://refcardz.dzone.com/refcardz/expression-based-authorization Spring Framework - Security Dmitry Noskov 94. QuestionsSpring Framework - Core Dmitry Noskov 95. The end http://www.linkedin.com/in/noskovdhttp://www.slideshare.net/analizator/presentations