Feed Buzzard

Cooking content that keeps your audience buzzing

  • General
    • General News
  • Tech
  • World Tech
  • World Tech Code
  • Wearable Tech
  • Pokemon
  • Latest
  • About Us
    • Terms & Conditions
    • Privacy Policy
  • Contact
No Result
View All Result
  • General
    • General News
  • Tech
  • World Tech
  • World Tech Code
  • Wearable Tech
  • Pokemon
  • Latest
  • About Us
    • Terms & Conditions
    • Privacy Policy
  • Contact
No Result
View All Result
Feed Buzzard
No Result
View All Result
Home World Tech

Custom Password Encoder in Spring Security

Gordon James by Gordon James
June 4, 2021
in World Tech
0
0
SHARES
57
VIEWS
Share on FacebookShare on Twitter

Spring Security is a popular Java web application framework that protects web applications against authentication and authorization attacks. It works by performing claims based access control and by providing a view of the logged in user. In this post, we will explore how to implement a custom password encoder in Spring Security.

Many organizations today are still using the default password encoder that Spring Security uses by default. Request parameters are encoded as a base64 string. This is a very weak encoding when it come to password security.

The Spring Security framework is a very popular solution for securing your application in the Java EE 5 and 6 world. One issue with Spring Security is that it uses a proprietary cryptographic algorithm for encrypting passwords. Today, the default algorithm used in Spring Security framework is still the standard PBKDF2. The problem is that it is known to be vulnerable to rainbow table attacks.

In this tutorial, you will learn how to create a custom password encryptor in a Spring Boot application using Spring Security.

Table of Contents

Toggle
  • Table of contents
    • Connection characteristics
  • Add a user template
  • Create a custom archive
  • Implementing a user password recorder
  • Create a service class that implements UserDetailService
    • Methods of recording and retrieval
  • Create a class that extends the WebSecurityConfigurerAdapter
  • Creating a user controller class
  • Application test
  • Supplement
      • Related Tags:

Table of contents

  1. Create a Spring Boot project and add the database connection properties.
  2. Add a user template.
  3. Make a user deposit.
  4. Implement a custom PasswordEncoder.
  5. Create a service class implementing UserDetailService
  6. Add a configuration class that extends the WebSecurityConfigurerAdapter.
  7. Create a user controller class.
  8. Job interview.

Creating a Spring Boot project and adding database connection properties Go to Spring Initializr and create a Spring Boot project with the Maven Spring Web, Spring Security, Spring Data JPA, and MySQL Driver dependencies.

Connection characteristics

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/user_database spring.datasource.username=username spring.datasource.password=password spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true

Add a user template

The User class creates an instance of user data. import javax.persistence.*; @Entity @Table(name = user) public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = id) private int id ; @Column(name = first name) private String first name ; @Column(name = lastName) private String lastName ; @Column(name = email) private String email ; @Column(name = username) private String username ; @Column(name = password) private String password ; //Generates getter, setter, construc and toString methods }

Create a custom archive

UserRepository class to store and retrieve a user object in the database. @Repository public interface UserRepository extends JpaRepository<User,Integer> { }

Implementing a user password recorder

Here is an example of a class that implements the PasswordEncoder interface. We will use this class to implement our own password encoder. PasswordEncoder is a Spring Security interface that we can use to give our class an implementation of our own password encoder. Implementation options for the password encoder include BcryptPasswordEncoder, NoOpPasswordEncoder, and StandardPasswordEncoder. Standard and custom implementations must override the encode and matches methods of the password encoder. The encryption method encrypts the raw password. As a general rule, a good encryption algorithm uses a SHA-1 hash or higher in combination with a randomly generated salt of 8 bytes or more. The match method checks that the encrypted password retrieved from the archive matches the raw password submitted after it was encrypted. Returns true if the password matches, false if it does not. The stored password itself is not decrypted. To use this password encoder, you create a custom password bean and integrate it into the user service, where the user’s password is encrypted before being stored in the database. public class CustomPasswordEncoder implements PasswordEncoder { @Override public String encode(CharSequence plainTextPassword) { return BCrypt.hashpw(plainTextPassword.toString(),BCrypt.gensalt(8)); } @Override public boolean matches(CharSequence plainTextPassword, String passwordInDatabase) { return BCrypt.checkpw(plainTextPassword.toString(),passwordInDatabase); } }

Create a service class that implements UserDetailService

UserDetailService provides a method to search for a user based on their name. The method finds the user during authentication, but since our interest lies in encrypting the password, we will return the user data and credentials as null.

Methods of recording and retrieval

