I have a spring rest service, I want to use it for authenticated and not authenticated users. And I want to get user information from SecurityContextHolder.getContext(
permitAll()
still requires Authentication
object to present in SecurityContext
.
For not oauth users this can be achieved with anonymous access enabled:
@Override
public void configure(HttpSecurity http) throws Exception {
http
//some configuration
.and()
.anonymous() //allow anonymous access
.and()
.authorizeRequests()
.antMatchers("/views/**").permitAll()
//other security settings
Anonymous access will add additional filter: AnonymousAuthenticationFilter
to the filter chain that populate AnonymousAuthenticationToken
as Authentication information in case no Authentication
object in SecurityContext
I've this security config for check AuthUser by /public/auth
:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests()
.antMatchers("/api/skills/**", "/api/profile/**", "/api/info/**").authenticated()
.antMatchers("/api/**").hasAuthority(Role.ROLE_ADMIN.getAuthority())
.antMatchers("/public/auth").permitAll()
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().csrf().disable();
}
@GetMapping(value = "/public/auth")
private ResponseEntity<User> getAuthUser(@AuthenticationPrincipal AuthUser authUser) {
return authUser == null ?
ResponseEntity.notFound().build() :
ResponseEntity.ok(authUser.getUser());
}