Thursday, March 1, 2018

Spring Security




1.CONFIGURE AUTHENTICATION MANAGER


1.1 CONFIGURE JDBC AUTHENTICATION

1.2 CONFIGURE LDAP AUTHENTICATION

1.1 CONFIGURE KERBEROS  AUTHENTICATION

2.CONFIGURE AUTHERIZATION

1.1 CONFIGURE JDBC AUTHENTICATION

1.2 CONFIGURE LDAP AUTHENTICATION

1.1 CONFIGURE KERBEROS  AUTHENTICATION



org.springframework.security.authentication.encoding.PasswordEncoder

  • BaseDigestPasswordEncoder
  • BasePasswordEncoder
  • LdapShaPasswordEncoder
  • Md4PasswordEncoder,
  • Md5PasswordEncoder
  • MessageDigestPasswordEncoder
  • MessageDigestPasswordEncoder
  • PlaintextPasswordEncoder
  • ShaPasswordEncoder


3.RESTICTING PAGE ACCESS


The taglib contains three useful tags: 
  • authorize
  • authentication
  • accesscontrollist

4.METHOD SECURITY



4.1

Method level authorization using Spring’s in-house annotations 


  • @PreAuthorize("spEL expression")e.g @PreAuthorize('hasRole('ROLE_USER')')
  • @PostAuthorize("spEL expression")
  • @Secure

4.2

  • @RolesAllowed({“ROLE_USER”,”ROLE_ADMIN”})
  • @PermitAll
  • @DenyAll

@RolesAllowed({"ROLE_ADMIN","ROLE_USER"})
  public void deleteUser(String username);





kerberos
https://seenukarthi.com/security/2014/08/13/localhost-authentication-spring-kerberos/
https://dzone.com/articles/microservices-and-kerberos-authentication

https://memorynotfound.com/spring-security-spring-ldap-authentication-example/
_______________________________________________________________________

https://spring.io/guides/topicals/spring-security-architecture/
https://www.concretepage.com/spring/spring-security/
https://www.concretepage.com/spring/spring-security/authentication-authorization-spring-security
https://www.concretepage.com/spring/spring-security/spring-security-login-example-database
https://www.concretepage.com/spring/spring-security/how-use-password-encoder-spring-security
https://www.concretepage.com/spring/spring-security/how-to-add-channel-security-in-spring
https://www.concretepage.com/spring/spring-security/session-management-in-spring-security
https://www.concretepage.com/spring/spring-security/how-to-access-roles-and-user-details-using-spring-security
https://www.concretepage.com/spring/spring-security/example-of-security-pointcuts-in-spring
https://www.concretepage.com/spring/spring-security/spring-security-using-secured-annotation

https://www.concretepage.com/spring/spring-security/preauthorize-postauthorize-in-spring-security
https://www.concretepage.com/spring/spring-security/prefilter-postfilter-in-spring-security
https://www.concretepage.com/spring/spring-security/built-in-expressions-and-objects-in-spring-security
https://www.concretepage.com/spring/spring-security/spring-mvc-security-in-memory-authentication-example-with-authenticationmanagerbuilder-using-java-configuration
https://www.concretepage.com/spring/spring-security/spring-mvc-security-jdbc-authentication-example-with-custom-userdetailsservice-and-database-tables-using-java-configuration
https://www.concretepage.com/spring/spring-security/prefilter-postfilter-in-spring-security
https://www.concretepage.com/spring/spring-security/spring-mvc-security-jdbc-authentication-example-with-custom-userdetailsservice-and-database-tables-using-java-configuration

https://www.concretepage.com/spring/spring-security/spring-mvc-security-in-memory-authentication-example-with-authenticationmanagerbuilder-using-java-configuration

https://javapapers.com/spring/spring-component-service-repository-controller-difference/

http://javasampleapproach.com/spring-framework/spring-bean-scope-annotation-requestscope-sessionscope-applicationscope

http://javasampleapproach.com/spring-framework/spring-mvc/spring-requestattribute-annotation-spring-mvc

https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans

https://stackoverflow.com/questions/25583355/spring-service-default-scope

https://javapapers.com/spring/spring-component-service-repository-controller-difference/

https://spring.io/guides/topicals/spring-security-architecture/
https://spring.io/guides/topicals/spring-security-architecture/#_authentication_and_access_control
https://spring.io/guides/topicals/spring-security-architecture/#_web_security
https://spring.io/guides/topicals/spring-security-architecture/#_method_security
https://spring.io/guides/topicals/spring-security-architecture/#_working_with_threads


https://shekhargulati.com/2010/10/30/spring-scoped-proxy-beans-an-alternative-to-method-injection/
https://www.logicbig.com/tutorials/spring-framework/spring-core/scoped-proxy.html
http://sanseeni.blogspot.in/2011/12/understanding-scoped-proxy-in-spring.html


