[JAVA] Login fails because the redirect URL of the self-login screen is incorrect in spring-security

phenomenon

If you log in under the spring-security environment, it will fail only the first time, and you will be authenticated normally from the second time onward.

Cause

The method of constructing the redirect URL to the self-login screen was incorrect.

Details

The following controllers were prepared to display the login screen of their own.

@Controller
@RequestMapping("/login")
public class LoginController {
    @GetMapping
    public String index(Optional<String> error) {
        ...
    }
}

Next, I prepared the following controller to redirect to `/ login``` when I came to / ``.

@Controller
public class TopController {
    @GetMapping("/")
    public String index() {
        return "redirect:" + MvcUriComponentsBuilder.fromMethodName(LoginController.class, "index", "").build().toUri().toString();
    }
}

However, this specification method is incorrect and the redirect URL becomes `` http: // localhost: 8080 / login? Error incorrectly. In short, this URL is a URL for displaying login errors.

First, when you redirect to this URL, the login screen is displayed. By the way, spring-security has a function called `SavedRequest``` that if there is a URL that was accessed before login, it will be skipped to that URL after login. The last URL in this case is login? Error incorrectly for login errors. For this reason, if the login is successful, the URL of the login error will be skipped.

Coping

Changed the usage of MvcUriComponentsBuilder.

return "redirect:" + MvcUriComponentsBuilder.fromController(LoginController.class).build().toUri().toString();

I didn't really understand the relationship between `` `MvcUriComponentsBuilder``` and Optional </ code>, so I compromised.

Recommended Posts

Login fails because the redirect URL of the self-login screen is incorrect in spring-security
Get the URL of the HTTP redirect destination in Java
Get the URL of the HTTP redirect destination in Ruby
When the login screen times out with spring-security, the CSRF token expires and login fails.
Correspondence of the part where Authentication # getDetails is done in the unit test of spring-security
In Time.strptime,% j (total date of the year) is
Source used to get the redirect source URL in Java
Display the list in setDetails on the screen with spring-security
Determine that the value is a multiple of 〇 in Ruby
What is the representation of domain knowledge in the [DDD] model?
[Android] Try to display the effect on the touched part of the screen, which is common in games.