Skip to content

Security 获取用户信息

java
package cloud.xuxiaowei.core.utils;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Security 工具类
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
public class SecurityUtils {

    /**
     * 获取用户名
     * @return 返回用户名。如果返回 null,代表未登录(匿名用户)
     */
    public static String getName() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            return null;
        }
        return authentication.getName();
    }

}
java
package cloud.xuxiaowei.passport.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户接口
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserRestController {

    /**
     * 获取用户名
     */
    @PostMapping("/name")
    public String info(Authentication authentication) {

        if (authentication instanceof AnonymousAuthenticationToken) {
            // 未登录(匿名用户)
            return null;
        }

        return authentication.getName();
    }

}