preface

In everyday projects, Spring Security’s default authentication process does not meet the requirements.

However, the requirements for authentication and authentication are very similar in general projects.

So I wrapped Spring Security around the authentication and authentication requirements of everyday projects.

The project address, and the test project address, are placed at the end of the text.

Project description

This project is completely based on Spring Security, only for daily development projects in the authentication, dynamic permission requirements to do a layer of encapsulation.

Clean and pure, no other messy function.

Can be used for project rapid development, Spring Security framework learning.

In addition, considering that JWT is used most at present, the built-in encapsulation logic is that token is generated and returned after successful authentication.

The token contains the userId and roleIds. Example of Token content:

{roles: "10,1,5", exp: 1626480624, userId: "1"}. [signature]Copy the code

Results show

  1. Normal login

  2. Missing parameter login

  3. Normal access

  4. No access

  5. No login access

  6. Token error access

package

├─authentication Related Processing ├─authorization Related Processing ├─ Config Security Configuration ├─constant constant ├─filter Filter (login gateway, JWT processing gateway) ├─handle ├─ LoginLogic │ ├─ Base ├─ Model ├─ utilsCopy the code

The overall process

The login request

Business requests

Quick to use

  1. Introduction of depend on

This package is not released to the central repository, please install it to your local repository.

< the dependency > < groupId > pri. Damai < / groupId > < artifactId > fast ws-security < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > </dependency>Copy the code
  1. Provides a user query interface.

    That is, the database of connected users.

@Component public class UserServiceImpl{ static List<FastUserInfo> userList = new ArrayList<>(); / /... public FastUserInfo loadUserByPhone(String phone) { return userList.stream() .filter(user -> User. GetPhone (.) the equals (phone)) findAny () orElseThrow (() - > new AuthenticationServiceException (" the user ")); }}Copy the code
  1. Implementing logon logic

    There are several logins, and there are several implementation classes. Note that the return value of getSupportLoginType() should be distinguished.

@Component public class PhoneLogin extends AbstractLoginLogic { @Resource UserServiceImpl userService; @Override public String getSupportLoginType() { return "phone"; } @Override public void checkParam(LoginData loginData) throws AuthenticationException { String msg = null; If (logindata.getPhone () == null) {MSG = "phone number cannot be null "; } the if (loginData getPhoneVerifyCode () = = null) {MSG = MSG + ", message authentication code cannot be empty "; } if (! Objects.equals(msg, null)) { this.throwException(msg); } } @Override protected void login(LoginData loginData) throws AuthenticationException { if (!" 22 ". The equals (loginData getPhoneVerifyCode ())) {enclosing throwException (" verification code error "); FastUserInfo = this.getUserDetails(loginData); } @Override public FastUserInfo getUserDetails(LoginData loginData) { return userService.loadUserByPhone(loginData.getPhone()); } private void throwException(String msg) { throw new AuthenticationServiceException(msg); }}Copy the code
  1. Implements the ResourceService interface.

    This interface allows you to query permission. This is the access database. Caching or not caching is up to your implementation.

@Component public class MyResourceImpl implements ResourceService { static HashMap<String, List<String>> roleMap = new HashMap<>(); / /... @Override public List<String> getRolesByUrl(String url) { return roleMap.get(url); }}Copy the code

Other extensions

Yml configuration is optional

The following configurations have default values and can be configured only when required.

Expiration: /user login-url: # expiration: # expiration: # expiration: # expiration: # Specify Jwt key authentication-failed-code: # Specify login failure error code unauthorized-code: # Specify unauthenticated error code permission-denied-code: # Specifies an unauthorized error code no-roles-pass: # Specifies whether roles-pass is allowed when the Url is not configuredCopy the code

Successful login processor

In a real development, we might need to store tokens. Customize the function which can realize LoginSuccessResultHandler interface.

@Component public class GGLoginSuccessResultHandler implements LoginSuccessResultHandler { @Override public Object HandleResult (UserDetails UserDetails, String Token) {// Save token or other operation return null; }}Copy the code

Custom login failure handler

@Component public class GGLoginFailureResultHandler implements LoginFailureResultHandler { @Override public Object handleResult(AuthenticationException e) { return null; }}Copy the code

GIT address

Fast-Security

Fast-Security-Test

If it works for you, remember to click a little star ⭐⭐⭐.