gpt4 book ai didi

java - Spring Security getAuthentication() 返回 null

转载 作者:行者123 更新时间:2023-12-04 18:03:51 25 4
gpt4 key购买 nike

我正在尝试从 Spring Boot + AngularJS 应用程序返回当前登录的用户,但是 SecurityContextHolder.getContext().getAuthentication()返回空值。

安全配置:

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("test").password("test").roles("USER", "ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin().and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).and()
.authorizeRequests()
.antMatchers("/index.html", "/login.html", "/").permitAll()
.anyRequest().authenticated().and()
.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
.csrf().csrfTokenRepository(csrfTokenRepository());
}

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/bower_components/**");
web.ignoring().antMatchers("/js/**");
web.ignoring().antMatchers("/css/**");
web.ignoring().antMatchers("/api/user");
}

private static CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
}

Controller :
@RequestMapping(value="/user", method = RequestMethod.GET)
@ResponseBody
public User user() {
User user = new User();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
String name = auth.getName();
user.setUsername(name);
}
return user;
}

最佳答案

假设您显示的 Controller 映射到上下文 /api/user ,那么原因是因为您添加了行 web.ignoring().antMatchers("/api/user");到您的安全配置,这意味着对该 Controller 的所有请求都不 protected ,因此也没有 SecurityContext。删除该行,以便 Spring Security 保护它。

忽略方法的 Javadoc 摘录:

Web Security provided by Spring Security (including the SecurityContext) will not be available on HttpServletRequest that match.

关于java - Spring Security getAuthentication() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36411947/

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