728x90

The HTTP 401 response code indicates an "Unauthorized" error. This typically means that the request requires user authentication which has not been provided or which has failed. Here are some common reasons and solutions for this issue in a Spring Boot application:

1. Spring Security Configuration

If your Spring Boot application is using Spring Security, it might be configured to require authentication for accessing the API endpoints. This is a common scenario when Spring Security is included in the project dependencies.

Solutions:

  • Provide Authentication Credentials: If your API requires authentication, you need to provide the correct credentials in your request header. In Postman, you can do this in the Authorization tab, selecting the type of authentication your API uses (like Basic Auth, Bearer Token, etc.) and entering the required credentials.
  • Adjust Security Configuration: If the /users endpoint should be publicly accessible without authentication, you'll need to adjust your Spring Security configuration to permit requests to this endpoint. Here’s an example of how you might configure this in your WebSecurityConfigurerAdapter:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        // ... other configurations ...
        .authorizeRequests()
        .antMatchers("/users").permitAll() // Permit requests to /users endpoint
        .anyRequest().authenticated()
        // ... other configurations ...
}

 

2. CSRF Protection

Spring Security's CSRF (Cross-Site Request Forgery) protection is enabled by default. If you are making a POST request to your Spring Boot application from Postman or another REST client, CSRF protection might block it.

Solutions:

  • Include CSRF Token: If CSRF protection is necessary (usually for browser-based applications), include the CSRF token in your request.
  • Disable CSRF Protection for API Endpoints: If you're building a stateless REST API (especially one used by non-browser clients), you might consider disabling CSRF protection for those endpoints:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        // ... other configurations ...
        .csrf().disable() // Disable CSRF protection
        // ... other configurations ...
}

3. CORS Configuration

While the 401 error isn't directly related to CORS (Cross-Origin Resource Sharing), incorrect CORS settings can sometimes manifest as authentication issues, especially if you're calling the API from a different domain.

Solution:

  • Configure CORS Settings: Ensure that your Spring Boot application has the correct CORS settings if your API is being accessed from a different domain.

4. Check Server Logs

Finally, check your server logs for any additional information or error messages related to the failed request. The logs can provide more specific details about why the request was unauthorized.

By addressing these areas, you should be able to resolve the 401 error and successfully make POST requests to your /users endpoint.

 
 
 
728x90

1. Reserved Keyword 

 GenerationTarget encountered exception accepting command : Error executing DDL "create table evaluation (id bigint generated by default as identity, comment varchar(255), content_id bigint, like boolean, unlike boolean, user_id bigint, primary key (id))" via JDBC [Syntax error in SQL statement "create table evaluation (id bigint generated by default as identity, comment varchar(255), content_id bigint, [*]like boolean, unlike boolean, user_id bigint, primary key (id))"; expected "identifier";]

 

위에서 나온 부분은 Reserved Keyword (예약어) 에 대한 사용이다.

 

 JPA  를 사용할 때에 JPA는 형상변환을 거쳐 SQL 문법 (Diarect)로 변환되게 되는데, 코드상에서 보면 당연히 '좋아요' 를 like로 지정할 수 있겠지만 이러한 부분은 SQL 문법에서의 like 와 문제를 일으키게 된다.

 

문제가 되는 코드를 살펴보자

 

package com.webtoon.webtoonservice.model;

import jakarta.persistence.*;

@Entity
public class Evaluation {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long userId;
    private Long contentId;
    private Boolean like;
    private Boolean unlike;
    private String comment; // Ensure validation to disallow special characters
}

 

이 부분에서 해당하는 부분을 고치려면 like를 likes 로 고치거나 이스케이핑을 하면 된다.

 

@Entity
@Table(name = "evaluation")
public class Evaluation {
    // other fields...

    @Column(name = "`like`")
    private Boolean like;
    private Boolean unlike;

    // getters and setters...
}

 


2. Reserved Keyword

GenerationTarget encountered exception accepting command : Error executing DDL "create table user (id bigint generated by default as identity, gender varchar(255), register_date timestamp(6), type varchar(255), user_email varchar(255), user_name varchar(255), primary key (id))" via JDBC [Syntax error in SQL statement "create table [*]user (id bigint generated by default as identity, gender varchar(255), register_date timestamp(6), type varchar(255), user_email varchar(255), user_name varchar(255), primary key (id))"; expected "identifier";]

 

