简体   繁体   中英

Spring 4 Security jdbc authentication

I'm trying to get JDBC authentication to work with my little side project, by the looks of it, it should work, but it does not. All the configurations follow bellow.

If I switch to inMemory auth which has the same username/password it works perfectly.

This is what I get if I log the output:

1]

AuthenticationManagerBuilder configuration:

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

    auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("select user_name as username, password, enabled from gag.users as u where u.user_name=?")
            .authoritiesByUsernameQuery("select user_name as username, role from gag.user_roles as u where u.user_name=?");
}

HttpSecurity configuration:

@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/post/**").hasRole("USER")
            .and()
                .formLogin()
                    .loginPage("/login")
            .and()
                .exceptionHandling().accessDeniedPage("/denied")
            .and()
                .csrf().disable();
    // @formatter:on
}

DB Tables:

CREATE TABLE gag.USERS(
    id SERIAL PRIMARY KEY,
    user_name varchar(30) UNIQUE,
    password varchar(30),
    enabled BOOLEAN NOT NULL DEFAULT TRUE
);

CREATE TABLE gag.USER_ROLES(
    id SERIAL PRIMARY KEY,
    user_name varchar(30) REFERENCES gag.USERS(user_name) NOT NULL,
    role varchar(30) NOT NULL,
    UNIQUE(user_name, role)
);

INSERT INTO gag.USERS(user_name, password, enabled) VALUES('admin', 'admin', TRUE);
INSERT INTO gag.USER_ROLES(user_name, role) VALUES('admin', 'USER');

Any ideas why I am getting 403 for a user who does have the correct role?

Since the version of 4, Spring Security framework adds automatically the prefix ROLE_ . See the relevant documtnation about migrating from Spring Security 3.x to 4.x:

  • 8. Automatic ROLE_ prefixing :

    Spring Security 4 automatically prefixes any role with ROLE_. The changes were made as part of SEC-2758

    So you have to change the insertion to:

     INSERT INTO gag.USER_ROLES(user_name, role) VALUES('admin', 'ROLE_USER'); 
  • 8.3. Disable ROLE_ Prefixing

    If you want to omit the ROLE_ prefix, you might find interesting the article linked above.

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