java 获取当前用户_Spring boot:获取当前用户的用户名

我试图使用Spring的安全性获取当前登录的用户名,但 Principal 对象返回null .

这是我的REST控制器方法:

@RequestMapping("/getCurrentUser")

public User getCurrentUser(Principal principal) {

String username = principal.getName();

User user = new User();

if (null != username) {

user = userService.findByUsername(username);

}

return user;

}

NB: I am running Spring boot 1.5.13 and spring security 4.2.6

这是我的安全配置类:

@组态

@EnableWebSecurity

公共类SecurityConfig扩展WebSecurityConfigurerAdapter {

@Autowired

private Environment env;

@Autowired

private UserSecurityService userSecurityService;

private BCryptPasswordEncoder passwordEncoder() {

return SecurityUtility.passwordEncoder();

}

private static final String[] PUBLIC_MATCHERS = {

"/css/**",

"/js/**",

"/image/**",

"/book/**",

"/user/**"

};

@Override

protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable().cors().disable().httpBasic().and().authorizeRequests()

.antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated();

}

@Autowired

public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());

}

@Bean

public HttpSessionStrategy httpSessionStrategy() {

return new HeaderHttpSessionStrategy();

}

这是我的用户安全服务类:

@服务

公共类UserSecurityService实现UserDetailsService {

private static final Logger LOG = LoggerFactory.getLogger(UserSecurityService.class);

@Autowired

private UserRepository userRepository;

@Override

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

User user = userRepository.findByUsername(username);

if(null == user) {

LOG.warn("Username {} not found", username);

throw new UsernameNotFoundException("Username "+username+" not found");

}

return user;

}

}

这是我的用户类:

@实体

public class User实现UserDetails,Serializable {

private static final long serialVersionUID = 902783495L;

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

@Column(name="Id", nullable=false, updatable = false)

private Long id;

private String username;

private String password;

private String firstName;

private String lastName;

private String email;

private String phone;

private boolean enabled = true;

@OneToMany(mappedBy = "user", cascade=CascadeType.ALL, fetch = FetchType.EAGER)

@JsonIgnore

private Set userRoles = new HashSet<>();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 很好,这个问题属于技术问题,可以回答。您可以通过注入SecurityContextHolder来获取当前用户的信息。比如在Controller中,可以这样获取: ``` Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Object principal = authentication.getPrincipal(); ``` 这里的principal就是当前登录用户的信息。 ### 回答2: 要获取当前登录用户的属性,可以采用以下步骤: 1. 添加Spring Security依赖。在pom.xml文件中,添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 在Spring Boot的配置类上添加@EnableWebSecurity注解来启用Spring Security功能: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 根据需要进行配置 } ``` 3. 定义获取当前登录用户属性的方法。在自定义的服务类或控制器中,可以通过SecurityContextHolder来获取当前登录用户的信息: ```java import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; public class UserService { public String getCurrentUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Object principal = authentication.getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } else { return principal.toString(); } } return null; } } ``` 在上述代码中,我们可以通过SecurityContextHolder获取当前的Authentication对象,然后再从Authentication对象中获取用户的详细信息。如果用户是通过用户名和密码进行认证的,则可以通过UserDetails来获取用户名。如果用户是通过第三方认证(如OAuth2或LDAP)进行认证的,则可以通过getPrincipal()方法直接获取用户的属性。 这样,我们就可以在Spring Boot获取当前登录用户的属性了。 ### 回答3: 要获取当前登录用户的属性,可以使用Spring Security和Spring Boot结合来实现。 首先,我们需要引入相关的依赖。在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 然后,在Spring Boot的配置类上添加@EnableWebSecurity注解,启用Web安全性配置。创建一个实现了UserDetailsService接口的自定义用户服务类,并将其注入到WebSecurityConfigurerAdapter中,如下所示: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated().and().formLogin(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 在自定义用户服务类中,实现loadUserByUsername方法以根据用户名加载用户信息。在该方法中,可以使用UserDetails对象的getUsername和getAuthorities等方法获取用户属性,如下所示: ```java @Service public class CustomUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 根据用户名从数据库或其他地方获取用户信息,并创建UserDetails对象 User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found"); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getAuthorities()); } } ``` 在控制器中,可以使用SecurityContextHolder获取当前已认证用户的信息。可以调用Authentication对象的getPrincipal和getAuthorities等方法获取用户属性,如下所示: ```java @RestController public class UserController { @GetMapping("/user") public String getUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); // 根据需要处理用户属性 ... return "Username: " + username; } } ``` 总结起来,通过引入Spring Security,并在配置类和用户服务类中配置相关的信息,然后在控制器中使用SecurityContextHolder获取当前登录用户的属性,就可以实现Spring Boot获取当前登录用户的属性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值