-->
How is security implemented in Spring?
HTTP BASIC AUTHENTICATION:
This endpoint simulates a basic-auth protected endpoint. The endpoint accepts a default username and password and returns a status code of 200 ok only if the same is provided. Otherwise it will return a status code 401 unauthorized.

Username: postman

Password: password
To use this endpoint, send a request with the header Authorization: Basic cG9zdG1hbjpwYXNzd29yZA==. The cryptic latter half of the header value is a base64 encoded concatenation of the default username and password. Using Postman, to send this request, you can simply fill in the username and password in the "Authorization" tab and Postman will do the rest for you.

HTTP DIGEST AUTHETICATION
Digest authentication protects an endpoint with a username and password without actually transmitting the password over network. One has to apply a hash function (like MD5, etc) to the username and password before sending them over the network.                                                                                                                      authentication happens using two consecutive requests where the first request returns 401 Unauthorised along with WWW-Authenticate header containing information that needs to be used to authenticate subsequent calls.

HTTP X.509 CERTIFICATION


LDAP


FORM BASED


OPENID


CAS


JAAS


KERBEROS


JOSSO


OAUTH
OAuth1.0a is a specification that defines a protocol that can be used by one service to access "protected" resources (endpoints) on another service. A major part of OAuth1.0 is HTTP Request Signing. This endpoint allows you to check whether the request calculation works properly in the client.

The endpoint supports the HTTP Authorization header. In case the signature verification fails, the endpoint provides the four debug values,

base_uri
normalized_param_string
base_string
signing_key

This endpoint is a Hawk Authentication protected endpoint. Hawk authentication is a widely used protocol for protecting API endpoints. One of Hawk's main goals is to enable HTTP authentication for services that do not use TLS (although it can be used in conjunction with TLS as well).

In order to use this endpoint, select the "Hawk Auth" helper inside Postman, and set the following values:

Hawk Auth ID: dh37fgj492je

Hawk Auth Key: werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn

Algorithm: sha256

The rest of the values are optional, and can be left blank. Hitting send should give you a response with a status code of 200 OK.


25. How to implement Spring Security
Step1: include spring-security-config jar is on your classpath
http://www.springframework.org/schema/beans"
  xmlns:security="http://www.springframework.org/schema/security"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
    ...



