0

I am trying to set up spring security by jdbcauthentication. I have looked at a lot of guides but unfortunately I get an error after providing the correct login details "Spring Security - HTTP Status 403 – Forbidden - The server understood the request but refuses to authorize it." When I enter incorrect login details, I receive a message about their incorrectness, so checking the correctness of the login and password in the database works.

There is no errors in Tomcat Localhost Log, and Spring log. There is only HttP Status 403... on web page after submit login credentials.

I am very beginner in the spring. Can someone tell me what I'm doing wrong? What should I do to make it work properly?

WebConfig.java

@Configuration
@EnableWebMvc
@ComponentScan({"com.name.surname.controller"})
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver jspViewResolver() {
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/WEB-INF/views/");
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }
}

WebSecurityConfig.java

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("select username, password, enabled from users where username = ?")
                .authoritiesByUsernameQuery("select username, authority from authorities where username = ?")
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").hasAnyRole("ADMIN")
                .and()
                .formLogin()
                .and()
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .and()
                .csrf().disable();
    }
}

Controller.java

@Controller
public class UserController {

    @RequestMapping(value = {"/"})
    public String index(Model model, Principal principal) {
        modelAndView.addObject("loggedUser", principal.getName());
        model.addAttribute("loggedUser", principal.getName());
        return "index";
    }
}

Authorities.java

@Entity
public class Authorities {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int authorityId;

    private String username;

    private String authority;

    public Authorities() {
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }


    public String getAuthority() {
        return authority;
    }

    public void setAuthority(String authority) {
        this.authority = authority;
    }

    @Override
    public String toString() {
        return "Authorities{" +
                "authorityId=" + authorityId +
                ", login='" + username + '\'' +
                ", authority='" + authority + '\'' +
                '}';
    }
}

Users.java

@Entity
public class Users {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int userId;

    private String username;

    private String password;

    private boolean enabled = true;

    public Users() {
    }

    public int getUserId() {
        return userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    @Override
    public String toString() {
        return "Users{" +
                "userId=" + userId +
                ", login='" + username + '\'' +
                ", password='" + password + '\'' +
                ", active=" + enabled +
                '}';
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Index</title>
    </head>

    <body>

        <h1>Spring Security - Hello World Example JDBC authorisation</h1>
        <h4>You are logged in as ${loggedUser}</h4>

        <hr>
        <hr>

        <a href="/logout">Logout</a>    

    </body>
</html>
Grzesiek
  • 1
  • 1
  • Does the user you are testing with appear in the `authorities` table with `ADMIN` ? – moilejter Jul 28 '18 at 01:36
  • Yes. Table authorities: authorityid: 84, authority: ADMIN, username: grzesiek Table users: userid: 83, username: grzesiek, password:"my encoded password", enabled: true – Grzesiek Jul 28 '18 at 02:00
  • 1
    Sounds like your problem is the missing "ROLE_" prefix on role names (in the DB?): https://stackoverflow.com/questions/33205236/spring-security-added-prefix-role-to-all-roles-name – moilejter Jul 28 '18 at 04:12
  • I do not use Spring Boot. Missing prefix "ROLE_" was the problem. Thank You. Problem is solved. – Grzesiek Jul 28 '18 at 09:31

0 Answers0