JDBC的Spring会话|主体为空

时间:2019-03-13 17:29:13

标签: mysql spring-boot spring-security spring-jdbc spring-session

我将Spring Session与JDBC和Mysql一起使用。 Spring Security登录成功,但是主体名称为null。

有人有主意吗,那是什么错误?

文件:

application.yaml:

  session:
    store-type: jdbc
    jdbc:
      initialize-schema: always
      table-name: SPRING_SESSION

配置:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@EnableJdbcHttpSession
@EnableJpaRepositories(basePackageClasses = UsersRepository.class)
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/*").authenticated().anyRequest().permitAll()
                .antMatchers("/sources/*").anonymous().anyRequest().permitAll()
                .antMatchers("/public/*").anonymous().anyRequest().permitAll()
                .and()
                .formLogin().
                loginPage("/login").
                loginProcessingUrl("/app-login").
                usernameParameter("app_username").
                passwordParameter("app_password").
                permitAll()
                .and()
                .exceptionHandling().
                accessDeniedPage("/error403");
    }

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

这是数据库表的图片: link

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sandbox</groupId>
<artifactId>TestApp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session</artifactId>
        <version>1.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
</dependencies>
<properties>
    <java.version>1.8</java.version>
</properties>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <executable>true</executable>
            </configuration>

        </plugin>
    </plugins>
</build>
</project>

UPDATE 03/18/19

我无法更改安全策略。 link

更新

如果将以下Bean添加到我的Security配置中,则数据库中的principal_name不再为空。现在有已登录用户的用户名。 但是在每个站点重新加载后,都会创建一个新会话,因此用户无法说已登录。

@Bean
public HttpSessionIdResolver httpSessionIdResolver(){
    return new HeaderHttpSessionIdResolver("X-Auth-Token");
}

3 个答案:

答案 0 :(得分:0)

登录后,您的凭据将被删除。您可以防止这种情况,但是您无法从PrincipleSecurityContext中找到密码。在上面的配置文件中尝试以下代码:

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

    auth.eraseCredentials(false);
    auth.userDetailsService(myUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}

更新

添加以下bean并查看结果:

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

还请向您的问题添加 pom.xml 内容。

更新

如果使用Thymeleaf,请将以下几行添加到pom:

<properties>
    <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
    <thymeleaf-extras-springsecurity4.version>3.0.4.RELEASE</thymeleaf-extras-springsecurity4.version>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

现在主要部分,您配置文件:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@EnableJdbcHttpSession
@EnableJpaRepositories(basePackageClasses = UsersRepository.class)
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    <strike>@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }</strike>


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

        auth.eraseCredentials(false);
        auth.userDetailsService(myUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/*").authenticated().anyRequest().permitAll()
                .antMatchers("/sources/*").anonymous().anyRequest().permitAll()
                .antMatchers("/public/*").anonymous().anyRequest().permitAll()
                .and()
                .formLogin().
                loginPage("/login").
                loginProcessingUrl("/app-login").
                usernameParameter("app_username").
                passwordParameter("app_password").
                permitAll()
                .and()
                .exceptionHandling().
                accessDeniedPage("/error403");
    }

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

最后是控制器:

@ResponseBody
@GetMapping("/check")
public String check(Principal principal) {

    System.out.println(principal.getName());
    return "ok";
}

答案 1 :(得分:0)

如果您使用的是Spring 3,那么这可能会帮助您获取用户名

@RequestMapping(value="", method = RequestMethod.method)   
public String showCurrentUser(Principal principal) {
      return principal.getName();
}

或更改SecurityContextHolder MODE可能会对您有所帮助。 Refer Here


@GetMapping(value = {"/", ""})
    public String start(Principal principal, Model model) {
        if(principal.getName()!=null)
        {
            //your code
        }
        else
        {
            //your code
        }    
        return something;
    }

答案 2 :(得分:0)

我终于找到了问题。我必须将接口Serializable实现到我的User类。现在可以正常工作了。

相关问题