Spring Security:用于 API 的 JWT 令牌和用于 Web 的会话 [英] Spring Security: JWT token for API and session for web

查看:19
本文介绍了Spring Security:用于 API 的 JWT 令牌和用于 Web 的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在我的 Spring Boot 应用程序中同时使用这两种安全性.我已经用 JWT 做了 API 端,但是不知道如何实现 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.

这是我的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));
}

我想要这样的东西:

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

推荐答案

经过6个小时的搜索,解决方案如下:https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity

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

这是我的做法:

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

希望这能有所帮助!

这篇关于Spring Security:用于 API 的 JWT 令牌和用于 Web 的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