gpt4 book ai didi

java - Spring 启动 : Get current user's username

转载 作者:行者123 更新时间:2023-11-29 08:28:27 25 4
gpt4 key购买 nike

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

这是我的 REST Controller 方法:

@RequestMapping("/getCurrentUser")
public User getCurrentUser(Principal principal) {

String username = principal.getName();
User user = new User();
if (null != username) {
user = userService.findByUsername(username);
}

return user;
}

注意:我正在运行 Spring boot 1.5.13 和 spring security 4.2.6

  • 这是我的安全配置类:

    @Configuration

    @EnableWebSecurity

    public class SecurityConfig extends 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();
    }
    }
  • 这是我的用户安全服务类:

    @Service

    public class UserSecurityService implements 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;
    }
    }
  • 这是我的用户类:

    @Entity

    public class User implements 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<UserRole> userRoles = new HashSet<>();
    }

最佳答案

有多种方法可以做到这一点。

使用SecurityContextHolder

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();

从 Controller 使用Principal

@RequestMapping(value = "/myusername", method = RequestMethod.GET)
@ResponseBody
public String currentUserName(Principal principal) {
return principal.getName();
}

来自 HttpServletRequest

@RequestMapping(value = "/myusername", method = RequestMethod.GET)
@ResponseBody
public String getUsername(HttpServletRequest req) {
return req.getUserPrincipal.getName();
}

关于java - Spring 启动 : Get current user's username,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50355486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com