Vue Cli3+SpringBoot

Follow today The blogger Learn the back-end registration encryption and login decryption functions.

1. To be honest, I didn't understand the application of Shiro framework in springboot. So I put the code to record what I did:

First, the realm class of the realm package:

package realm;

import com.example.demo.User.User;
import com.example.demo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

public class Realm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    // Simple rewriting method for obtaining authorization information
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection){
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        return s;
    }

    // Obtain the authentication information, that is, obtain the password, salt, etc. from the database according to the user name in the token and return
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException{
        String userName = token.getPrincipal().toString();
        User user = userService.getByName(userName);
        if(ObjectUtils.isEmpty(user)){
            throw new UnknownAccountException();
        }
        String passwordInDB = user.getPassword();
        String salt = user.getSalt();
        SimpleAuthenticationInfo authenticationInfo  = new SimpleAuthenticationInfo(userName,passwordInDB, ByteSource.Util.bytes(salt),getName());
        return authenticationInfo ;
    }
}

Next, the User class adds new properties:

Then there are three classes of the result package:

package com.example.demo.result;

public class Result {
    private int code;
    private String message;
    private Object data;

    Result(int code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

package com.example.demo.result;


public enum ResultCode {
    SUCCESS(200),
    FAIL(400),
    UNAUTHORIZED(401),
    NOT_FOUND(404),
    INTERNAL_SERVER_ERROR(500);

    public int code;

    ResultCode(int code) {
        this.code = code;
    }
}

package com.example.demo.result;


public class ResultFactory {

    public static Result buildSuccessResult(Object data) {
        return buildResult(ResultCode.SUCCESS, "Success", data);
    }

    public static Result buildFailResult(String message) {
        return buildResult(ResultCode.FAIL, message, null);
    }

    public static Result buildResult(ResultCode resultCode, String message, Object data) {
        return buildResult(resultCode.code, message, data);
    }

    public static Result buildResult(int resultCode, String message, Object data) {
        return new Result(resultCode, message, data);
    }
}

LoginController class to update:

package com.example.demo.controller;

import com.example.demo.User.User;
import com.example.demo.result.Result;
import com.example.demo.result.ResultFactory;
import com.example.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

@Controller
public class LoginController{
    @Autowired
    UserService userService;

//    @CrossOrigin
////    @PostMapping(value = "/login")
//    @RequestMapping(value = "/login",method = RequestMethod.POST)
//    @ResponseBody
//    public Result login(@RequestBody User requertUser){
//        String username = requertUser.getUsername();
//        username = HtmlUtils.htmlEscape(username);
//
//        User user = userService.get(username,requertUser.getPassword());
//        if (null==user){
//            return new Result(400);
//        }else {
//            return new Result(200);
//        }
//    }

    @CrossOrigin
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody User requestUser){
        String username = requestUser.getUsername();
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,requestUser.getPassword());
        try {
            subject.login(usernamePasswordToken);
            return ResultFactory.buildSuccessResult(usernamePasswordToken);
        }catch (AuthenticationException e){
            String message = "Account password error";
            return ResultFactory.buildFailResult(message);
        }
    }
    @CrossOrigin
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        username = HtmlUtils.htmlEscape(username);
        user.setUsername(username);

        boolean exist = userService.isExist(username);
        if (exist) {
            String message = "User name is already in use";
            return ResultFactory.buildFailResult(message);
        }

        // Generate salt, default length 16 bits
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        // Set iteration times of hash algorithm
        int times = 2;
        // Get the password after hash
        String encodedPassword = new SimpleHash("md5", password, salt, times).toString();
        // Store user information, including passwords after salt and hash
        user.setSalt(salt);
        user.setPassword(encodedPassword);
        userService.add(user);

        return ResultFactory.buildSuccessResult(user);
        }

}

A configuration class:

package com.example.demo.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import realm.Realm;


@Configuration
public class ShiroConfiguration {
    @Bean
    public static LifecycleBeanPostProcessor getLifecycleBeanProcessor(){
        return new LifecycleBeanPostProcessor();
    }
   @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager)
   {
       ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
       shiroFilterFactoryBean.setSecurityManager(securityManager);
       return shiroFilterFactoryBean;
   }
   @Bean
    public SecurityManager securityManager(){
       DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
       defaultWebSecurityManager.setRealm(getRealm());
       return defaultWebSecurityManager;
   }
   @Bean
    public Realm getRealm(){
        Realm realm = new Realm();
        realm.setCredentialsMatcher(hashedCredentialsMatcher());
        return realm;
   }
   @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName(("md5"));
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
   }
   @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}

Thank you so much for being here This blogger's tutorial!
If someone read this article, remember to read this blogger. Don't look at mine. I just use it for myself on his basis.

Published 13 original articles, won praise 3, visited 281
Private letter follow

Tags: Shiro Apache Spring SpringBoot

Posted on Mon, 03 Feb 2020 08:07:24 -0800 by Kunax