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

后端 未结 2 919
眼角桃花
眼角桃花 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: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 getAuthUser(@AuthenticationPrincipal AuthUser authUser) {
        return authUser == null ? 
                   ResponseEntity.notFound().build() :
                   ResponseEntity.ok(authUser.getUser());
    }
    

提交回复
热议问题