I’m currently integrating Spring Boot with Flutter, but I’m encountering an issue with the login process. Specifically, I’m receiving a 302 redirection error which is preventing successful login and further progress.
Details:
Issue: When attempting to log in, the application encounters a 302 redirection error. This issue is blocking the login process and preventing me from moving forward.
Expected Outcome: The login should successfully authenticate the user and redirect them to the appropriate page or dashboard.
Observed Outcome: Instead of logging in successfully, the application results in a 302 redirection error, and the login does not proceed.
Request for Assistance:
Could you provide guidance on how to resolve this 302 redirection error? Any suggestions on troubleshooting steps or configuration changes in Spring Boot or Flutter to fix this issue would be greatly appreciated.
Feel free to adjust the message based on any additional details or specific aspects of your integration.
package com.example.//.config;
import com.example.//.Service.UserDetailService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final UserDetailService userDetailService;
private final ObjectMapper objectMapper;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors
.configurationSource(CorsConfig.corsConfigurationSource())
)
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/user/create", "/user/login", "/user/mypage").permitAll()
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
)
.formLogin(form -> form
.loginPage("/user/login").permitAll()
.usernameParameter("nickname")
.passwordParameter("password")
.successHandler(authenticationSuccessHandler())
)
.logout(logout -> logout
.logoutUrl("/user/logout")
.invalidateHttpSession(true)
);
return http.build();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return new ProviderManager(daoAuthenticationProvider);
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
return (request, response, auth) -> response.sendRedirect("/friends/page");
}
}
package com.example.blogback.config;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CorsConfig {
public static CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
ArrayList<String> allowedOriginPatterns = new ArrayList<>();
allowedOriginPatterns.add("http://localhost:");
allowedOriginPatterns.add("http://localhost:*");
configuration.setAllowedOrigins(allowedOriginPatterns);
ArrayList<String> allowedHttpMethods = new ArrayList<>();
allowedHttpMethods.add("GET");
allowedHttpMethods.add("POST");
allowedHttpMethods.add("PUT");
allowedHttpMethods.add("DELETE");
allowedHttpMethods.add("OPTIONS");
configuration.setAllowedMethods(allowedHttpMethods);
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setAllowedHeaders(List.of(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
import 'package:flutter/material.dart';
import 'package:flutter_application_blog/page/mainPage.dart';
import 'package:flutter_application_blog/page/mypage.dart';
import 'package:flutter_application_blog/page/create_account.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:dio/dio.dart';
class Login extends StatefulWidget {
const Login({super.key});
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
final TextEditingController _nicknameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final _formKey = GlobalKey<FormState>();
static final storage = FlutterSecureStorage();
dynamic userInfo;
@override
void initState() {
super.initState();
_checkLoginStatus();
}
Future<void> _checkLoginStatus() async {
userInfo = await storage.read(key: 'login');
if (userInfo != null) {
Navigator.pushNamed(context, '/main');
}
}
Future<bool> loginAction(String nickname, String password) async {
try {
var dio = Dio(BaseOptions(
baseUrl: "http://localhost:8081",
headers: {"Accept": "application/json"},
));
var param = {'nickname': nickname, 'password': password};
Response response = await dio.post('/user/login', data: param);
if (response.statusCode == 200) {
final userId = response.data['user_id'];
await storage.write(key: 'login', value: jsonEncode(userId));
print('Login successful!');
return true;
} else {
print('Login failed: ${response.statusCode}');
return false;
}
} catch (e) {
print('Error occurred: $e');
return false;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _buildBody(),
);
}
Widget _buildBody() {
return Container(
color: const Color(0xffFEFCEB),
child: SingleChildScrollView(
child: Column(
children: [
Container(
width: 150,
height: 150,
margin: const EdgeInsets.only(top: 45, bottom: 20),
child: Image.asset("logo.png"),
),
Container(
width: 330,
height: 250,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
border: Border.all(width: 0.5, color: const Color(0xff1A495D)),
),
child: Form(
key: _formKey,
child: Column(
children: [
_buildTextField(
controller: _nicknameController,
label: 'Nickname',
),
_buildTextField(
controller: _passwordController,
label: 'Password',
obscureText: true,
),
],
),
),
),
const SizedBox(height: 20),
_buildLoginButton(),
const SizedBox(height: 10),
_buildSignUpPrompt(),
],
),
),
);
}
Widget _buildLoginButton() {
return Container(
width: 100,
height: 50,
margin: const EdgeInsets.all(20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(40),
color: const Color(0xffB5DDDB),
),
child: Center(
child: GestureDetector(
onTap: () async {
if (_formKey.currentState!.validate()) {
bool success = await loginAction(
_nicknameController.text, _passwordController.text);
if (success) {
print('로그인 성공');
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MainPage()), // CreateAccount로 수정
);
} else {
print('로그인 실패');
}
}
},
child: const Text(
'Login',
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
),
);
}
Widget _buildSignUpPrompt() {
return Column(
children: [
const Text(
"계정이 없으신가요?",
style: TextStyle(color: Colors.grey, fontSize: 15),
),
TextButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => create_account()), // CreateAccount로 수정
);
},
child: const Text(
"회원가입",
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.black,
),
),
),
],
);
}
Widget _buildTextField({
required TextEditingController controller,
required String label,
bool obscureText = false,
}) {
return Padding(
padding: const EdgeInsets.only(top: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: const TextStyle(fontSize: 22),
textAlign: TextAlign.left,
),
Container(
width: 250,
margin: const EdgeInsets.only(top: 10),
decoration: BoxDecoration(
border: Border.all(width: 2, color: const Color(0xffB5DDDD)),
borderRadius: BorderRadius.circular(10),
),
child: TextField(
controller: controller,
obscureText: obscureText,
decoration: InputDecoration(
border: InputBorder.none,
hintText: " ",
contentPadding: const EdgeInsets.only(left: 10, top: 12),
),
),
),
],
),
);
}
}
최수진 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.