I’m implementing SecurityFilterChain and setting it up so that only admins have access. When I log in with the admin,doesn’t allow me access

I’m implementing SecurityFilterChain and setting it up so that only admins have access to that endpoint. When I log in with the admin account, it doesn’t allow me access.

My code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class EndToEndSecurityDemo{
private final EndToEndUserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests((auth) -> auth
.requestMatchers(
new AntPathRequestMatcher("/"),
new AntPathRequestMatcher("/login"),
new AntPathRequestMatcher("/error"),
new AntPathRequestMatcher("/registration/**")
)
.permitAll()
.requestMatchers(
new AntPathRequestMatcher("/users/**")
)
.hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin((login)-> login
.loginPage("/login")
.usernameParameter("email")
.defaultSuccessUrl("/")
.permitAll()
)
.logout((logout)-> logout
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
)
.csrf(withDefaults())
.httpBasic(withDefaults())
.build();
}
}
@Data
public class EndToEndUserDetails implements UserDetails {
private String userName;
private String password;
private boolean isEnabled;
private List<GrantedAuthority> authorities;
public EndToEndUserDetails(User user) {
this.userName = user.getEmail();
this.password = user.getPassword();
this.isEnabled = user.isEnabled();
this.authorities =
Arrays.stream(user.getRoles().toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return userName;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
@Service
@RequiredArgsConstructor
public class EndToEndUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.findByEmail(email)
.map(EndToEndUserDetails::new)
.orElseThrow(()-> new UsernameNotFoundException("User not found"));
}
}
</code>
<code>@Configuration @EnableWebSecurity @RequiredArgsConstructor public class EndToEndSecurityDemo{ private final EndToEndUserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationProvider authenticationProvider(){ DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService); authenticationProvider.setPasswordEncoder(passwordEncoder()); return authenticationProvider; } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http .authorizeHttpRequests((auth) -> auth .requestMatchers( new AntPathRequestMatcher("/"), new AntPathRequestMatcher("/login"), new AntPathRequestMatcher("/error"), new AntPathRequestMatcher("/registration/**") ) .permitAll() .requestMatchers( new AntPathRequestMatcher("/users/**") ) .hasRole("ADMIN") .anyRequest().authenticated() ) .formLogin((login)-> login .loginPage("/login") .usernameParameter("email") .defaultSuccessUrl("/") .permitAll() ) .logout((logout)-> logout .invalidateHttpSession(true) .clearAuthentication(true) .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/") ) .csrf(withDefaults()) .httpBasic(withDefaults()) .build(); } } @Data public class EndToEndUserDetails implements UserDetails { private String userName; private String password; private boolean isEnabled; private List<GrantedAuthority> authorities; public EndToEndUserDetails(User user) { this.userName = user.getEmail(); this.password = user.getPassword(); this.isEnabled = user.isEnabled(); this.authorities = Arrays.stream(user.getRoles().toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return userName; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } @Service @RequiredArgsConstructor public class EndToEndUserDetailsService implements UserDetailsService { private final UserRepository userRepository; @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { return userRepository.findByEmail(email) .map(EndToEndUserDetails::new) .orElseThrow(()-> new UsernameNotFoundException("User not found")); } } </code>
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class EndToEndSecurityDemo{
    private final EndToEndUserDetailsService userDetailsService;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeHttpRequests((auth) -> auth
                        .requestMatchers(
                                new AntPathRequestMatcher("/"),
                                new AntPathRequestMatcher("/login"),
                                new AntPathRequestMatcher("/error"),
                                new AntPathRequestMatcher("/registration/**")
                        )
                        .permitAll()
                        .requestMatchers(
                                new AntPathRequestMatcher("/users/**")
                        )
                        .hasRole("ADMIN")
                        .anyRequest().authenticated()
                )
                .formLogin((login)-> login
                        .loginPage("/login")
                        .usernameParameter("email")
                        .defaultSuccessUrl("/")
                        .permitAll()
                )
                .logout((logout)-> logout
                        .invalidateHttpSession(true)
                        .clearAuthentication(true)
                        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                        .logoutSuccessUrl("/")
                )
                .csrf(withDefaults())
                .httpBasic(withDefaults())
                .build();
    }
}

@Data
public class EndToEndUserDetails implements UserDetails {
    private String userName;
    private String password;
    private boolean isEnabled;
    private List<GrantedAuthority> authorities;

