Spring Security get user info in rest service, for authenticated and not authenticated users

后端 未结 2 917
眼角桃花
眼角桃花 2020-12-10 03:19

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(

相关标签:
2条回答
  • 2020-12-10 04:11

    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

    0 讨论(0)
  • 2020-12-10 04:23

    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());
    }
    
    0 讨论(0)
提交回复
热议问题