Issue
I use csrf in my code in spring-security.xml. I think the problems are related with csrf. All code is working but there are problems with login.jsp and spring-security.xml. spring-security.xml looks like this:
<http auto-config="true">
<intercept-url pattern="/list" access="ROLE_USER"/>
<intercept-url pattern="/security" access="isAnonymous()"/>
<form-login login-page="/security"
default-target-url="/list"
authentication-failure-url="/security?error"
username-parameter="username"
password-parameter="password"/>
<logout logout-success-url="/security?logout"/>
<csrf disabled="true"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="password" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
my LoginController look like this:
@Controller
public class LoginController {
@RequestMapping(value = "/security", method = RequestMethod.GET)
public String login(@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout,
Model model) {
if (error != null) {
model.addAttribute("error", "Invalid username or password");
}
if (logout != null) {
model.addAttribute("msg", "You logout successfully");
}
return "login";
}
}
This is my code in login.jsp:
<body onload='document.loginForm.username.focus();'>
<div id="login-box">
<h2>Insert Your Login and password:</h2>
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name='loginForm' action="<c:url value='/security'/>" method="post">
<table>
<tr>
<td>User:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td colspan="3">
<input name="submit" type="submit" value="submit"/>
</td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</div>
When you open the page opens
but when I log in to the main page such error crashes such this
What should I fix my code?
Solution
I think the error is because you lack login-processing-url
, which is the URL where Spring Login will trigger the authentication process.
Adding it via XML:
login-processing-url="/security"
Alternatively, if you do not wish to add it, make your form to send its POST request to /login
, which is the default URL for Spring to trigger authentication (for Spring Security 4 and above).
See more here.
Answered By - Petar Bivolarski
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)