The register method retrieves the user object from the controller, encrypts the password in unencrypted text, and then stores the user in the database. The find method returns a user object to the controller, which can then be accessed from the client using postman. @Service public class UserService implements UserDetailsService {. private UserRepository userRepository ; private CustomPasswordEncoder customPasswordEncoder ; @Autowired public UserService(UserRepository userRepository, @Lazy CustomPasswordEncoder customPasswordEncoder){ this.userRepository = userRepository; this.customPasswordEncoder = customPasswordEncoder ; } public void registerUser(user user) { user newUser = new User(); newUser.setId(user.getId()); newUser.setFirstName(user.getFirstName()); newUser.setLastName(user.getLastName()); newUser.setEmail(user.getEmail()); newUser.setUsername(user.getUsername()); newUser.setPassword(customPasswordEncoder.encode(user.getPassword()); userRepository.save(newUser) ; } public User findUserById(id) { return userRepository.findById(id) .orElseThrow() -> new NullPointerException(User not found)); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = new User(); return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),Collections.emptyList()) } }

Create a class that extends the WebSecurityConfigurerAdapter

WebSecurityConfigurerAdapter is a handy base class for creating an instance of WebSecurityConfigurerAdapter. The Dao authentication provider retrieves the user’s data from the user’s data service. The creator of the authentication manager adds authentication providers. HTTP Security allows you to configure web security for specific HTTP requests. By creating a password encoding bean, we can integrate it into the user service class to encrypt the user’s password. @Configuration @EnableWebSecurity public class CustomPasswordEncoderConfig extends WebSecurityConfigurerAdapter { private UserService userService ; @Autowired public CustomPasswordEncoderConfig(UserService userService){ this.userService = userService; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(daoAuthenticationProvider()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests() .antMatchers(/user/**) .permitAll(); } @Bean public DaoAuthenticationProvider daoAuthenticationProvider(){ DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setPasswordEncoder(customPasswordEncoder()); daoAuthenticationProvider.setUserDetailsService(userService); return daoAuthenticationProvider; } @Bean public CustomPasswordEncoder customPasswordEncoder(){ return new CustomPasswordEncoder(); } }

Creating a user controller class

/user/register – Create a new user object. /user/find/{id} – retrieves the user’s instance. @RestController @RequestMapping(/user) public class UserController {. private UserService userService ; @Autowired public UserController(UserService userService){ this.userService = userService; } @PostMapping(/register) public void registerUser(@RequestBody User user){ userService.registerUser(user); } @GetMapping(/find/{id}) public User findUserById(@PathVariable(id) int id){ return userService.findUserById(id); } }

Application test

Create a new user object with postman with the following reference. http://localhost:8080/user/register word-image-694 Retrieve the user object and notice that the password is now encrypted. http://localhost:8080/user/find/1 word-image-695

Supplement

Password encryption is a security measure that protects the integrity and confidentiality of data from intruders. The security should also protect against other types of vulnerabilities, such as cross-site scripting, SQL injection, denial-of-service and cross-site query spoofing. To secure our application, we need to enable the strong authentication and authorization mechanism and provide a password hash.For many, choosing good passwords is a struggle, and it can be especially difficult for those who use the same password to secure different services or who do not have a good password manager that they can rely on. The secure password encoder is an easy-to-use tool that allows users to encode their passwords into a secure string without having to type the actual password.. Read more about spring security password encryption example and let us know what you think.

Related Tags:

spring security password encoderspring security password encoder sha256bcryptpasswordencoderbcrypt password encoderspring security decrypt passwordspring security password encryption and decryption example,People also search for,Privacy settings,How Search works,spring security password encoder,spring security password encryption and decryption example,spring security password encoder sha256,spring security password encryption example,password encryption and decryption in spring mvc,bcryptpasswordencoder,bcrypt password encoder,spring security decrypt password

Total
0
Shares
Share 0
Tweet 0
Pin it 0
Share 0
Gordon James

Gordon James

James Gordon is a content manager for the website Feedbuzzard. He loves spending time in nature, and his favorite pastime is watching dogs play. He also enjoys watching sunsets, as the colors are always so soothing to him. James loves learning about new technology, and he is excited to be working on a website that covers this topic.

Related Posts

World Tech

No Phone, No Problem: Receiving SMS Online Made Easy

March 24, 2025
Image2
World Tech

The Smart Shopper’s Guide to Finding Reliable Tech at the Price

February 24, 2025
Image1
World Tech

The Unique Appeal of Clash GG Case Battles

February 19, 2025
Next Post

Lenovo Flex 5 touch screen driver not working

How to install printer driver without admin rights

Download, Install & Use Deer Animal Hunting 2021: African Safari Animals on PC (Windows & Mac)

No Result
View All Result

Recommended

Image2

Build Smarter, Ship Faster: Why Agile Teams are Adopting Model Context Protocol

13 hours ago

Smart Transit: The Rise of GPS, Scheduling Apps, and Digital Tools in Bus Fleets

1 day ago
Image3

Why Social Betting is Changing Online Gambling’s Future

2 days ago
Image1

What $10 Purchase You in The Digital World: A 2025 Micro-Spending Roundup

3 days ago

Categories

  • Businesses
  • Fitness Trackers
  • Gaming
  • General
  • General News
  • Latest
  • Latest Trends
  • Online Gaming
  • Pokemon
  • Tech
  • Technology and Computing
  • Wearable Tech
  • World Tech
  • World Tech Code

Our Address: 222 Haloria Crossing
Vrentis Point, HV 12345

Categories

  • Businesses
  • Fitness Trackers
  • Gaming
  • General
  • General News
  • Latest
  • Latest Trends
  • Online Gaming
  • Pokemon
  • Tech
  • Technology and Computing
  • Wearable Tech
  • World Tech
  • World Tech Code
No Result
View All Result
  • Image2
  • Image1
  • Image2
  • RyanMotorsOmaha
  • Tech News FeedCryptobuzz
  • Ujjukt [Hjv
  • www Feedbuzzard .com
  • Image3
  • Image3
  • Image1
  • Image3
  • Image2
  • Image2
  • Image3
  • Image1
  • Image2
  • Image2
  • pandagendut slot
  • faktor-faktor yang mendorong didirikannya voc adalah
  • sayur yang bisa ngeramal
  • buku mimpi 2d 3d 4d abjad
  • gerakan awal guling lenting yang benar diawali dengan gerak
  • ibanking bank jateng personal
  • canadadry.ca enter pin 2022
  • chord gitar wali kerudung merah
  • Reparasi Tas Terdekat
  • buku mimpi 2d 3d 4d abjad
  • no hp janda yang bisa dihubungi
  • pola138
  • photoacampamente
  • bo togel hadiah 2d 200rb
  • www feedbuzzard .com
  • feedcryptobuzz cryptocurrency updates from feedbuzzard
  • feedbuzzard com
  • Ca Khia
  • 5 letter words starting with ca
  • Mobile. de
  • Mendarat Yang Baik Dalam Lompat Jauh Dilakukan Dengan.....
  • jual ayam potong terdekat
  • how to play crypto games in 2023 feedgamebuzz
  • latest gadjets for gaming zardgadjets
  • latest hacks buzzardcoding
  • what are new technologies in 2023 feedworldtech
  • Image1
  • remaxhd.com
  • tv.hotstar.com
  • rajbet.com
  • venus.happyreturns.com
  • Image2
  • ibooma.com
  • fapwife.com
  • Image1
  • Image1
  • Image3
  • Image2
  • the budget process involves doing all of the following except
  • rice purity test for 14 year olds
  • during operations outside declared hostilities, you may delay contact with local authorities.
  • active shooter is one or more subjects who participate in a shooting
  • rick and morty season 6 online
  • which of the following is most likely to be considered plagiarism
  • which of the following could be a replacement behavior for cutting in line
  • effective scrum master apply which coaching behavior
  • a decrease in blood protein concentration would tend to
  • hair removal cream for private parts male
  • what escape planning factors can facilitate
  • the adversary is collecting information regarding your organization's mission from the trash
  • identify two meanings for the japanese word inu
  • an immediate annuity has been purchased with a single premium
  • justify the following statement: “diversity should exist in the workplace.”
  • fc barcelona vs viktoria plzeň lineups
  • which of the following is tax-deductible to the firm?
  • latest feedbuzzard com
  • treasure of wisdom a new plan
  • which data types are typically found in the human resources department?
  • what supports the arms and hands medical term
  • which of the following is true about nonforfeiture values?
  • match each type of anxiety disorder with its description.
  • daniel is a middle-income medicare beneficiary
  • what does wtm mean on snapchat
  • which facility is shown in the image
  • how can you report potential insider threats to the js in to select all that apply
  • what does wtv mean in text
  • jane assessment answers
  • employee records must meet all of the following criteria except
  • a major challenge of nationalism is .
  • a covered entity (ce) must have an established complaint process. true false
  • fema is 100 hcb answers
  • identify the true and false statements about culture.
  • in which word does the grapheme representing /k/ indicate that the word is probably from greek?
  • mr. wingate is a newly enrolled
  • gear patrol the spirit of adventure
  • ms insurance company denied a reinstatement
  • which option below is a preventive measure against id fraud or theft?
  • preferred stock is advantageous in that it ______. (check all that apply.)
  • which sentence from the novel best reflects the story's gothic nature
  • m and t bank near me

© 2022 FeedBuzzard.com

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
No Result
View All Result
  • General
    • General News
  • Tech
  • World Tech
  • World Tech Code
  • Wearable Tech
  • Pokemon
  • Latest
  • About Us
    • Terms & Conditions
    • Privacy Policy
  • Contact

© 2024 JNews - Premium WordPress news & magazine theme by Jegtheme.