1

I use Spring Session with JDBC and Mysql. The Spring Security Login is successfully but the principal name is null.

Does anyone have an idea, whats the mistake?

Files:

application.yaml:

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

Configuration:

@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();
    }
}

Here is a picture of the database table: link

The 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

I can't change the Security strategy. link

UPDATE

If I add the following Bean to my Security configuration, the principal_name in the database is no longer null. Now there is the username of the logged in user. BUT after each site reload, a new session is created, so the user can't say logged in.

@Bean
public HttpSessionIdResolver httpSessionIdResolver(){
    return new HeaderHttpSessionIdResolver("X-Auth-Token");
}
Tom
  • 65
  • 1
  • 3
  • 11

3 Answers3

1

I finally found the problem. I had to implement the interface Serializable to my User class. Now it works fine.

Tom
  • 65
  • 1
  • 3
  • 11
0

Your credentials are getting erased after logging in. You can prevent that but password you won't find from Principle or SecurityContext. Try the below code in the above config file:

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

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

UPDATE

Add the following bean and see the result:

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

Also please add pom.xml content to you question.

UPDATE

Add these lines to your pom if you are using Thymeleaf:

<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>

Now the main part, you config file:

@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();
    }
}

Finally the controller:

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

    System.out.println(principal.getName());
    return "ok";
}
sam
  • 1,800
  • 1
  • 25
  • 47
0

If you are using spring 3 then this might help you to getName of User

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

OR changing the SecurityContextHolder MODE may help you. Refer Here


@GetMapping(value = {"/", ""})
    public String start(Principal principal, Model model) {
        if(principal.getName()!=null)
        {
            //your code
        }
        else
        {
            //your code
        }    
        return something;
    }
Romil Patel
  • 12,879
  • 7
  • 47
  • 76
  • `Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); System.out.println(principal);` **Output:** `User{id=0, email='null', password='null', firstName='null', lastName='null', active=false, roles=null}` – Tom Mar 14 '19 at 08:25
  • How can I change the SecurityContextHolder Mode? – Tom Mar 16 '19 at 22:52
  • @Tom SecurityContextHolder.YOUR_MODE will change the mode. updated answer doesn't help you? – Romil Patel Mar 17 '19 at 06:06
  • I‘m tring to test this. But where I have to put these line in? Which file? The Controller where I want to display the principal? – Tom Mar 17 '19 at 07:48
  • @Tom Yes, you can use it in controller, refer the updated answer – Romil Patel Mar 17 '19 at 08:32
  • Yeah, but I mean, in which file I have to put `SecurityContextHolder.YOUR_MODE` – Tom Mar 17 '19 at 13:44
  • @Tom Refer the Link in answer and this https://stackoverflow.com/questions/3467918/how-to-set-up-spring-security-securitycontextholder-strategy – Romil Patel Mar 17 '19 at 15:22
  • Yeah, but this is null. (See the Link after my Security Configuration) – Tom Mar 18 '19 at 17:12