Questions

Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 10

What is OAuth 2.0?

Ans:

OAuth 2.0 released in October 2012 to overcome the problem as specified above in OAuth 1.0. The
OAuth 2.0 authorization framework allows a third-party application to gain limited access to an HTTP
service, either on behalf of a resource owner by orchestration of an approval agreement between the
resource owner and the HTTP service, or by requiring the third-party application to obtain access on its
own behalf.

The Client Application requests an access token from the Authorization Server by passing credentials
received from the resource owner.

The Authorization Server authenticates the client by validating the resource owner credentials. Once
Validation is successful and if request is valid, it sends an access token.

Client sends the received access token to Resource Server to access the resource end point.

Resource Server validates the access token by calling Authorization Server.

If the token is valid, resource server return the requested resource to Client.

List<String> names = List.of("Lokesh", "Amit", "John");

//Preserve the elements order

System.out.println(names);

//names.add("Brian"); //UnsupportedOperationException occured

//java.lang.NullPointerException

//List<String> names2 = List.of("Lokesh", "Amit", "John", null);


Set<String> names = Set.of("Lokesh", "Amit", "John");

//Elements order not fixed

System.out.println(names);

//names.add("Brian"); //UnsupportedOperationException occured

//java.lang.NullPointerException

//Set<String> names2 = Set.of("Lokesh", "Amit", "John", null);

//java.lang.IllegalArgumentException

//Set<String> names3 = Set.of("Lokesh", "Amit", "John", "Amit");

Map<String, String> names = Map.ofEntries(

Map.entry("1", "Lokesh"),

Map.entry("2", "Amit"),

Map.entry("3", "Brian"));

System.out.println(names);

//UnsupportedOperationException

//names.put("2", "Ravi");

What is Spring Security?

Ans:
Spring Security is a framework that focuses on providing authentication, authorization, and protection
against common attacks.

Spring Security enables a programmer to impose security restrictions to Spring-framework-based Web


applications through JEE components. In short, it is a library that can be used, extended to customize as
per the programmer's needs.

Q: Why Security is needed in application?

Ans:

Security of applications is very important because now a days applications are often accessible over
multiple networks and connected to the cloud, growing vulnerabilities to security threats and breaches.

Q: What is Delegating Filter Proxy?

Ans:

Spring makes use of the DelegatingFilterProxy for implementing security mechanisms.

It is a Proxy for standard Servlet Filter, delegating to a Spring-managed bean that implements the Filter
interface. Its the starting point in the springSecurityFilterChain which instantiates the Spring Security
filters according to the Spring configuration.

Some of the features of Spring Security are:

Support for both Authentication and Authorization

Protection against attacks like session fixation, clickjacking, cross site request forgery, etc

Servlet API integration Optional integration with Spring Web MVC

Q: What is Security Context and Security Context Holder in Spring Security?

Ans:

The SecurityContext and SecurityContextHolder are two fundamental classes of Spring Security. The
SecurityContext is used to store the details of the currently authenticated user, also known as a principle.
Q: What is Basic Authentication?

Ans:

Basic Authentication is a way to provide authentication by passing username and password as part of our
request, using HTTP [Authorization] header to allows user to access the resource.

Syntax of basic Authentication

Value = username:password

Encoded Value = base64(Value)

Authorization Value = Basic <Encoded Value>

//Example: Authorization: Basic VGVzdFVzZXI6dGVzdDEyMw==

//Decode it'll give back the original username:password TestUser:test123

Q: How to implement Spring Boot + Basic Authentication?

Ans:

You can implement Basic Authentication by following steps:

Create Spring boot project from Spring Initializr

Add spring-boot-starter-security maven dependency in pom.xml.

Configure the user and password in application.yml

Configure Spring Security by extending WebSecurityConfigurerAdapter to enable the basic


authentication for our REST API. Override configure method, to use HTTP basic authentication.

Create some simple rest end point to test the basic authentication, which can configure in the above
step.

Test above created Rest end point.

What is ssl and why it is used?

Ans:
Secure Sockets Layer (SSL) was the most commonly used cryptographic protocol to provide security over
internet communications.

SSL provides a secure channel between two machines or devices running over the internet or an internal
network. A common example is when SSL is used to secure/protect communication between a web
browser and a web server. This changes the address of the website from HTTP to HTTPS, basically 'S'
stands for 'Secure'.

Q: How do I know a Website is Secure with SSL?

Ans:

Take a look at the URL of the website. If it starts with "https" instead of "http" it means that the site is
protected using an SSL certificate (S stands for secure). SSL certificates secure all of your data as it is
transferred from your browser to the web server.

Q: Why do we need SSL certificate for website?

Ans:

The SSL certificate encrypts data that goes back and forth from the user's device to the target website.
Any time a user enters information on your site, SSL ensures that they can navigate securely from their
browser to your web server.

Can we create our own SSl Certificate to enable HTTPS for website?

Ans:

Yes, we can create SSL certificate by using keytool. SSL certificates have a key pair: a public and a private
key. These keys work together to establish an encrypted connection.

Follow the below steps to enable HTTPS for website:

Generate an SSL certificate in a keystore.


Verify the keystore content.

Convert a JKS keystore into PKCS12.

Configuring/Enable SSL in Spring Boot.

Configure Spring Security to require HTTPS requests.

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 the
FilterSecurityInterceptor.

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 over
HttpSecurity.

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.

You might also like