Most Frequently asked JWT Interview Questions (2024)
In this post, questions of JWT Interviews will be answered for Experienced and Freshers. We're trying to share our experience and learn how to help you make progress in your career.
Spring Boot Security Interview Questions:
Q: What is JWT? How to implement?
Ans:
JSON Web Token (JWT) is an open standard (RFC 7519) that specifies a compact and self-contained way of transmitting information securely as a JSON object between parties. This information can be verified and trusted as it has been digitally signed. It can also hold all the user's claim, like authorization information, so that the service provider does not need to access the database to validate user roles and permissions for each request; data is extracted from the token.
Refer Spring Boot Security + JWT (JSON Web Token) Authentication Example for implementation.
Q: What is Workflow of JWT?
Ans:
- Customers sign in by submitting their credentials to the provider.
- Upon successful authentication, it generates JWT containing user details and privileges for accessing the services and sets the JWT expiry date in payload.
- The server signs and encrypts the JWT if necessary and sends it to the client as a response with credentials to the initial request.
- Based on the expiration set by the server, the customer/client stores the JWT for a restricted or infinite amount of time.
- The client sends this JWT token in the header for all subsequent requests.
- The client authenticates the user with this token. So we don't need the client to send the user name and password to the server during each authentication process, but only once the server sends the client a JWT.
Q: What is the structure of JWT?
Ans:
JWT consists of 3 parts - Header.Payload.Signature
It generate JWT token as in the form of
a
.b
.c
which represent
header
.payload
.signature
Q: What is expiration date of JWT?
Ans:
The JWT access token is only valid for a limited period of time. Using an expired JWT would cause the operation to fail. This value is normally 1200 seconds or 20 minutes.
Q: How do we specify expiration date of JWT?
Ans:
private String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + jwtExpirationInMs)).signWith(SignatureAlgorithm.HS512, secret).compact();
}
Q: What are the advantages of JWT?
Ans:
- Good Performance: JWT itself contains all information, so we don't have to go to Authorization server to get the user's information to verify whether user is valid or not.
- Portable: Allow to use multiple backends with single access token.
- It is Very Mobile Friendly, because cookies are not required.
- JWT contains expiration date as a claim that can be used to determine when the access token is going to expire.
- It's very secure way to validate the user information, as it's digitally signed.
- It's digitally signed, so if anyone updates it the server will know about it.
- It is most suitable for Microservices Architecture.
- It has other advantages like specifying the expiration time.
Checkout our related posts :
Q: How to implement JWT with MYSQL?
Ans:
Refer Spring Boot Security + JWT (JSON Web Token) Authentication using MYSQL Example for implementation.
Q: How to implement JWT with Angular?
Ans:
Refer Angular 8 + Spring Boot JWT (JSON Web Token) Authentication Example for implementation.
Q: What is OAuth and JWT?
Ans:
JWT is essentially a token format. JWT is a token that can be used as part of the OAuth authorization protocol. Server-side and client-side storage are used in OAuth. If you want to make a proper logout, you'll need to use OAuth2. Authentication with a JWT token does not allow you to logout.
Refer Implementation of OAuth2 with JWT Access Token Example.
Refer Advantage of JWT as OAuth Access Token Vs OAuth Default Token
Q: Is JWT required while communicating over HTTPS?
Ans:
The JWT is signed with public/private key pairs to ensure that the sender is authenticated and that the payload has not been tampered with. The JSON Web Token, on the other hand, is in plain text.
To encrypt communication, we will require SSL/HTTPS. Attackers can intercept network traffic without SSL/HTTPS and extract the JWT, making your application vulnerable to man in the middle attacks.
Refer Enable https (http+ssl) Example
Q: Why JWT is a stateless authentication?
Ans:
JSON Web Tokens (JWT) are called stateless because the authorizing server doesn't need to keep track of anything, the token is all that's required to verify a token bearer's authorization. In stateless authentication, no need to store user information in the session.
Refer to understand more why user not required to call authorizing server for verifying user identity.
Q: Does JWT token contain password?
Ans:
The JWT comprises encoded user information as well as a signature that is checked when decoded to confirm that the token has not been tampered with. After the JWT has been confirmed, instead of sending the user their forgotten password, your application can safely allow them to generate a new password.
Q: What is AbstractSecurityInterceptor in Spring Security?
Ans:
The AbstractSecurityInterceptor
in Spring Security handles the initial authorization of
an incoming request.
There are two concrete implementations of the AbstractSecurityInterceptor:
FilterSecurityInterceptor
The Spring Security filter chain's default filter. All authenticated user requests will be authorised by theFilterSecurityInterceptor
.MethodSecurityInterceptor
This is required for method level security to be implemented. It enables us to apply security to our programme at the method level.
What is Spring Boot Method-Level Security?
The @PreAuthorize
annotation is used on controller methods to implement method-level
security. This annotation comprises a snippet
of Spring Expression Language (SpEL) that is evaluated to determine whether the request should be
authenticated.
Refer implementation of Spring Boot Method Security with PreAuthorize Example
Q: What is difference of using @PreAuthorize
and @Secured
in Spring Security?
Ans:
@PreAuthorize
annotation is used to check for authorization before executing the
method.
We could alternatively use the @Secured
annotation in spring to handle method-level
security, however it has several limitations, such as
- We cannot have several conditions with the
@Secured
annotation, i.e. the roles cannot be coupled with an AND/OR condition. - Spring expression language is not supported by the
@Secured
annotation.
Q: What is the difference between hasRole()
and hasAuthority()
?
Ans:
Spring roles are authorities with the ROLE_prefix
. Another thing to understand of
it is that roles are meant for broad sets of permissions, whereas authorities are meant for
finer-grained management. However, that is only one possible usage. The developer is in charge
of the actual implementation. In this tutorial, authorities are used to map to
authorization groups.
@PreAuthorize("hasAuthority('Admin')")
@RequestMapping("/fetch-users")
@ResponseBody
public String protectedUserPage() {
return "TechGeekNext User";
}
------------------------------------------
@PreAuthorize("hasRole('admin')")
@RequestMapping("/fetch-users")
public String protectedUserPage() {
return "TechGeekNext User";
}
The crucial thing to remember is that in order to use hasRole()
, the authority name
in the claim must begin with ROLE_
. You might, for example, use hasRole('ADMIN')
if
you created a ROLE ADMIN group and added your user to it.
Q: What is difference between Spring Security's @PreAuthorize
and HttpSecurity
?
Ans:
- The first distinction is small, but it is important to note. Before controller mapping
occurs,
the HttpSecurity function rejects the request in a web request filter. The @PreAuthorize
assessment, on the other hand, occurs later, directly before the controller method is
executed.
This means that
HttpSecurity
configuration is done before@PreAuthorize
. - Second,
HttpSecurity
is associated with URL endpoints, whereas@PreAuthorize
is associated with controller methods and is located within the code next to the controller definitions. - The use of SpEL (Spring Expression Language ) is another advantage that
@PreAuthorize
has overHttpSecurity
.
Q: How to enable Method-level Security for Spring?
Ans:
The @PreAuthorize
annotation is enabled by the @EnableGlobalMethodSecurity(prePostEnabled
=
true)
annotation.
@Component
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
.......
.......
}
Refer for complete implementation of Spring Boot Method Security with PreAuthorize Example
Q: How to use Authorization Based On OAuth 2.0
with PreAuthorize
?
Ans:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(final HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
//.and().formLogin(); // <-- Without OAUTH
.and().oauth2Login(); // <-- With OAUTH
}
}
Q: Which open source tools are available for Oauth 2.0 /SAML/ OpenID Connect based SSO?
Ans:
Keycloak is a modern application and service-oriented open source Identity and Access Management system. Single-Sign-On (SSO), Identity Brokering and Social Login, User Federation, Client Adapters, an Admin Console, and an Account Management Console are some of the features offered by Keycloak.
It works with a variety of protocols, including Oauth 2.0, SAML 2.0 and OpenID Connect. User credentials can also be stored locally or via an LDAP or Kerberos backend.
When a user logs in successfully with Keycloak, they are given a token, which is saved as a cookie in the browser, and they are automatically sent back to the service they were trying to access. This token usually includes a username as well as information about the user's permissions.
Refer Spring Boot Keycloak SSO Example to understand it's implementation.