0% found this document useful (0 votes)
111 views7 pages

Spring Security

The document discusses Spring Security which provides authentication and authorization for Java applications. It describes how Spring Security can be used to secure web applications and REST APIs. It also discusses different approaches for authentication including using in-memory users, JDBC, and LDAP. The document contains code examples of configuring Spring Security.

Uploaded by

Java Pro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views7 pages

Spring Security

The document discusses Spring Security which provides authentication and authorization for Java applications. It describes how Spring Security can be used to secure web applications and REST APIs. It also discusses different approaches for authentication including using in-memory users, JDBC, and LDAP. The document contains code examples of configuring Spring Security.

Uploaded by

Java Pro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Spring Security [JAAS]

What is Software Security?


- Software system manage large amount of data. Any information of user considers
as private and sensitive for any Software applications. So sensitive data can
harmless information like phone number, email address, identification number.
Think more about data that is risker to lose like user credit card details.

- The application should ensure that there is no chance to be accessed, changed of


intercepted user data or information by outside person or any un-authenticated
and un-authorized person. This is the meaning of security

==============
Spring Security
==============
- Spring Security is a framework that belongs to application-level security and
provides multiple readymade filters to enable security filter.

Spring security mainly focus on 2 thinks

Authentication
- It is first level to checking whether the person is right or not to access our
application on the basis of username and password.
- Authentication = Identification[username] + verification[password]
- Verifying the user credential like user Login details.
Authorization
- It is second level to checking the permission, when an authenticated users try to
access a particular service of our application.
- Validating User Role, can this user access specified functionality/service
- Role is nothing but designations given to the users
===================
Authorization Levels
==================

1. permitAll: A URL/Path can be accessed by every one for this no login/ no role is
required.
Example: /home, /login, /contactUs, /aboutUs

2. Authenticated: A URL/Path can be accessed only after login.


Example: Show Logout Link, First Login, /chagePwd, /logout …etc.

Reference: https://www.baeldung.com/security-spring
https://reflectoring.io/spring-security/
Spring Security [JAAS]
3. hasAuthority: Login must and valid Role is required (after login which service
he/she can access).
Example: /approveLoan => Login and Role: Manager
4. hasAnyAuthority: Login must and valid Roles is required (one end point/services
can access either customer or admin)

Example: /checkBal => Login and Role: Customer, Manager

==========================================
How to secure/authorization specific URL Patterns
==========================================

1. Accessed by every one: requestMatchers("/welcome").permitAll()


2. Access URL only after Login: /profile
 .requestMatchers("/profile").authenticated()
3. Access URL after login having role ADMIN: /orderConform
 .requestMatchers("/orderConform ").hasAuthority("ADMIN")

4. Access URL after login having role MANAGER or CUSTOMER: /order


 .requestMatchers("/order").hasAnyAuthority("MANAGER", "CUSTOMER")

5. To indicates remaining URLs (which are not configured like above)


 .anyRequest().permitAll()
(or)
 .anyRequest().authenticated()
(or)
 anyRequest().hasAuthority("ADMIN")

***requestMatchers(“/classLevelPath**”): Used for Multi-level path matching.

1. @Controller
2. @RequestMapping("/bank")
3. public class BankOperationController {
4.
5. @GetMapping("/")
6. public String showHome() {…}
7.
8. @GetMapping("/offers")
9. public String showOffers() {…}
10.
11. @GetMapping("/approveLoan")
12. public String loans() {…}
13. }

Reference: https://www.baeldung.com/security-spring
https://reflectoring.io/spring-security/
Spring Security [JAAS]
requestMatchers(“/bank**”).hasRole(“MANAGER”)  means MANGER can access “/”,
“/offers”, “/approveLoan” any services.
requestMatchers(“/emp*”).hasAuthority(“ADMIN”)  means any service can access
those endpoints are started with /emp

Example: /empSave, /empDetails, /empDelete ...etc.

In Spring or spring boot environment, we can apply security on MVC apps or ReST
application 3 approaches -

1. Using Spring/Spring Boot Security


I. Basic Authentication (spring security generate password and user on
console)
II. Based on custom Authentication Provider that define, where are store
User name and password.
a. Using properties file as authentication info provider
b. Using InMemory DB as authentication info provider RAM Level
c. Using DB software as authentication info provider (with Spring
JDBC, Spring Data JPA etc.
d. Using LDAP server as authentication info provider.

2. Using JWT (JSON Web Token)


3. Using Spring OAuth 2.x

Using Spring/ Spring Boot Security

----------------------------------------
Using Default Authentication
---------------------------------------
To secure our spring boot application we need to add below starter in pom.xml file
1. <dependency>
2. <groupId>org.springframework.boot</groupId>
3. <artifactId>spring-boot-starter-security</artifactId>
4. </dependency>

Note: When we add this dependency in pom.xml file then by default our application will
be secured with basic authentication and authorization for all the HTTP methods of our

Reference: https://www.baeldung.com/security-spring
https://reflectoring.io/spring-security/
Spring Security [JAAS]
application. It will generate random password to access our application that will be print
on console.
When we access our application URL in browser then it will display "Login Form" to
authenticate our request. So, we need to use below credentials to access our
application.
Username: user
Password: on console
----------------------------------------------------------------------
Using properties file as authentication info provider
----------------------------------------------------------------------
To set our own credential we need to configure spring security credential in
application.properties file .
 Spring.security.user.name = <SetUserName>
 Spring.security.user.password = <SetPassword>

Q) How to access Secure API using postman?


