1
votes

I'm new to spring boot security and following this tutorial:

https://www.baeldung.com/spring-security-jdbc-authentication

I'm using POSTMAN to test.

I used Type = Basic Auth in Authorization -> Type

Username/Password = admin/12345

I tried everything but always get following response:

{
    "timestamp": "2019-10-11T16:03:23.463+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/api/user"
}    

One of the URLs:

http://localhost:8080/api/user

Here is my security configuration:

package com.spr.security;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
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 com.spr.util.Constants;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter 
{
    @Autowired
    private DataSource dataSource;

    @Autowired
    private PasswordEncoder passwordEncoder;

    protected void configure(HttpSecurity http) throws Exception 
    {
        http.httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/api/**").hasRole("USER")
            .antMatchers("/admin/**").hasRole("ADMIN")
            .and()
            .csrf().disable()
            .headers().frameOptions().disable();
    }

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
    {
            auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder);  

        /*
         * By default spring security assumes `users` table for storing users 
         * and `authorities` table for storing roles
         */
    }

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

Also tried:

auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(new BCryptPasswordEncoder());  

I created following tables using entities.

users
    id int AUTO_INCREMENT (PK)
    username UNIQUE varchar(256)
    email varchar(256)

authorities
    username varchar(256)
    authority varchar(256)

There is single record in each table

In users:

username = admin
password = $2y$10$llcw8Cbuww90KW1dYB6Rn.98iM0JyTiC1VBT1WveVKz99VqbhFLpG
email = [email protected]

Password is 12345 hashed on bcrypt-generator.com with 10 strength

In authorities:

username = admin
authority = ROLE_USER

I also tried authority = USER

I have following dependency in my pom.xml

<!-- Spring data JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- spring security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

        <!-- for jdbc authentication -->
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

My application.properties file

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:mysql://localhost:3306/sprboot?useSSL=false&serverTimezone=UTC
spring.datasource.username=spr
spring.datasource.password=boot


## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=validate

spring.jackson.serialization.fail-on-empty-beans=false

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
logging.level.org.springframework.security=DEBUG

Without Spring Security, all my paths, controllers, jpa etc. works fine.

What am I doing wrong here?

Any more information required?

Edit

Is there a way to see spring security authentication sql in log window(console) I added following in application.properties but nothing shows the generated sql

spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
logging.level.org.springframework.security=DEBUG

I'm using mysql database

1

1 Answers

0
votes

There were two problems and this is how I fixed:

Changed hasRole() to hasAuthority()

protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/api/**").hasAuthority("USER")
            .antMatchers("/admin/**").hasAuthority("ADMIN")
            .and()
            .csrf().disable()
            .headers().frameOptions().disable();
    }

I found in another link on stack overflow that there is a bug in Spring Security and the bcrypted password should start with $2a... and not with $2b... or $2y...