{"id":3978,"date":"2020-10-04T04:52:13","date_gmt":"2020-10-04T04:52:13","guid":{"rendered":"https:\/\/codethataint.com\/blog\/?p=3978"},"modified":"2021-04-13T11:24:12","modified_gmt":"2021-04-13T11:24:12","slug":"spring-security-interview","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/spring-security-interview\/","title":{"rendered":"Spring Security Interview"},"content":{"rendered":"<ol>\n<li><strong>What is the difference between FormBased and BasicAuth?<\/strong><br \/>\nThe Difference between FormAuth and BasicAuth is in BasicAuth UserName and Password would be sent everytime when making a request to the server in the header as base64 encoded character. BasicAuth happens at http Protocol level where as Formbased Auth happens at Framework level.\n<\/li>\n<li><strong>What is the difference between JKS and PKCS12?<\/strong><br \/>\nJKS is the most common if you stay within the Java world. PKCS#12 isn&#8217;t Java-specific, it&#8217;s particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools.JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it&#8217;s a Java specific keystore, so it cannot be used in other programming languages.PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.<\/p>\n<\/li>\n<li>\n<strong>How safe is Userid and Password in Basic Auth?<\/strong><br \/>\nUserId and Password in BasicAuth would transferred using base64 encoded UserName and Password attached to Header prepending Basic<\/p>\n<pre>\r\nAuthorization : Basic base64(UserId:Password)\r\n<\/pre>\n<\/li>\n<li><strong>How POST, PUT and DELETE works in Basic Auth?<\/strong><br \/>\nIn Basic Auth with respect to Spring Security CSRF Token would be used incase CSRF is enabled. If CSRF is disabled Authorization in header would be used<br \/>\nfor access. <em>csrf().disable()<\/em> should be always used incase you are using other than GET method.\n<\/li>\n<li><strong>What is JSESSIONID?<\/strong><br \/>\nJSESSIONID which is generated and Stored as Cookie in Postman helps the spring boot app to recognizane whether the User is Authenticated or not.\n<\/li>\n<li><strong>How Spring Security handles CSRF in client Side when enabled?<\/strong><br \/>\nSpring Security generates JSESSIONID  and XSRF-TOKEN. Both were Set in Cookie. On Subsequent request X-XSRF-TOKEN should be sent in Header for Authorization.\n<\/li>\n<li><strong>What happens when I delete XSRF token in Cookie?<\/strong><br \/>\nNew Token would be generated based on JSESSIONID in cookie\n<\/li>\n<li><strong>What happens when I delete XSRF token and in Cookie and try POST, DELETE and PUT over API?<\/strong><br \/>\nNew JSESSIONID would be generated and placed in cookie. For this X-XSRF-TOKEN should be passed in header.\n<\/li>\n<li><strong>Where is JSESSION stored?<\/strong><br \/>\nJSESSION is session ID which is stored in Inmemory Database in Server and in a Cookie in Client Side.\n<\/li>\n<li><strong>What is the default Expiration time of JSESSION Cookie?<\/strong><br \/>\n30 Minutes\n<\/li>\n<li><strong>Spring Security Arcitecture?<\/strong><br \/>\n<img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2020\/10\/DefaultConfig.jpg\" alt=\"\" \/>\n<\/li>\n<li><strong>Encoding vs Encrytion vs Hashing?<\/strong><br \/>\n<strong>Encoding <\/strong>refers to any transformation of a given input. For example, if we have a function x that reverses a string, function x -> y applied to ABCD produces DCBA.<\/p>\n<pre>\r\nx -> y\r\n<\/pre>\n<p><strong>Encryption<\/strong> is a particular type of encoding where, to obtain the output, you provide both the input value and a key. The key makes it possible for choosing afterward who should be able to reverse the function (obtain the input from the output). The simplest form of representing encryption as a function looks like this:<\/p>\n<pre>\r\n(x, k) -> y\r\n<\/pre>\n<p>where x is the input, k is the key, and y is the result of the encryption. This way, an individual knows the key can use a known function to obtain the input from the output (y, k) -> x. We call this reverse function decryption. If the key used for encryption is the same as the one used for decryption, we usually call it a <strong>symmetric key<\/strong>.If we have two different keys for encryption ((x, k1) -> y) and decryption ((y,k2) -> x), then we say that the encryption is done with <strong>asymmetric keys<\/strong>. Then (k1,k2) is called a <strong>key pair<\/strong>. The key used for encryption, k1, is also referred to as the public key, while k2 is known as the private one. This way, only the owner of the private key can decrypt the data. <\/p>\n<p><strong>Hashing <\/strong>is a particular type of encoding, except the function is only one way. That is,from an output y of the hashing function, you cannot get back the input x. However,there should always be a way to check if an output y corresponds to an input x, so we can understand the hashing as a pair of functions for encoding and matching. If hashing is x -> y, then we should also have a matching function (x,y) ->boolean. <\/p>\n<pre>\r\n(x,y) ->boolean\r\n<\/pre>\n<p>Sometimes the hashing function could also use a random value added to the input:<br \/>\n(x, k) -> y. We refer to this value as <strong>salt<\/strong>. The salt makes the function stronger, enforcing the difficulty of applying a reverse function to obtain the input from the<br \/>\nresult.<\/p>\n<li><strong>Two ways of Configuring Spring Security?<\/strong><br \/>\nMethod 1: Adding userservice and passwordEncoder in configure method(Not Recommended)<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n@Configuration\r\npublic class ProjectConfig extends WebSecurityConfigurerAdapter {\r\n    @Override\r\n    protected void configure(AuthenticationManagerBuilder auth) throws Exception {\r\n        auth.inMemoryAuthentication()\r\n                .withUser(&quot;john&quot;)\r\n                .password(&quot;12345&quot;)\r\n                .authorities(&quot;read&quot;)\r\n                .and()\r\n                .passwordEncoder(NoOpPasswordEncoder.getInstance());\r\n    }\r\n}\r\n<\/pre>\n<p>Method 2: Using Seperate Configuration class for Bean and injecting beans(Recommended Method)<br \/>\n<strong>PasswordConfig.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n@Configuration\r\npublic class PasswordConfig {\r\n    @Bean\r\n    public PasswordEncoder passwordEncoder()\r\n    {\r\n        return new BCryptPasswordEncoder(10);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>ApplicationSecurityConfig.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n@Configuration\r\n@EnableWebSecurity\r\npublic class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {\r\n   @Autowired\r\n   private PasswordEncoder passwordEncoder; \r\n \r\n    @Override\r\n    @Bean\r\n    protected UserDetailsService userDetailsService() {\r\n\t   UserDetails mugilUsrBuilder = User.builder()\r\n\t\t\t   .username(&quot;Mugil&quot;)\r\n\t\t\t   .password(this.passwordEncoder.encode(&quot;password&quot;))\r\n\t\t\t   .roles(&quot;ADMIN&quot;)\r\n\t\t\t   .build();\r\n \r\n\t   return new InMemoryUserDetailsManager(mugilUsrBuilder);\r\n    }\r\n\r\n \r\n    @Override\r\n    protected void configure(HttpSecurity httpSecurity) throws Exception{\r\n        httpSecurity.csrf().disable()\r\n                     .authorizeRequests()\r\n                     \/\/Whitelisting URLS\r\n                    .antMatchers(&quot;\/&quot;, &quot;index&quot;, &quot;\/css\/*&quot;, &quot;\/js\/*&quot;).permitAll()\r\n                    .antMatchers(HttpMethod.GET,&quot;\/api\/**&quot;).permitAll()\r\n                    .antMatchers(HttpMethod.DELETE,&quot;\/api\/**&quot;).hasRole(&quot;ADMIN&quot;)\r\n                    .antMatchers(HttpMethod.PUT,&quot;\/api\/**&quot;).hasRole(&quot;ADMIN&quot;)\r\n                    .antMatchers(HttpMethod.POST,&quot;\/api\/**&quot;).hasRole(&quot;ADMIN&quot;)\r\n                    .anyRequest()\r\n                    .authenticated()\r\n                    .and()\r\n                    .httpBasic();\r\n    }\r\n}\r\n<\/pre>\n<\/li>\n<li>What are the interface methods available in Spring Security?<br \/>\n<table>\n<tr>\n<td>UserDetailsManager<\/td>\n<td>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">public interface UserDetailsManager extends UserDetailsService {\r\nvoid createUser(UserDetails user);\r\nvoid updateUser(UserDetails user);\r\nvoid deleteUser(String username);\r\nvoid changePassword(String oldPassword, String newPassword);\r\nboolean userExists(String username);\r\n}<\/pre>\n<\/td>\n<\/tr>\n<tr>\n<td>UserDetailsService<\/td>\n<td>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">public interface UserDetailsService {\r\nUserDetails loadUserByUsername(String username)\r\nthrows UsernameNotFoundException;\r\n}<\/pre>\n<\/td>\n<\/tr>\n<tr>\n<td>UserDetails<\/td>\n<td>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">public interface UserDetails extends Serializable {\r\nString getUsername();\r\nString getPassword();\r\nCollection&lt;? extends GrantedAuthority&gt;\r\n\u27a5getAuthorities();\r\nboolean isAccountNonExpired();\r\nboolean isAccountNonLocked();\r\nboolean isCredentialsNonExpired();\r\nboolean isEnabled();\r\n}<\/pre>\n<\/td>\n<\/tr>\n<tr>\n<td>AuthenticationProvider<\/td>\n<td>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">public interface AuthenticationProvider {\r\nAuthentication authenticate(Authentication authentication)\r\nthrows AuthenticationException;\r\nboolean supports(Class&lt;?&gt; authentication);\r\n}<\/pre>\n<\/td>\n<\/tr>\n<tr>\n<td>Authentication<\/td>\n<td>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">public interface Authentication extends Principal, Serializable {\r\nCollection&lt;? extends GrantedAuthority&gt; getAuthorities();\r\nObject getCredentials();\r\nObject getDetails();\r\nObject getPrincipal();\r\nboolean isAuthenticated();\r\nvoid setAuthenticated(boolean isAuthenticated)\r\nthrows IllegalArgumentException;\r\n}<\/pre>\n<\/td>\n<\/tr>\n<\/table>\n<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>What is the difference between FormBased and BasicAuth? The Difference between FormAuth and BasicAuth is in BasicAuth UserName and Password would be sent everytime when making a request to the server in the header as base64 encoded character. BasicAuth happens at http Protocol level where as Formbased Auth happens at Framework level. What is the&hellip; <a href=\"https:\/\/codethataint.com\/blog\/spring-security-interview\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[326],"tags":[],"class_list":["post-3978","post","type-post","status-publish","format-standard","hentry","category-interview-questions-spring-security"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3978","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=3978"}],"version-history":[{"count":5,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3978\/revisions"}],"predecessor-version":[{"id":4221,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3978\/revisions\/4221"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=3978"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=3978"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=3978"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}