spring-security JWT登录无法在已部署的Sping Boot 应用程序上工作

x4shl7ld  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(128)

我遵循此JWT tutorial来保护我的应用程序。
我最终得到了以下WebSecurity配置:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private MyUserDetailsService userDetailsService;
    private MyPasswordEncoder passwordEncoder;

    public SecurityConfiguration(MyUserDetailsService userService) {
        this.userDetailsService = userService;
        this.passwordEncoder = new MyPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().authorizeRequests()
                //SIGN_UP_URL = "/login";
                .antMatchers(HttpMethod.GET, SIGN_UP_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                // this disables session creation on Spring Security
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.logout().permitAll();
        http.logout(logout -> logout
                .logoutUrl("/logout")
                .addLogoutHandler(new SecurityContextLogoutHandler())
                .permitAll()
                .clearAuthentication(true));

    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = new CorsConfiguration().applyPermitDefaultValues();
        source.registerCorsConfiguration("/**", corsConfiguration);

        return source;
    }

和下面的JWTAuthenticationFilter:

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;

        //SIGN_UP_URL= "/login"
        setFilterProcessesUrl(MySettings.SIGN_UP_URL); 
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
                                                HttpServletResponse res) throws AuthenticationException {
        try {
            User creds = new ObjectMapper()
                    .readValue(req.getInputStream(), User.class);

            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            creds.getUsername(),
                            creds.getPassword(),
                            new ArrayList<>())
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) throws IOException {
        String token;
        token = JWT.create()
                .withSubject(((User) auth.getPrincipal()).getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + MySettings.EXPIRATION_TIME))
                .sign(Algorithm.HMAC512(MySettings.SECRET.getBytes()));

        String body = ((User) auth.getPrincipal()).getUsername() + " " + token;

        res.getWriter().write(body);
        res.getWriter().flush();
    }

问题

目前,在我的电脑/localhost上启动应用程序时,应用程序接受/login URL上的GET请求。我使用postman,我能够登录并接收令牌。
当我将应用程序部署到服务器时,/login会自动回复403禁止。
数据库是相等的。
我做错了什么?

参考资料

Set custom login url in Spring Security UsernamePasswordAuthenticationFilter JWT authentication
https://www.freecodecamp.org/news/how-to-setup-jwt-authorization-and-authentication-in-spring/

gopyfrb3

gopyfrb31#

试图添加

@CrossOrigin(origins = "*", allowedHeaders = "*")

在控制器中的登录Api上方

相关问题