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().getAuthentication()
if user is authenticated.
.antMatchers("/app/rest/question/useroperation/list/**").permitAll()
in ouath2 configuration like below, then I can get user info for
authenticated user, but 401 error for not authenticated users..antMatchers("/app/rest/question/useroperation/list/**").permitAll()
and ignore the url in WebSecurity by
web.ignoring()..antMatchers("/app/rest/question/useroperation/list/**")
in SecurityConfiguration
like below, then all users can call the
service, but I cant get user information from SecurityContext.How can configure my spring security to call a url for authenticated and not authenticated users and get user info from SecurityContext if user logged in.
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Inject
private Http401UnauthorizedEntryPoint authenticationEntryPoint;
@Inject
private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
@Override
public void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.logout()
.logoutUrl("/app/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.and()
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable()
.headers()
.frameOptions().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/views/**").permitAll()
.antMatchers("/app/rest/authenticate").permitAll()
.antMatchers("/app/rest/register").permitAll()
.antMatchers("/app/rest/question/useroperation/list/**").permitAll()
.antMatchers("/app/rest/question/useroperation/comment/**").authenticated()
.antMatchers("/app/rest/question/useroperation/answer/**").authenticated()
.antMatchers("/app/rest/question/definition/**").hasAnyAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/app/rest/logs/**").hasAnyAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/app/**").authenticated()
.antMatchers("/websocket/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/websocket/**").permitAll()
.antMatchers("/metrics/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/health/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/dump/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/shutdown/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/beans/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/info/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/autoconfig/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/env/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/protected/**").authenticated();
}
}
SecurityConfiguration
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Inject
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new StandardPasswordEncoder();
}
@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/bower_components/**")
.antMatchers("/fonts/**")
.antMatchers("/images/**")
.antMatchers("/scripts/**")
.antMatchers("/styles/**")
.antMatchers("/views/**")
.antMatchers("/i18n/**")
.antMatchers("/swagger-ui/**")
.antMatchers("/app/rest/register")
.antMatchers("/app/rest/activate")
.antMatchers("/app/rest/question/useroperation/list/**")
.antMatchers("/console/**");
}
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
}
The getPrincipal() method normally returns the UserDetails object in Spring Security, which contains all the details of the currently logged-in user.
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
The Spring Security Architecture There are multiple filters in spring security out of which one is the Authentication Filter, which initiates the process of authentication. Once the request passes through the authentication filter, the credentials of the user are stored in the Authentication object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With