    public EndToEndUserDetails(User user) {
        this.userName = user.getEmail();
        this.password = user.getPassword();
        this.isEnabled = user.isEnabled();
        this.authorities =
                Arrays.stream(user.getRoles().toString().split(","))
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}


@Service
@RequiredArgsConstructor
public class EndToEndUserDetailsService implements UserDetailsService {
    private final UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        return userRepository.findByEmail(email)
                .map(EndToEndUserDetails::new)
                .orElseThrow(()-> new UsernameNotFoundException("User not found"));
    }
}

At registration, I set the user as a ‘user’.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Service
@RequiredArgsConstructor
public class UserService implements IUserService{
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final VerificationTokenService verificationTokenService;
@Override
public List<User> getAllUsers() {
return userRepository.findAll();
}
@Override
public User registerUser(RegistrationRequest registration) {
var user = new User(registration.getFirstName(), registration.getLastName(),
registration.getEmail(),
passwordEncoder.encode(registration.getPassword()),
Arrays.asList(new Role("USER")));
return userRepository.save(user);
}
@Override
public Optional<User> findByEmail(String email) {
return Optional.ofNullable(userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("User not found")));
}
@Override
public Optional<User> findById(Long id) {
return userRepository.findById(id);
}
@Transactional
@Override
public void updateUser(Long id, String firstName, String lastName, String email) {
userRepository.update(firstName, lastName, email, id);
}
@Transactional
@Override
public void deleteUser(Long id) {
Optional<User> theUser = userRepository.findById(id);
theUser.ifPresent(user -> verificationTokenService.deleteUserToken(user.getId()));
userRepository.deleteById(id);
}
}
</code>
<code>@Service @RequiredArgsConstructor public class UserService implements IUserService{ private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final VerificationTokenService verificationTokenService; @Override public List<User> getAllUsers() { return userRepository.findAll(); } @Override public User registerUser(RegistrationRequest registration) { var user = new User(registration.getFirstName(), registration.getLastName(), registration.getEmail(), passwordEncoder.encode(registration.getPassword()), Arrays.asList(new Role("USER"))); return userRepository.save(user); } @Override public Optional<User> findByEmail(String email) { return Optional.ofNullable(userRepository.findByEmail(email) .orElseThrow(() -> new UsernameNotFoundException("User not found"))); } @Override public Optional<User> findById(Long id) { return userRepository.findById(id); } @Transactional @Override public void updateUser(Long id, String firstName, String lastName, String email) { userRepository.update(firstName, lastName, email, id); } @Transactional @Override public void deleteUser(Long id) { Optional<User> theUser = userRepository.findById(id); theUser.ifPresent(user -> verificationTokenService.deleteUserToken(user.getId())); userRepository.deleteById(id); } } </code>
@Service
@RequiredArgsConstructor
public class UserService implements IUserService{
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final VerificationTokenService verificationTokenService;

    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public User registerUser(RegistrationRequest registration) {
        var user = new User(registration.getFirstName(), registration.getLastName(),
                registration.getEmail(),
                passwordEncoder.encode(registration.getPassword()),
                Arrays.asList(new Role("USER")));
        return userRepository.save(user);
    }
    @Override
    public Optional<User> findByEmail(String email) {
        return Optional.ofNullable(userRepository.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException("User not found")));
    }
    @Override
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }

    @Transactional
    @Override
    public void updateUser(Long id, String firstName, String lastName, String email) {
        userRepository.update(firstName, lastName, email, id);
    }

    @Transactional
    @Override
    public void deleteUser(Long id) {
        Optional<User> theUser = userRepository.findById(id);
        theUser.ifPresent(user -> verificationTokenService.deleteUserToken(user.getId()));
        userRepository.deleteById(id);
    }
}

In the database, I have the tables ‘user’, ‘role’, and ‘user_role’. I changed the name of the role to ‘ADMIN’ and restarted the application, but it’s still the same.

New contributor

Veaceslav Antoci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật