Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand SpringSecurity principle Authentication

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to understand SpringSecurity principle authentication", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to understand the authentication of SpringSecurity principles"!

The project structure remains basically unchanged:

First, we need to implement UserDetailsService to get the user-related information wrapper class UserDetails.

Import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;@Servicepublic class MyUserDetailService implements UserDetailsService {@ Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {/ / SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority ("admin") / / you can access the database, cache, etc., to obtain user information, and then build it as User. User is the UserDetails implementation class return User.builder () .username ("bob") / / username / / password 111111 ciphertext encrypted by BCryptPasswordEncoder .password ("$2a$10 $344aKAgXr17q7u.8l5i7Cu8wUJr/cxBIniLsVtf/WwFrPx0khY62K") .authorities ( "admin") / / permission information .build () }}

UserDetailsService only does one thing, which is to get the UserDetails, mainly the user name, password, and permissions. You can use the implementation class User provided by Spring Security, or you can implement UserDetails on your own and encapsulate it according to your own needs.

With the method of how to get the UserDetails, we also have to tell the Spring Security through the AuthenticationManagerBuilder configured by the SecurityConfig.

Import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import vip.oschool.uinion.security.MyUserDetailService;import javax.annotation.Resource @ Configuration@EnableWebSecurity@EnableGlobalMethodSecurity (prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter {@ Resource MyUserDetailService myUserDetailService; @ Bean BCryptPasswordEncoder bCryptPasswordEncoder () {return new BCryptPasswordEncoder ();} @ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService (myUserDetailService);}}

Note that we also added a BCryptPasswordEncoder, which is a password encryptor, because the database usually stores ciphertext of passwords, so we have to tell Spring Security what the password of our database is encrypted, so that Spring Security can encrypt the passwords received from the client in the same way, and then do authentication.

Of course, you can also set the password cipher in the following ways:

@ Overrideprotected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService (myUserDetailService) .passwordEncoder (new BCryptPasswordEncoder ());}

Let's comment out the user name and password in the configuration file, restart, and then authenticate with the user bob and password 111111 we set in the UserDetailsService implementation.

Server: port: 8081#spring:# security:# user:# name: tim# password: 111111Principal

A more abstract concept for a class that uniquely identifies an entity.

For example, for the user: the user id, mobile phone number, mailbox can be used as the user's principal to identify the user.

Credentials

To make it easier to understand, it can be regarded as a password.

GrantedAuthority

The first thing to know is: roles and permissions, which will be described in detail later.

UserDetails

The interface of the user entity, through which you can obtain:

GetPassword: get password

GetUserName: get user name

IsEnabled: whether the account is available

IsAccountNonExpired: whether the account expires

IsAccountNonLocked: whether the account is locked

IsCredentialsNonExpired: whether the password expires

GetAuthorites: obtaining user rights, which is essentially the role information of the user.

In Spring Security: org.springframework.security.core.userdetails.UserDetails

Spring Security provides a default implementation class: org.springframework.security.core.userdetails.User

UserDetailsService

This interface has only one purpose, which is to get the UserDetails. For example, if we need to get the user from the database, we need to implement this interface and inject the implementation class into the Spring container.

Only need to obtain the UserDetails, the authentication work Spring Security itself is verified by the user name and password, which may also involve the process of password processing.

Authentication

Used to store user authentication details: principal, permission GrantedAuthority, etc.

A custom Authentication can implement the Authentication interface or directly inherit AbstractAuthenticationToken.

Import org.springframework.security.authentication.AbstractAuthenticationToken;import org.springframework.security.core.GrantedAuthority;import java.util.Collection;public class JwtAuthenticationToken extends AbstractAuthenticationToken {public JwtAuthenticationToken (Collection authentication) {return authentication.isAssignableFrom (JwtAuthenticationToken.class);}}

We can then inject our custom AuthenticationProvider in the following way.

@ EnableWebSecurity () public class SecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.authenticationProvider (daoAuthenticationProvider ()) .authenticationProvider (jwtAuthenticationProvider ());}}