Step 2: The first thing you need to do is add the following filter declaration to your web.xml file:1. This needs to be added first to add any security related configurations in applications-xml file
  springSecurityFilterChain

  org.springframework.web.filter.DelegatingFilterProxy


  springSecurityFilterChain

  /*






Step3: Spring Security web infrastructure. DelegatingFilterProxy
If you are using xml configurations  then  else the same  code will move into java class
    /**" access="ROLE_USER" />
 

    
    /login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    /**" access="ROLE_USER" />
    />
 



To add some users, you can define a set of test data directly in the namespace:

   
     
        jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
        bob" password="bobspassword" authorities="ROLE_USER" />
     

   

 






24. List the spring security jars
There are 7 jars.


spring-security-core.jar
core authentication and access-contol classes and interfaces, remoting support and basic provisioning APIs
org.springframework.security.core

org.springframework.security.access

org.springframework.security.authentication

org.springframework.security.provisioning

org.springframework.security.remoting


spring-security-web.jar
Contains filters and related web-security infrastructure code. Anything with a servlet API dependency. You'll need it if you require Spring Security web authentication services and URL-based access-control. The main package is org.springframework.security.web.


spring-security-config.jar
Contains the security namespace parsing code (and hence nothing that you are likely yo use directly in your application). You need it if you are using the Spring Security XML namespace for configuration. The main package is org.springframework.security.config.


spring-security-ldap.jar
LDAP authentication and provisioning code. Required if you need to use LDAP authentication or manage LDAP user entries. The top-level package is org.springframework.security.ldap.


spring-security-acl.jar
Specialized domain object ACL implementation. Used to apply security to specific domain object instances within your application. The top-level package is org.springframework.security.acls.


spring-security-cas-client.jar
Spring Security's CAS client integration. If you want to use Spring Security web authentication with a CAS single sign-on server. The top-level package is org.springframework.security.cas.


Spring-security-OpenID.jar
OpenID web authentication support. Used to authenticate users against an external OpenID server. org.springframework.security.openid. Requires OpenID4Java

25. HOW WILL YOU CONFIGURE SPIRNG SECURITY ANNOTATION BASED ?
STEP1 : ADD MAVEN DEPENDENICES
STEP2: WILL CREATE CONFIGURATION CLASS ~ HTTP XML TAG
By extending WebSecurityConfigurerAdapter  
@Configuration
@EnableWebSecurity
Two methods:
configureGlobal(AutheticationManager auth)
auth.inMemoryAuthetication().withUser().password(“123456”).roles(“USER”)
configure(HttpSecurity)
http.autherizeRequest.antMatcher().access();
-----------------------------
CREATE  SPRINGSECURITYWEBAPPLICAITON  INITIALIZER CLASS TO MAP FILTER CHAIN
S package com.mkyong.config.core;  import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;  public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {    //do nothing }
pringSecuirtyInitializer  extends AbstractSecurityWebApplicationInitializer

STEP 4:
@EnableWebMvc
 @Configuration
 @ComponentScan({ "com.mkyong.web.*" })
 @Import({ SecurityConfig.class }) 
public class AppConfig {
STEP5:


  public class SpringMvcInitializer        extends AbstractAnnotationConfigDispatcherServletInitializer {




<http auto-config="true">
         <intercept-url pattern="/admin**" access="ROLE_ADMIN" />       
<intercept-url pattern="/dba**" access="ROLE_ADMIN,ROLE_DBA" />
 </http>  <authentication-manager> 
 <authentication-provider>   
 <user-service>
         <user name="mkyong" password="123456" authorities="ROLE_USER" />         <user name="admin" password="123456" authorities="ROLE_ADMIN" />      <user name="dba" password="123456" authorities="ROLE_DBA" />  
  </user-service>  
</authentication-provider>
</authentication-manager>

Create a class extends AbstractSecurityWebApplicationInitializer, it will load the springSecurityFilterChain automatically.






http://www.mkyong.com/spring-security/spring-security-hello-world-annotation-example/


26.SECURITY LINKS
https://spring.io/guides/tutorials/spring-security-and-angular-js/







What is Basic Authentication?
Basic Authentication provides a solution for this problem, although not very secure. With Basic Authentication, clients send it’s Base64 encoded credentials with each request, using HTTP [Authorization] header . That means each request is independent of other request and server may/does not maintain any state information for the client, which is good for scalability point of view.

String plainClientCredentials="myusername:mypassword";
String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));

HttpHeaders headers = getHeaders();
headers.add("Authorization", "Basic " + base64ClientCredentials);



How will you configure Basic Authentication & Spring Security?
With two steps, you can enable the Basic Authentication in Spring Security Configuration.

1. Configure httpBasic : Configures HTTP Basic authentication. [http-basic in XML]
2. Configure authentication entry point with BasicAuthenticationEntryPoint :

In case the Authentication fails [invalid/missing credentials], this entry point will get triggered. It is very important, because we don’t want [Spring Security default behavior] of redirecting to a login page on authentication failure [We don't have a login page].


How will you configure Basic Authentication & Spring Security ?
With two steps, you can enable the Basic Authentication in Spring Security Configuration.

1. Configure httpBasic : Configures HTTP Basic authentication. [http-basic in XML]
2. Configure authentication entry point with BasicAuthenticationEntryPoint :

In case the Authentication fails [invalid/missing credentials], this entry point will get triggered. It is very important, because we don’t want [Spring Security default behavior] of redirecting to a login page on authentication failure [We don't have a login page].
150 questions
client interviews
logics good



How will you configure Basic Authentication & Spring Security ?
With two steps, you can enable the Basic Authentication in Spring Security Configuration.

1. Configure httpBasic : Configures HTTP Basic authentication. [http-basic in XML]
2. Configure authentication entry point with BasicAuthenticationEntryPoint :

In case the Authentication fails [invalid/missing credentials], this entry point will get triggered. It is very important, because we don’t want [Spring Security default behavior] of redirecting to a login page on authentication failure [We don't have a login page].





Spring 4 Security Features

Spring 3.x Security Framework provides the following Features:
  1. Authentication and Authorization.
  2. Supports BASIC,Digest and Form-Based Authentication.
  3. Supports LDAP Authentication.
  4. Supports OpenID Authentication.
  5. Supports SSO (Single Sign-On) Implementation.
  6. Supports Cross-Site Request Forgery (CSRF) Implementation.
  7. Supports “Remember-Me” Feature through HTTP Cookies.
  8. Supports Implementation of ACLs
  9. Supports “Channel Security” that means automatically switching between HTTP and HTTPS.
  10. Supports I18N (Internationalisation).
  11. Supports JAAS (Java Authentication and Authorization Service).
  12. Supports Flow Authorization using Spring WebFlow Framework.
  13. Supports WS-Security using Spring Web Services.
  14. Supports Both XML Configuration and Annotations. Very Less or minimal XML Configuration.
Spring 4.x Security Framework supports the following New Features:
  1. Supports WebSocket Security.
  2. Supports Spring Data Integration.
  3. CSRF Token Argument Resolver.

No comments:

Post a Comment