zoukankan      html  css  js  c++  java
  • Spring Security使用Authentication获取当前用户信息


    Spring Security使用一个Authentication对象来描述当前用户的相关信息。SecurityContextHolder中持有的是当前用户的SecurityContext,而SecurityContext持有的是代表当前用户相关信息的Authentication的引用。这个Authentication对象不需要我们自己去创建,在与系统交互的过程中,Spring Security会自动为我们创建相应的Authentication对象,然后赋值给当前的SecurityContext。但是往往我们需要在程序中获取当前用户的相关信息,比如最常见的是获取当前登录用户的用户名。在程序的任何地方,通过如下方式我们可以获取到当前用户的用户名。

      public String getCurrentUsername() {
    
          Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
          if (principal instanceof UserDetails) {
    
             return ((UserDetails) principal).getUsername();
    
          }
    
          if (principal instanceof Principal) {
    
             return ((Principal) principal).getName();
    
          }
    
          return String.valueOf(principal);
    
       }


    通过Authentication.getPrincipal()可以获取到代表当前用户的信息,这个对象通常是UserDetails的实例。获取当前用户的用户名是一种比较常见的需求,关于上述代码其实Spring Security在Authentication中的实现类中已经为我们做了相关实现,所以获取当前用户的用户名最简单的方式应当如下。

       public String getCurrentUsername() {
    
          return SecurityContextHolder.getContext().getAuthentication().getName();
    
       }


    此外,调用SecurityContextHolder.getContext()获取SecurityContext时,如果对应的SecurityContext不存在,则Spring Security将为我们建立一个空的SecurityContext并进行返回。

  • 相关阅读:
    SQL Server 全文搜索 配置、查询初体验
    SQL Server 触发器
    SQL Server 锁
    SQL Server 事务语法
    SQL Server 表变量和临时表的区别
    SQL Server系统存储过程
    SQL 语句转换格式函数Cast、Convert
    SQL Server 系统视图
    T-SQL 批处理
    SQL Server 分区表
  • 原文地址:https://www.cnblogs.com/liuys635/p/12577175.html
Copyright © 2011-2022 走看看