简体   繁体   中英

Unauthorized calls after configuring spring security

I want to secure my REST endpoints but I'm having troubles... it was just fine while I was using inMemoryAuth , but since I tried to use credentials stored in the database - it stopped working.

Ok, so my Entity classes look like that

class User {
    @Id
    @GeneratedValue
    @Column(name = "user_id")
    private Integer id;

    @Column
    private String username;

    @Column
    private String password;

    @ManyToMany
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;
}

class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "role_id")
    private Integer id;

    @Column(name = "role")
    private String role;
}

And my security config

@Configuration
class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    private DataSource dataSource;

    public SecurityConfiguration(DataSource dataSource) {
        this.dataSource = dataSource;
    }

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
            .usersByUsernameQuery(usersQuery)
            .authoritiesByUsernameQuery(rolesQuery)
            .dataSource(dataSource)
            .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/task/**").hasRole("USER")
            .and()
            .csrf().disable()
            .formLogin().disable();
    }
}

And finally, application.properties

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/teamplanner?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Europe/Warsaw
spring.datasource.username=root
spring.datasource.password=root

spring.queries.users-query=select username, password from user where username=?
spring.queries.roles-query=select u.username, r.role from user u inner join user_role ur on(u.user_id=ur.user_id) inner join role r on(ur.role_id=r.role_id) where u.username=?

Now, I'm trying to call /task/all with Basic auth in postman and I'm getting

{
    "timestamp": "2019-04-21T22:50:17.189+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/task/all"
}

Both queries I've stored in the application.properties return records if I run them directly in the database

you should tell spring security that the user is enabled, see the source code in JdbcDaoImpl

在此输入图像描述

so you should change the configuration spring.queries.users-query

spring.queries.users-query=select username, password, 1 from user where username=?

if you can't still make it sense, change the value of role name from USER to ROLE_USER

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM