'Why get 403 Forbidden while click on login [duplicate]

I am working on Spring MVC project. I use Spring Security for secure the url of my project. While i click on login button login succesfully but got error type=Forbidden, status=403 on localhost:8092/user/index url. I think Spring Security interrupt the url.

Here down is code of Spring Security:

CustomUserDetail

public class CustomUserDetail implements UserDetails {
    
    private User user;

    public CustomUserDetail(User user) {
        super();
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority(user.getRole());
        return List.of(authority);
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getEmail();
    }

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

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

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

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

UserDetailsServiceImpl

public class UserDetailsServiceImpl implements UserDetailsService{
    @Autowired
    private UserRepo userRepo;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepo.getUserByUserName(username);
        
        if(user == null)
        {
            throw new UsernameNotFoundException(username);
        }
        
        CustomUserDetail customUserDetail = new CustomUserDetail(user);
        
        
        return customUserDetail;
    }
    
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeRequests()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .antMatchers("/user/**").hasRole("USER")
        .antMatchers("/**").permitAll()
        .and()
            .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/user/index");
}

Here down is Controller

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepo userRepo;
    
    
    @RequestMapping(value = "/index")
    public String login(Model mdl, Principal principal)
    {
        
        User user = userRepo.getUserByUserName(principal.getName());
        
        mdl.addAttribute("user", user);
        
        return "user/user-dashboard";
    }
}

Here down is my user-dashboard.html while which is located on src/main/resources/templates/user.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <h1> Details of User</h1>
    
    <p th:text="${user.name}"></p>
    <p th:text="${user.email}"></p>
</body>
</html>

I got while click on login button that time url is http://localhost:8092/user/index

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sat Mar 19 18:16:13 IST 2022
There was an unexpected error (type=Forbidden, status=403).
Forbidden

Snapshot of database:

enter image description here



Solution 1:[1]

I think you should check two things.

  1. What is the role data of user in the database?
  • I think it should have a prefix "ROLE_" like ROLE_ADMIN in the database.
  1. Check the password which should be encrypted and saved in the database.
  • Spring security's DaoAuthenticationProvider uses default PasswordEncoder made by PasswordEncoderFactories.createDelegatingPasswordEncoder() method.
  • So you have to save the encrypted password of user data by using PasswordEncoderFactories.createDelegatingPasswordEncoder() instance's encode method. passwordEncoder.encode(password).

Solution 2:[2]

while saving in db save it as role_user all caps. spring security compares roles as (role+ hasRole value)==db value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ayush Dubey