Previously, the reason why the UserDetailService we used works is due to the following configuration:

@ Overrideprotected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService (userDetailService);}

The userDetailsService of the authentication manager builder AuthenticationManagerBuilder creates a DaoAuthenticationProvider,DaoAuthenticationProvider that uses DelegatingPasswordEncoder as an agent, and BCryptPasswordEncoder is used by default.

AuthenticationManager and ProviderManager

AuthenticationManager, as its name implies, is used to manage Authentication, but actually to manage AuthenticationProvider.

ProviderManager is the implementation class of AuthenticationManager, which holds an AuthenticationProvider list that is used to complete different authentications.

It also holds a reference to AuthenticationManager as its parent class.

Generally speaking, it is enough for us to use ProviderManager, and generally all we need is an AuthenticationProvider.

If you want to configure more than one, you can override authenticationManager in SecurityConfig (which inherits WebSecurityConfigurerAdapter).

@ Overrideprotected AuthenticationManager authenticationManager () {/ / ProviderManager can set multiple AuthenticationProvider ProviderManager authenticationManager = new ProviderManager (Arrays.asList ()); return authenticationManager;} PasswordEncoder

To put it simply, it is not a good habit to encrypt the password and store the plaintext of the user's password, which is irresponsible to the user and the risk of the project.

Therefore, we usually encrypt the user's password and then store it, usually adding salt and then using algorithms such as sha256 and md5.

Using Spring Security requires us to implement these processes ourselves, and we can configure PasswordEncoder directly.

Spring Security provides the following implementation classes for PasswordEncoder.

DelegatingPasswordEncoder

That is, entrusted password encoder, compatible with a variety of different encryption methods to store passwords. It is mainly used for the compatibility of encryption methods between new and old data to achieve smooth migration, such as NoOpPasswordEncoder for old data and BCryptPasswordEncoder encryption for new data.

BCryptPasswordEncoder

In order to make the encoder based on bcrypt algorithm more resistant to password cracking, bcrypt deliberately slows down the speed, and like other adaptive one-way functions, it should be adjusted to about 1 second to verify the password on the system. The default implementation of BCryptPasswordEncoder uses a strength of 10.

Argon2PasswordEncoder

The encoder based on Argon2 algorithm, Argon2 is a deliberately slow algorithm, which requires a lot of memory. As with other adaptive one-way features, it should be adjusted to approximately 1 second to verify passwords on the system. The current implementation of Argon2PasswordEncoder requires BouncyCastle.

Pbkdf2PasswordEncoder

For the encoder based on PBKDF2 algorithm, PBKDF2 is a deliberately slow algorithm in order to overcome the problem of password cracking. As with other adaptive one-way features, it should be adjusted to approximately 1 second to verify passwords on the system. This algorithm is a good choice when FIPS authentication is required.

SCryptPasswordEncoder

The encoder based on the scrypt algorithm, in order to overcome the password cracking problem on the custom hardware scrypt, this is a deliberately slow algorithm, which requires a lot of memory. As with other adaptive one-way features, it should be adjusted to approximately 1 second to verify passwords on the system.

Add test user

When we test, we want to add test users, but do not want to go to too much trouble to implement UserDetailsService, we can also use the following ways:

@ Configuration@EnableWebSecurity@EnableGlobalMethodSecurity (prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication () .withUser ("tim") .password ("111111") .roles ("admin") .and () .withUser ("allen") .password ("222222") .password ("user") }}

Entering the inMemoryAuthentication method, we can see that the above method is equivalent to:

@ Beanpublic UserDetailsService userDetailsService () {InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager (); manager.createUser (User.withUsername ("tim"). Password ("111111"). Roles ("admin"). Build (); manager.createUser (User.withUsername ("allen"). Password ("222222"). Roles ("user"). Build (); return manager;}

So, in essence, it is equivalent to creating a UserDetailsService, except that the data is kept in memory.

At this point, I believe you have a deeper understanding of "how to understand the authentication of SpringSecurity principles". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report