use*_*702 5 java spring spring-security
我正在尝试从Spring Boot + AngularJS应用程序返回当前登录的用户,但SecurityContextHolder.getContext().getAuthentication()返回null.
安全配置:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
控制器:
@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;
}
Run Code Online (Sandbox Code Playgroud)
假设您显示的控制器映射到上下文/api/user,那么原因是您已将该行添加web.ignoring().antMatchers("/api/user");到安全配置中,这意味着对该控制器的所有请求都不受保护,因此也没有SecurityContext.删除该行,以便Spring Security保护它.
摘录自忽略方法的Javadoc:
Spring Security提供的Web Security(包括SecurityContext)将无法在匹配的HttpServletRequest上使用.
| 归档时间: |
|
| 查看次数: |
9376 次 |
| 最近记录: |