Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security: JWT token for API and session for web

I aim to use both security in my Spring Boot app. I already done the API side with JWT, but I don't know how to implement the session for the WEB side. I have already done that in another project but I don't know how to make them work together.

Here is my SecurityConfig:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().ignoringAntMatchers("/api/**")
         .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
         .and()
            .authorizeRequests()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/login").permitAll()
            .antMatchers("/api/public").permitAll()
            .antMatchers("/api/lost").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/contact").permitAll()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/file/**").permitAll()
            .anyRequest().authenticated()
         .and()
            .apply(new JWTConfigurer(this.tokenProvider));
}

I would like to have something like this :

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
         // For API side something like : .match("/api/**")
         // No CSRF
         .csrf().ignoringAntMatchers("/api/**")
         // STATELESS session
         // Use token filter
         .apply(new JWTConfigurer(this.tokenProvider));

         // For WEB side something like : .match "others"
         // Use CSRF
         .csrf()
         // Use session

         // And the other permit :
            .authorizeRequests()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/login").permitAll()
            .antMatchers("/api/public").permitAll()
            .antMatchers("/api/lost").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/contact").permitAll()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/file/**").permitAll()
            .anyRequest().authenticated();
}

Can anyone tell me how to do that? (and explain me how it works). I have not found any good solution on what I am asking.

like image 720
Julien G. Avatar asked Jul 07 '17 12:07

Julien G.


People also ask

Can I store JWT in session?

A JWT needs to be stored in a safe place inside the user's browser. Any way,you shouldn't store a JWT in local storage (or session storage).

How does Spring Security validate JWT token?

We expose a public POST API for the authentication, and upon passing the correct credentials, it will generate a JWT. If a user tries to access the protected API, it will allow access only if a request has a valid JWT. Validation will happen in the filter registered in the Spring Security filter chain.


1 Answers

After 6 hours of searching, here is the solution : https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity

EDIT : Here is how i did that :

@EnableWebSecurity
public class MultiHttpSecurityConfig {

    @Autowired
    private UserDetailsService userDetailsService;

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

    @Configuration
    @Order(1)
    public class ApiSecurityAdapter extends WebSecurityConfigurerAdapter {

        private TokenProvider tokenProvider;

        public ApiSecurityAdapter(TokenProvider tokenProvider) {
            this.tokenProvider = tokenProvider;
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**") //<= Security only available for /api/**
                .authorizeRequests()
                    .antMatchers("/api/register").permitAll()
                    .antMatchers("/api/login").permitAll()
                    .antMatchers("/api/public").permitAll()
                    .antMatchers("/api/lost").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .apply(new JWTConfigurer(this.tokenProvider))
                .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }

    @Configuration
    public class WebSecurityAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http // <= Security available for others (not /api/)
                .authorizeRequests()
                    .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                    .antMatchers("/").permitAll()
                    .antMatchers("/login").permitAll()
                    .antMatchers("/resources/**").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .formLogin()
                        .loginPage("/login")
                            .usernameParameter("email")
                            .passwordParameter("password")
                            .defaultSuccessUrl("/central", false)
                            .failureForwardUrl("/login/fail")
                .and()
                    .logout()
                        .invalidateHttpSession(true)
                        .logoutUrl("/logout")
                        .logoutSuccessUrl("/")
                .and()
                    .csrf();
        }
    }
}

Hope this can help !

like image 154
Julien G. Avatar answered Oct 21 '22 13:10

Julien G.