가장 눈치채기 어려운 것 중 하나인 user 에 대한 부분이다. 변환하는 과정 도중 Directs 중에서 user 라는 부분은 이미 잡혀있는 user table 을 지칭하여 문제를 일으킬 수 있기 마련인데 이러한 부분 때문에 문제가 발생한다.

 

package com.webtoon.webtoonservice.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;


import jakarta.persistence.*;
import java.util.Date;



@Entity
@Table(name = "`user`") // use backticks to escape
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String userName;
    private String userEmail;
    private String gender; // Consider using an enum here
    private String type;   // Consider using an enum here
    private Date registerDate;
}

 

마찬가지로 이스케이핑을 하여 처리할 수 있다.

'Java > Spring Boot JPA' 카테고리의 다른 글

[Trouble Shooting] Open API  (1) 2024.02.01
HTTP 401 response code  (0) 2024.01.12
[Shop] 세션 끊김 문제 완전 해결  (0) 2023.09.21
[Shop] Session Failure Problem  (0) 2023.09.16
[sync] Complete Session Sync issue  (0) 2023.09.01
728x90

 

H2 Database 에서 Windows 기반을 선택한 경우

./webtoon 과 같이 dir path 를 지정하는 경우 에러가 난다.

 

그러니까 . 기반은 linux 에서나 작동하던 것 같다는 소리인데,

결과적으로 ~ 기준으로 하면 상대경로 기반에서 들어감으로 생성이 매우매우매우매우 잘된다는 것이다.

728x90
sudo mysqld_safe --skip-grant-tables &​
mysql  Ver 15.1 Distrib 10.1.33-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

Identify the Server Version

Depending on the MySQL or MariaDB server version you are running on your system, you will need to use different commands to recover the root password.

You can find your server version by issuing the following command:

mysql --version

 

If you have MySQL installed in your system the output will look something like this:

MariaDB case

mysql  Ver 15.1 Distrib 10.1.33-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

 

 

Be sure to make a note of which version of MySQL or MariaDB you’re running.

How to Reset MySQL or MariaDB Root Password

Follow these steps to reset your MySQL/MariaDB root password:

1. Stop the MySQL/MariaDB service

To change the root password first, you need to stop the MySQL server. To do so type the following command:

sudo systemctl stop mysql

 

 

2. Start the MySQL/MariaDB server without loading the grant tables

Start the database server without loading the grant tables:

sudo mysqld_safe --skip-grant-tables &

The ampersand & at the end of the command above will cause the program to run in the background , so you can continue to use the shell.

 

When the --skip-grant-tables option is used, anyone can to connect to the database server without a password and with all privileges granted.

 

3. Log in to the MySQL shell

Now you can connect to the database server as the root user:

mysql -u root

 

4. Set a new root password 

Run the following commands if you run MySQL 5.7.6 and later or MariaDB 10.1.20 and later:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MY_NEW_PASSWORD';
FLUSH PRIVILEGES;

 

 

5. Trouble Shooting

In mysqld_safe mode, ALTER 'root' user command was denied, 

- Information Gathering

 

ERROR 1290 (HY000): The MariaDB server is running with the --skip-grant-tables option so it cannot execute this statement

It will mean "Bloat" status, Hence Query need to be updated.

 

MariaDB> UPDATE mysql.user SET authentication_string = PASSWORD('NEW_PASSWORD')
WHERE User = 'root' AND Host = 'localhost';

MariaDB> FLUSH PRIVILEGES;

Or We colud choose FLUSH 

MariaDB> FLUSH PRIVILEGES;
MariaDB> ALTER USER 'root'@'localhost' IDENTIFIED BY 'NEW_PASSWORD';
MariaDB> FLUSH PRIVILEGES;

5. Stop and Start the database server normally

Now that the root password is set, stop the database server and start it normally:

mysqladmin -u root -p shutdown

 

 

You will be prompted to enter the new root password.

Start the database server normally:

 

For MariaDB, type:

sudo systemctl start mariadb

+ Recent posts