title: How to correctly set role for User in oauth2 app spring boot
body: <p>I'm struggling with spring security after implemented oauth2 in my application. That's my first experience, but will be glad to hear nice or anger comments. That's the way to improve.</p>
  <p><strong>Problem:</strong>
  During the logging in my application I see that I retrieve from google oidcuser object of DefaultOidcUser class. This object has collection of <code>authorities</code> with 4 items: <a href="https://i.stack.imgur.com/xo06B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xo06B.png" alt="enter image description here" /></a></p>
  <p>Honestly, I don't understand why I get ROLE_USER for this user in my system, cos actually it has ADMIN role in my system (role is created by me).</p>
  <p>Generally I have 3 roles in my app: User, Manager, Admin. But can't understand how to correctly set particular role for special user.</p>
  <p>Because of this, when I put smth like:</p>
  <pre><code>  .antMatchers(&quot;/api/**&quot;).hasRole(Role.ADMIN.name())
    .antMatchers(&quot;/administration/**&quot;).hasRole(Role.ADMIN.name())
  </code></pre>
  <p>I get 403 cos as I understand I get ROLE_USER for each user.</p>
  <p>Can you please help me to set roles for each User but from my db (not this default ROLSER_USER from google)?
  Also I read about GrantedAuthorities and mapper of grantedAuthorities, but it's a bit unclear for me.</p>
  <p>I will be glad to hear any opinion. any useful link to improve my knowledge about this. Cos main goal: to understand how it works.</p>
  <p>Other classes of my oauth2 implementation below:</p>
  <pre><code>@Getter
  @Setter
  @RequiredArgsConstructor
  public class CustomOidcUser implements OidcUser {
  
      private final OidcUser oidcUser;
      private String email;
      private String firstName;
      private String lastName;
  
      @Override
      public Map&lt;String, Object&gt; getClaims() {
          return oidcUser.getClaims();
      }
      @Override
      public OidcUserInfo getUserInfo() {
          return oidcUser.getUserInfo();
      }
  
      @Override
      public OidcIdToken getIdToken() {
          return oidcUser.getIdToken();
      }
  
      @Override
      public Map&lt;String, Object&gt; getAttributes() {
          return oidcUser.getAttributes();
      }
  
      @Override
      public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {
          return oidcUser.getAuthorities();
      }
  
      @Override
      public String getName() {
          return oidcUser.getName();
      }
  
  }
  </code></pre>
  <pre><code>@Service
  @RequiredArgsConstructor
  public class CustomOidcUserService extends OidcUserService {
  
      private final UserRepository repository;
      private static final String GOOGLE_KEY_LASTNAME = &quot;family_name&quot;;
      private static final String GOOGLE_KEY_FIRSTNAME = &quot;given_name&quot;;
  
      @Override
      public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
          final OidcUser oidcUser = super.loadUser(userRequest);
          CustomOidcUser newUser =  new CustomOidcUser(oidcUser);
  
          String email = oidcUser.getAttributes().get(&quot;email&quot;).toString();
          User user = createUserIfNoExist(email, oidcUser);
          newUser.setEmail(email);
          newUser.setFirstName(user.getFirstName());
          newUser.setLastName(user.getLastName());
  
          return newUser;
      }
  
      public User createUserIfNoExist(String email, OidcUser oidcUser) {
          return repository.findByEmail(email)
                  .orElseGet(() -&gt; {
                      User newUser = new User();
                      newUser.setEmail(email);
                      newUser.setRole(Role.USER);
                      newUser.setStartWorkAt(LocalDate.now());
                      newUser.setLastLoginDate(LocalDateTime.now());
      ...
  
  </code></pre>
  <pre><code>@Configuration
  @EnableWebSecurity
  @RequiredArgsConstructor
  @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
    private final AuthProvider authProvider;
    private final OnSuccessHandler onSuccessHandler;
    private final CustomOidcUserService customOidcUserService;
    private final UserService userService;
  
    protected void configure(HttpSecurity http) throws Exception {
      SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
      successHandler.setUseReferer(true);
      successHandler.setDefaultTargetUrl(&quot;/success&quot;);
      successHandler.setAlwaysUseDefaultTargetUrl(true);
  
      http
          .addFilterAfter(new UserHasManagerFilter(userService), BasicAuthenticationFilter.class)
          .cors()
          .and()
            .csrf()
            .disable()
            .authorizeRequests()
            .antMatchers(&quot;/api/**&quot;).hasRole(Role.ADMIN.name())
            .antMatchers(&quot;/administration/**&quot;).hasRole(Role.ADMIN.name())
          .and()
              .httpBasic()
          .and()
            .formLogin()
            .loginPage(&quot;/unauthorized&quot;)
            .loginProcessingUrl(&quot;/login&quot;)
            .defaultSuccessUrl(&quot;/success&quot;)
            .failureUrl(&quot;/failed&quot;)
            .successHandler(successHandler)
            .usernameParameter(&quot;email&quot;)
            .passwordParameter(&quot;password&quot;)
            .permitAll()
          .and()
            .logout()
            .logoutUrl(&quot;/logout&quot;)
            .logoutSuccessUrl(&quot;/logout_success&quot;)
            .permitAll()
          .and()
              .oauth2Login()
  
                .loginPage(&quot;/&quot;)
                .userInfoEndpoint(userInfoEndpoint -&gt;
                        userInfoEndpoint.oidcUserService(customOidcUserService)
                        .customUserType(CustomOidcUser.class, &quot;google&quot;)
  //                      .userAuthoritiesMapper(userAuthoritiesMapper())
                )
  
                .defaultSuccessUrl(&quot;/dashboard&quot;, true)
                .successHandler(onSuccessHandler)
                .failureHandler(authenticationFailureHandler())
              .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers(&quot;/**&quot;)
          .permitAll();
    }
  </code></pre>