- In postman, we have to provide spring security credential in the request
header section click on Authorization > inherit auth from > Basic auth and
provide username and password.
Note: For basic Spring security on Producer ReST API and if we want to access
from consumer app then we need to set header as
 Key: Authorization and Value: username and password

----------------------------------------------------------------------
Using InMemory DB as authentication info provider
----------------------------------------------------------------------
- Storing user credential details in temporary memory (RAM level), no database is
used. This is only for testing purpose.

Reference: https://www.baeldung.com/security-spring
https://reflectoring.io/spring-security/
Spring Security [JAAS]

==========================
Application with InMemory
=========================
1. Application Name: 01.SpringSecurity-InMemoryAuth
2. Dependencies:
 Spring Web,
 Spring Security
 Thymeleaf
3. Define Controller class: HomeController
4. In src/main/resources/templates create html pages
5. Define Java Based configuration Class with name SecurityConfiguration with
 @Configuration
 @EnableWebSecurity
And define two methods one is for Authentication and other is for Authorization

=========== HomeController Class ================


1. @Controller
2. public class HomeController {
3.
4. @GetMapping({"/","/home"})
5. public String showHome() {
6. return "home";
7. }
9. @GetMapping("/hello")
10. public String shoeHello() {
11. return "hello";
12. }
14. @GetMapping("/loginPage")
15. public String showLogin() {
16. return "login";
17. }
18. }

================== SecurityConfiguration =================


1. @Configuration
2. @EnableWebSecurity
3. public class MyAppSecurityConfiguration {
4.
5. @Bean
6. public UserDetailsService detailsService() {
7. UserDetails nadim =User.builder()
8. .username("nadim")
9. .password("{noop}123")
10. .build();
11.
12. return new InMemoryUserDetailsManager(nadim);
13. }

Reference: https://www.baeldung.com/security-spring
https://reflectoring.io/spring-security/
Spring Security [JAAS]
14. }

Note: When using the default UserDetailsService, a PasswordEncoder is also auto-


configured. Because we override UserDetailsService, we also have to declare a
PasswordEncoder. If do not declare PasswordEncoder then, we will get exception. To
solve this problem, we can add a PasswordEncoder bean in the context. Or if we do not
use PasswordEncoder for encoding then define {noop} with password like above
example.

===================
Data Confidentiality
==================
- Data will be transferred on the network but it must be transferred by encrypting
data.
- So, we do not store plain text as password. Store Password as encoded.

PasswordEncoder:
- If we want to encode user password before store into DB then we can use
PasswordEncoder that is provided by Spring security.

Example:

===========================================
Spring Security Application with JDBCAuthentication
===========================================
Step #01: Create two tables one is for user and other is for authorities by using below
queries –
CREATE TABLE USERS (
USERNAME NVARCHAR2(128) PRIMARY KEY,
PASSWORD NVARCHAR2(128) NOT NULL,
ENABLED CHAR(1) CHECK (ENABLED IN ('Y','N') ) NOT NULL
);
CREATE TABLE AUTHORITIES (
USERNAME NVARCHAR2(128) NOT NULL,
AUTHORITY NVARCHAR2(128) NOT NULL
);

ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_UNIQUE UNIQUE (USERNAME, AUTHORITY);


ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME)
REFERENCES USERS (USERNAME) ENABLE;

And Insert value into tables


insert into users values ('admin','$2a$12$tw1vxO2Phtba2gjkMU44euk9rsG6fg3/O5sZfHwBZqDTG9..Vkjry', ‘Y’);

Reference: https://www.baeldung.com/security-spring
https://reflectoring.io/spring-security/
Spring Security [JAAS]
insert into users values ('user', '$2a$12$cDgq/OPn7tyRYQWwft5ptu/8Lh55TQYC/CyYYQCqK4YdQz.wkg5cK', ‘Y’);

insert into authorities values ('admin', 'ROLE_ADMIN');


insert into authorities values ('admin', 'ROLE_USER');
insert into authorities values ('user', 'ROLE_USER');

Step #2: Create Application


1. Application Name: 01.SpringSecurity-JDBCAuthManualQuery
2. Dependencies:
 Spring Web
 Oracle Driver
 JDBC API
 Spring Security
 Thymeleaf
 Dev tools
3. Define Controller class: HomeController
4. In src/main/resources/templates create html pages
5. Define Java Based configuration Class with name SecurityConfiguration with
 @Configuration
 @EnableWebSecurity

And define two methods one is for Authentication and other is for Authorization

OAuth 2.x

Reference: https://www.baeldung.com/security-spring
https://reflectoring.io/spring-security/

You might also like