Ivan Kotov
Ivan Kotov

Reputation: 11

Spring boot 2.2.7 OAuth2 client + User in database. How correct get authority from database for @AuthenticationPrincipal?

The application implements the possibility of authorization using the data stored in the database. Added the ability to log in through a third-party OAuth server. The server gives the client ID in its database, this id is stored in a table with data about the application user in a separate field.

I can not figure out how to correctly pull up user roles from the application database when authorizing using OAuth2 with spring boot 2.2.7? As i understood @EnableOAuth2Sso and PrincipalExtractor are deprecated and don't work (.

Please, don't scold me too much, I have little experience, I tried to figure out the documentation https://docs.spring.io/spring-security/site/docs/current/reference/html5/#multiple-httpsecurity. Thank you all for your help!

package ru.geekbase.portal.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ru.geekbase.portal.domain.User;
import ru.geekbase.portal.repos.UserRepo;
import ru.geekbase.portal.service.UserService;
import ru.geekbase.portal.util.XSSFilter;


@Configuration
@EnableWebSecurity

public class WebSecurityConfig  extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    private XSSFilter xssFilter;

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder(8);
    }

   

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();

       // http.addFilterAfter(
        //        new XSSFilter(), BasicAuthenticationFilter.class);

        http.authorizeRequests()
                .antMatchers("/",
                        "/checkUser",
                        "/checkUser/**",
                        "/login",
                        "/login/**",
                        "/oauth_login",
                        "/js/public/**",
                        "/css/**"
                        ,"/registration",
                        "/nav",
                        "/success_unsubscrube",
                        "/unsuccess_unsubscrube",
                        "/politic",
                        "/unsuccess_reset_password",
                        "/success_reset_password",
                        "/unsuccess_req_password",
                        "/success_req_password",
                        "/unsubscribe",
                        "/unsubscribe/**",
                        "/resetpassword",
                        "/resetpassword/**",
                        "/reqpassword",
                        "/reqpassword/**",
                        "/students/**",
                        "/students",
                        "/registration",
                        "/passwordrequest",
                        "/usergroup",
                        "/useragreement",
                        "/studentgroup").permitAll()
                .antMatchers("/js/authentificated/**",
                        "/profile",
                        "/courcemaker",
                        "/cource",
                        "/lectionmaker",
                        "/lection",
                        "/answermaker",
                        "/answer",
                        "/questionmaker",
                        "/question",
                        "/testmaker",
                        "/test",
                        "/logout",
                        "/record",
                        "/accesstocource",
                        "/studentlist",
                        "/seminars",
                        "/seminar",
                        "/seminar/**",
                        "/accessToSeminar",
                        "/seminarsForStudents").authenticated()
                .antMatchers("/js/admin/**",
                        "/usermaker",
                        "/srvconf",
                        "/userlist",
                        "/srv",
                        "/group",
                        "/courcelist",
                        "/activeMeetings").hasAnyAuthority("ADMIN")
                .antMatchers("/llist",
                        "/lectionlist",
                        "/activeMeetingsList").hasAnyAuthority("ADMIN","MODERATOR")

                .antMatchers("/gs-guide-websocket",
                        "/lectionStatistics/**",
                        "/lectionStatistic",
                        "/seminarListener",
                        "/accessUserToSeminar",
                        "/userForSelectList").hasAnyAuthority("USER", "ADMIN","LECTOR")
                .antMatchers("/lectionviews",
                        "/testforuser",
                        "/testforuser/**",
                        "/saveanswer",
                        "/saveanswer/**",
                        "/testattempt",
                        "/courceListForStudent",
                        "/lectionListForStudent",
                        "/lectionsListForStudent",
                        "/watchlist",
                        "/js/student/**",
                        "/upload",
                        "/file",
                        "/downloadFile",
                        "/filesForLection",
                        "/seminar/**",
                        "/seminar/begin/{id}",
                        "/seminarsForStudent",
                        "/seminarList").hasAnyAuthority("USER", "ADMIN","LECTOR","STUDENT")
                .anyRequest().authenticated()

                .and()
                    .oauth2Login()
                    .loginPage("/oauth_login")
                    .permitAll()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
               // .and()
               // .rememberMe()
                .and()
                .logout()
                .permitAll();


    }

    @Override
    protected  void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)
                .passwordEncoder(passwordEncoder);

    }

}

user service:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import ru.geekbase.portal.repos.UserRepo;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserRepo userRepo;
    @Autowired
    private PasswordEncoder  passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userRepo.findByUsername(username);
    }
}

User class:

Upvotes: 1

Views: 300

Answers (0)

Related Questions