Spring Security Interview Questions & Answers

Question: What is token relay in Spring security?


How do you control the concurrent Active session using Spring Security? (answer)
Another Spring interview question which is based on Out of box feature provided by Spring framework. You can easily control How many active session a user can have with a Java application by using Spring Security.

Apart from that Spring Security also provides the "remember me" feature which you can use to provide easier access for your users by remembering their login details on their personal computer. You can further see Learn Spring Security course by Eugen Paraschiv to learn more about advanced details of Spring Security. 



21. How do you set up LDAP Authentication using Spring Security? (answer)
This is a very popular Spring Security interview question as Spring provides out of the box support to connect Windows Active Directory for LDAP authentication and with few configurations in Spring config file you can have this feature enabled.


22.  How to implement Role Based Access Control (RBAC) using Spring Security? (answer)
Spring Security provides a couple of ways to implement Role based access control like by using GrantedAuthority. See the article to learn more about it.



How to limit login attempts (says 3) in spring security?

1. we need to take total_login_Attempts and failed_count columns in user_login table.
2. check and update the value whenever user login and reset if successful.
3. if all 3 attempts get failed then provide message that your userid is blocked and reset it using forget password.

How to implement "Remember Me" in Spring Security?

Remember-me refers to web sites should remember the identity of an user between sessions. This is typically accomplished by sending a cookie to the browser, with the cookie being detected during future sessions and causing automated login to take place.

There are 2 approaches supported by spring security.
1.  Hash-Based Token with Cookie
2. Persistent Token Approach with Cookie.

1.  Hash-Based Token with Cookie : we need to specify below entry in spring-security.xml file 

      <http>
...
    <remember-me key="myAppKey"/>
  </http>

2. Persistent Token Approach with Cookie: 
Step 1. create table where we will store the token which will be sent along with cookie. 
CREATE TABLE persistent_logins (
    username varchar(64) not null,
    series varchar(64) not null,
    token varchar(64) not null,
    last_used timestamp not null,
    PRIMARY KEY (series)
);
Step 2. if xml based authentication then add the below entry in spring-security.xml

<remember-me
        token-validity-seconds="1209600"
remember-me-parameter="remember-me"
data-source-ref="dataSource" />
Step 3. if Java based configuration then perform below task.

@Override
 protected void configure(HttpSecurity http) throws Exception {

   http.authorizeRequests()
       .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
     .and()
       .formLogin()
         .successHandler(savedRequestAwareAuthenticationSuccessHandler())
  .loginPage("/login")
         .failureUrl("/login?error")
  .loginProcessingUrl("/auth/login_check")
  .usernameParameter("username")
  .passwordParameter("password")
     .and()
  .logout().logoutSuccessUrl("/login?logout")
     .and()
         .csrf()
     .and()
  .rememberMe().tokenRepository(persistentTokenRepository())
  .tokenValiditySeconds(1209600);
 }

 @Bean
 public PersistentTokenRepository persistentTokenRepository() {
  JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
  db.setDataSource(dataSource);
  return db;
 }

 @Bean
 public SavedRequestAwareAuthenticationSuccessHandler
                savedRequestAwareAuthenticationSuccessHandler() {

               SavedRequestAwareAuthenticationSuccessHandler auth
                    = new SavedRequestAwareAuthenticationSuccessHandler();
  auth.setTargetUrlParameter("targetUrl");
  return auth;
 }

 Step 4. PersistentTokenBasedRememberMeServices

This class can be used in the same way as TokenBasedRememberMeServices, but it additionally needs to be configured with a PersistentTokenRepository to store the tokens. There are two standard implementations.

  • InMemoryTokenRepositoryImpl which is intended for testing only.
  • JdbcTokenRepositoryImpl which stores the tokens in a database.

What is csrf? how to prevent from it?
CSRF stands for Cross-Site Request Forgery. It is an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated.
For example: user is valid and logged-in in the system but creates employee record from dummy page and hit the url of the application with some dummy data. He does not uses proper createemployee.jsp page which is sent by the web application. 
look at the picture to understand.

step 1: user logs in with proper username and password.

boot-42_4


Step 2: after successful login he got his admin page from the application redirect.
boot-35_7
Step 3: he does not close the window and creates html page (says hack.html) in his local machine with below code.
<form method = "post" action="http://localhost:8080/addNewEmployee">
<input id ="empId" type="hidden" name="empId" value="Hacker001"/>
<input id ="empName" type="hidden" name="empName" value="hacker"/>
<input type="SUBMIT" value="Surprise..Surprise..See What This Does" />
</form>
Step 4: open in the browser and click on submit button. this will create new record in the DB.
boot-44_2



CSRF attacks specifically target state-changing requests, not theft of data

How to prevent this?
Step 1: we should send csrf token from each page to browser and should accept it.
Step 2: if there is csrf token in the request then just reject the request.
boot-44_1

we can achieve this by performing 2 steps
Step 1: remove the csrf.disable() from spring-security configuration.
Step 2: all the jsp pages add the spring security taglib and the csrf token tag
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> 
<sec:csrfInput />

https://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/remember-me.html


Difference between CSRF and CORS

1. CSRF stands for Cross-Site-Request-Forgery. It restricts resource/URL based on Authorization token.
    CORS stands Cross-Origin-Resource-Sharing. it restricts resource/URL, if request is coming from different application.

2. code inside method again URL will not gets executed if CSRF is enabled.
     But code inside gets executed but response will be sent to client if CORS is enabled for any URL.






Session handling in spring security?https://www.baeldung.com/spring-security-session

https://www.concretepage.com/spring/spring-security/session-management-in-spring-security

https://www.javainuse.com/spring/springboot_session





https://www.baeldung.com/learn-spring-security-course?utm_source=javarevisited&utm_medium=web&utm_campaign=lss&affcode=22136_bkwjs9xa


SHARE

esant technology

0 comments :

Post a Comment