bug
zhangzeli
2022-01-25 e31d4d2d3cecab2fb56508c0f5b82d821719e7bb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package cn.exrick.xboot.core.config.jpa;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
 
import java.util.Optional;
 
/**
 * 审计记录创建或修改用户
 * @author Exrickx
 */
@Configuration
@Slf4j
public class UserAuditor implements AuditorAware<String> {
 
    @Override
    public Optional<String> getCurrentAuditor() {
 
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if(authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)){
                return Optional.ofNullable(authentication.getName());
            }
            return Optional.empty();
        } catch (Exception e) {
            return Optional.empty();
        }
    }
}