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<>();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值