【发布时间】:2015-07-02 08:11:41
【问题描述】:
我有一个 Spring Boot 应用程序,其中大部分页面都使用以下安全配置进行保护(您需要登录才能访问它们)。
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
class SecurityConfiguration extends
WebSecurityConfigurerAdapter {
@Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("myapp")
.roles("ADMIN")
.and()
.withUser("guest")
.password("guest")
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/index.html", "/home.html", "/login.html", "/")
.permitAll()
.anyRequest().authenticated().and()
.csrf()
.csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
}
private CsrfTokenRepository csrfTokenRepository() {
final HttpSessionCsrfTokenRepository repository =
new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
}
在我的应用程序类中,我有一个服务publicData,我希望无需身份验证即可访问它(即使用户未登录)。
@SpringBootApplication
@RestController
public class MyAppApplication {
@RequestMapping("/resource")
public Map<String,Object> home() {
final Map<String,Object> model = new HashMap<>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
@RequestMapping("/publicData")
public String publicData() {
return ...;
}
@RequestMapping("/user")
public Principal user(final Principal user) {
return user;
}
public static void main(final String[] args) {
SpringApplication.run(MyAppApplication.class, args);
}
}
我该怎么做?
我试过了
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/index.html", "/home.html", "/login.html", "/")
.permitAll()
.anyRequest().authenticated().and()
.csrf()
.csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
.and()
.authorizeRequests()
.antMatchers("/publicData").permitAll();
}
但是没有用。
【问题讨论】:
-
顺序很重要。尝试在上面的
.authorizeRequests()之后链接它。理想情况下,您正在寻找类似的东西:github.com/jhipster/jhipster-sample-app/blob/master/src/main/… -
看看它是否有效,只需添加 /publicData 以及您的索引、主页等。
-
@Vaelyr 它没有。
SecurityContextHolder.getContext().getAuthentication().getPrincipal()现在即使在用户登录后也会返回null。
标签: java spring spring-security spring-boot