怎么使用spring security来获取用户的信息,账号

当用户登录完成之后,发起请求

package com.lzy.controller;

import cn.hutool.json.JSONObject;
import com.lzy.common.dto.SysMenuDto;
import com.lzy.common.lang.Result;
import com.lzy.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.List;

@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {
    @GetMapping("/nav")
    public Result nav(Principal principal) {
        try {
            if (principal == null) {
                return Result.fail("Unauthorized");
            }

            String username = principal.getName();
            SysUser byUsername = sysUserService.getByUsername(username);

            if (byUsername == null) {
                return Result.fail("User not found");
            }

            String userAuthorityInfo = sysUserService.getUserAuthorityInfo(byUsername.getId());
            String[] authorityArray = userAuthorityInfo != null ? StringUtils.tokenizeToStringArray(userAuthorityInfo, ",") : new String[]{};

            List navs = sysMenuService.getNav();

            JSONObject jsonObject = new JSONObject();
            jsonObject.set("authority", authorityArray);
            jsonObject.set("nav", navs);

            return Result.success(jsonObject);
        } catch (Exception e) {
            // Log the exception (consider using a logging framework like SLF4J)
            e.printStackTrace();
            return Result.fail("An error occurred");
        }
    }
}

可以使用Principal来获取username

    public Result nav(Principal principal) {
        try {
            if (principal == null) {
                return Result.fail("Unauthorized");
            }

            String username = principal.getName();

你可能感兴趣的:(从0开始做一个前后端分离项目,spring,security,java,spring,java,后端,spring,security)