I am trying to implement one simple user authentication by Spring Security in Spring MVC model but I am constantly getting "Bad credentials" even if I am providing correct credentials .
Below are my files. Can someone please suggest what am I missing?
Security.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/security
https://www.springframework.org/security/spring-security-4.2.xsd">
<http>
<csrf disabled="true"/>
<intercept-url pattern="/login*" access="ROLE_USER"/>
<form-login login-page="/" default-target-url="/login" authentication-failure-url="/"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="rishavraj#gmail.com" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Controller.java:
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView Login(#RequestParam Map<String, String> reqvar) {
System.out.println("login");
ModelAndView form = new ModelAndView("Index");
return form;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView Index() {
System.out.println("Index");
ModelAndView form = new ModelAndView("Index");
return form;
}
Index.jsp:
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION !=null}">
<div class="alert alert-danger fade in">
×
<strong> Wrong Email or Password </strong>
<h4> Caused by :
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</h4>
</div>
</c:if>
<form action="/Mail/login" method="post">
<div class="form-group">
<label for="inputUserName">Email</label>
<input class="form-control" placeholder="Email ID" type="text" id="inputUserName" name="Email"/>
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input class="form-control" placeholder="Login Password" type="password" id="inputPassword" name="password"/>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>`
</div>
</form>
Related
The problem is that after successful authorization on the login form (login.jsp), when trying to access the controllers (path: rest/profile), a browser window appears asking for the username and password (httpbasic).
QUESTION: why Spring Security requires double authentication - entering a password at the login form is not enough?
login.jsp:
<%# page contentType="text/html" pageEncoding="UTF-8" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<jsp:include page="fragments/headTag.jsp"/>
<body>
<jsp:include page="fragments/bodyHeader.jsp"/>
<div class="container">
<div class="d-flex justify-content-center h-100">
<div class="card">
<div class="card-header">
<h3><spring:message code="app.signIn"/></h3>
</div>
<div class="card-body">
<form:form id="login_form" action="spring_security_check" method="post">
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="text" name="username" class="form-control" placeholder="<spring:message code="user.login"/>">
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input type="password" name="password" class="form-control" placeholder="<spring:message code="user.password"/>">
</div>
<div class="row align-items-center remember">
<input type="checkbox"><spring:message code="app.rememberMe"/>
</div>
<div class="form-group">
<button type="submit" class="btn float-right yellow_btn"><spring:message code="app.login"/></button>
</div>
</form:form>
</div>
<br>
<div class="card-footer">
<div class="d-flex justify-content-center links">
<spring:message code="app.notProfileQuestion"/>
</div>
<div class="d-flex form-group justify-content-center">
<a class="btn yellow_btn" href="profile/register"><spring:message code="app.register"/> »</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<http pattern="/resources/**" security="none"/>
<http pattern="/webjars/**" security="none"/>
<http pattern="/rest/**" use-expressions="true" name="restSecurityFilterChain" create-session="stateless">
<http-basic/>
<intercept-url pattern="/rest/profile/register" access="isAnonymous()"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<csrf disabled="true"/>
</http>
<beans:bean class="org.springframework.security.crypto.factory.PasswordEncoderFactories" id="passwordEncoder" factory-method="createDelegatingPasswordEncoder"/>
<http>
<intercept-url pattern="/login" access="permitAll()"/>
<intercept-url pattern="/profile/register" access="isAnonymous()"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-page="/login" default-target-url="/profile"
authentication-failure-url="/login?error=true"
login-processing-url="/spring_security_check"/>
<logout logout-success-url="/login"/>
<!--<csrf disabled="true"/>-->
</http>
<authentication-manager>
<authentication-provider user-service-ref="userService">
<password-encoder ref="passwordEncoder"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
How to fix problem? I want enter password only once - at login page.
I am new to spring. I am creating a spring mvc app. I have a admin url "/admin/".If I login with user credentials with ROLE_ADMIN then I can access the admin page. Right now this scenario is working fine. But If I have not logged in with ROLE_ADMIN and I try to access /admin/ url spring security is redirecting me to /login page.
Here what I want to not expose to outer world that /admin/(or admin url exists) url need authentication. And I want to show default exception page or home page if someone who is not authorized try to access /admin/ url.
Also I need to have custom "/login" url like "/custom_url/" instead of "/login"
But right now I don't have any idea how to achieve this. Any help is appreciated.
applicationContext.xml
</bean>
<security:http auto-config="true">
<security:intercept-url pattern="/admin/**"
access="hasRole('ROLE_ADMIN')" />
<security:form-login
login-page="/login"
default-target-url="/admin"
always-use-default-target="true"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<security:logout logout-success-url="/" invalidate-session="true" logout-
url="/logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"
authorities-by-username-query="SELECT
username, authority From authorities WHERE username = ?"
users-by-username-query="SELECT
username, password, enabled FROM users WHERE username = ?" />
</security:authentication-provider>
</security:authentication-manager>
Login Controller
#RequestMapping("/login")
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 and password");
}
if(logout!=null) {
model.addAttribute("msg", "You have been logged out successfully.");
}
return "login";
}
login.jsp
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name="loginForm" action="<c:url
value="/j_spring_security_check" />" method="post">
<c:if test="${not empty error}">
<div class="error" style="color: #ff0000;">${error}</div>
</c:if>
<div class="form-group">
<label for="username">User: </label>
<input type="text" id="username" name="username"
class="form-control" />
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password"
class="form-control" />
</div>
<input type="submit" value="Submit" class="btn btn-default">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
I am using Spring security 4.
Change the authentication-failure-url="/login?error" to authentication-failure-url="/". This will redirect you to Home page.
The correct xml-snippet in applicationContext.xml is as following:
<security:form-login
login-page="/login"
default-target-url="/admin"
always-use-default-target="true"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/"
username-parameter="username"
password-parameter="password" />
Note: You can change value of authentication-failure-url attribute to an exception page as per need.
I'm working with spring mvc 4.3.8 and spring webflow 2.4.5 along with thymeleaf 3.x. I'm unable to get the error messages from jsr-303 annotations displayed with spring webflow after validation fails. While the view itself is re-rendered, error messages are not displayed. what else do I need to do ? Please help.
<!-- WebFlow Configuration -->
<bean id="viewFactoryCreator"
class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="viewResolvers" ref="viewResolver" />
</bean>
<webflow:flow-builder-services id="flowBuilderServices"
view-factory-creator="viewFactoryCreator" validator="validator"/>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<webflow:flow-registry id="flowRegistry"
flow-builder-services="flowBuilderServices" base-path="/WEB-INF/spring/flows">
<webflow:flow-location id="add-locale" path="/locale-flow.xml" />
</webflow:flow-registry>
<!-- the flow executor drives the execution of the flow -->
<webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry"/>
<!-- Enables FlowHandler URL mapping.
This handler adapter is the bridge between DispatcherServlet and the flow executor -->
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
<property name="flowExecutor" ref="flowExecutor" />
</bean>
<!-- Maps request paths to flows in the flowRegistry.
Tells DispatcherServlet to send flow requests to the FlowHandlerAdapter -->
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="flowRegistry" />
<property name="order" value="0" />
</bean>
locale-flow.xml
<input name="id"/>
<on-start>
<evaluate expression="localeController.newLocaleForm(id)" result="flowScope.localeForm" />
</on-start>
<view-state id="localeForm" view="locale/locale-form-p1" model="flowScope.localeForm">
<transition on="next" to="configureMessageBundle"/>
</view-state>
<view-state id="configureMessageBundle" view="locale/locale-form-p2" model="flowScope.localeForm" />
<view-state id="returnToViewPage" view="externalRedirect:locale-page.html" />
The backing form bean, LocaleForm.java
#NotNull(message = "Locale cannot be blank")
private String code;
#NotBlank(message = "Name cannot be blank")
#Size(min = 3, max = 255, message = "Name must be between 3 and 255 characters")
#Pattern(regexp = "^[\\w-_]+$", message = "Name can contain only alphabets, numbers, hypen and underscore")
private String name;
The form view page, locale-form-p1.html
<form class="form-horizontal" th:action="${flowExecutionUrl}" th:object="${localeForm}" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-xs-2">Locale</label>
<div class="col-xs-10">
<select class="selectpicker form-control" tabindex="0" th:field="*{code}">
<option value="en_US" th:each="locale : *{availableLocales}"
th:value="${locale.key}"
th:text="${locale.value}">English (US)</option>
</select>
</div>
</div>
<div class="form-group required">
<label class="control-label col-xs-2">
Name <a role="button" data-toggle="popover" data-trigger="hover" data-html="true" title="" data-content="Provide a unique name for the Locale." data-placement="top"><span class="fa fa-info-circle"></span></a>
</label>
<div class="col-xs-10" th:classappend="${#fields.hasErrors('name')}? has-error">
<input class="form-control" type="text" placeholder="Name" th:field="*{name}" >
<span class="help-block" th:unless="${#fields.hasErrors('name')}">Allowed characters are alphabets, numbers, hyphen and underscore.</span>
<span class="help-block" th:errors="*{name}"></span>
</div>
</div>
<div class="form-group">
<div class="col-xs-2 col-xs-offset-2">
<button class="btn btn-primary btn-sm btn-primary-spacing" type="submit" name="_eventId_next">Next</button>
<button class="btn btn-default btn-sm" type="button" up-href="locale-page.html" up-target="#page-content">Cancel</button>
</div>
</div>
</form>
Resolved it. It turns out that Spring Web Flow has a different way of providing the user with feedback messages. The Spring Web Flow reference documentation says: “Spring Web Flow’s MessageContext is an API for recording messages during the course of flow executions”.
<div class="form-group required">
<label class="control-label col-xs-2">
Name <a role="button" data-toggle="popover" data-trigger="hover" data-html="true" title="" data-content="Provide a unique name for the Locale." data-placement="top"><span class="fa fa-info-circle"></span></a>
</label>
<div class="col-xs-10" th:classappend="${#arrays.length(flowRequestContext.messageContext.getMessagesBySource('name'))>0}? has-error">
<input class="form-control" type="text" placeholder="Name" th:field="*{name}" >
<span class="help-block" th:if="${#arrays.isEmpty(flowRequestContext.messageContext.getMessagesBySource('name'))}">Allowed characters are alphabets, numbers, hyphen and underscore.</span>
<p class="help-block" th:each="err : ${flowRequestContext.messageContext.getMessagesBySource('name')}" th:text="${err.text}">Input is invalid</p>
</div>
</div>
I am new to using Spring MVC framework and have designed a html page which has two forms. One is login(form id: loginform) and other is for signup((form id:signupform). The controller is being called correctly for the login page but for the signup, nothing happens (no controller is called) and the page just refreshes. I am not able to find out the source of the problem. Here is my JSP page:
Login.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%#page session="true"%>
<html>
<head>
<title>Login Page</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous">
</script>
<spring:url value="/resources/css/mylogin.css" var="mainCss" />
<link href="${mainCss}" rel="stylesheet" />
<%-- <link href="<spring:url value='/resources/css/mylogin.css'/>" rel="stylesheet"> --%>
</head>
<body>
<div class="container">
<div id="loginbox" style="margin-top: 50px;"
class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Sign In</div>
</div>
<div style="padding-top: 30px" class="panel-body">
<c:if test="${not empty error}">
<!-- Invalid Username Password -->
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<!-- Logged out successfully -->
<div class="msg">${msg}</div>
</c:if>
<div style="display: none" id="login-alert"
class="alert alert-danger col-sm-12"></div>
<form id="loginform" class="form-horizontal" role="form"
name="loginform"
action="<c:url value='/j_spring_security_check' />" method='POST'>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input id="login-username"
type="text" class="form-control" name="username" value=""
placeholder="username">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-lock"></i></span> <input id="login-password"
type="password" class="form-control" name="password"
placeholder="password">
</div>
<div style="margin-top: 10px" class="form-group">
<div class="col-sm-12 controls">
<input class="btn btn-success" id="btn-login" name="submit"
type="submit" value="LOG IN" /> <input type="hidden"
name="${_csrf.parameterName}" value="${_csrf.token}" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div
style="border-top: 1px solid #888; padding-top: 15px; font-size: 85%">
Don't have an account! <a href="#"
onClick="$('#loginbox').hide(); $('#signupbox').show()">
Sign Up Here </a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div id="signupbox" style="display: none; margin-top: 50px"
class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Sign Up</div>
</div>
<div class="panel-body">
<form:form id="signupform" class="form-horizontal" role="form"
method="POST" modelAttribute="userForm"
action="<c:url value='/adduser' />">
<div id="signupalert" style="display: none"
class="alert alert-danger">
<p>Error:</p>
<span></span>
</div>
<form:hidden path="id" />
<spring:bind path="name">
<div class="form-group">
<label for="name" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<form:input path="name" type="text" class="form-control"
name="name" placeholder="Name" />
</div>
</div>
</spring:bind>
<spring:bind path="email">
<div class="form-group">
<label for="email" class="col-md-3 control-label">Email</label>
<div class="col-md-9">
<form:input path="email" type="text" class="form-control"
name="email" placeholder="Email Address" />
</div>
</div>
</spring:bind>
<spring:bind path="username">
<div class="form-group">
<label for="username" class="col-md-3 control-label">Username</label>
<div class="col-md-9">
<form:input path="username" type="text" class="form-control"
name="username" placeholder="Username" />
</div>
</div>
</spring:bind>
<spring:bind path="password">
<div class="form-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<form:input path="password" type="password"
class="form-control" name="passwd" placeholder="Password" />
</div>
</div>
</spring:bind>
<spring:bind path="dob">
<div class="form-group">
<label for="date" class="col-md-3 control-label">Date of
Birth</label>
<div class="col-md-9">
<form:input path="dob" type="date" name="bday"
class="form-control" />
</div>
</div>
</spring:bind>
<spring:bind path="image">
<div class="form-group">
<label for="pic" class="col-md-3 control-label">Profile
Picture</label>
<div class="col-md-9">
<form:input path="image" type="file" name="pic"
class="form-control" />
</div>
</div>
</spring:bind>
<spring:bind path="genreName">
<div class="form-group">
<label for="genre" class="col-md-3 control-label">Favorite
Genres</label>
<div class="col-md-9">
<!-- <input type="file" name="pic" class="form-control"> -->
<form:select multiple="" path="genreName" name="genreNames"
class="form-control">
<c:forEach items="${genres}" var="genre" varStatus="ctr">
<option id="${genre.id}" value="${genre.name}">${genre.name}</option>
</c:forEach>
</form:select>
</div>
</div>
</spring:bind>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9">
<input class="btn btn-info" id="tn-signup" name="submit"
type="submit" value="Sign Up" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div
style="border-top: 1px solid #888; padding-top: 15px; font-size: 85%">
Already have an account? <a id="signinlink" href="#"
onClick="$('#signupbox').hide(); $('#loginbox').show()">
Sign In </a>
</div>
</div>
</div>
</form:form>
</div>
</div>
</div>
</div>
</body>
</html>
Controller:
package com.moviebase.web.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.moviebase.web.model.user.UserDao;
import com.moviebase.web.model.genre.Genre;
import com.moviebase.web.model.genre.GenreDao;
import com.moviebase.web.model.user.User;
#Controller
public class MainController {
#Autowired
public UserDao userDao;
#Autowired
public GenreDao genreDao;
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
public ModelAndView defaultPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Moviebase");
model.addObject("message", "This is default page!");
model.setViewName("hello");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName(); //get logged in username
User user = userDao.findByUsername(username);
System.out.println(user.toString());
return model;
}
#RequestMapping(value = "/admin**", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Moviebase");
model.addObject("message", "This page is for ROLE_ADMIN only!");
model.setViewName("admin");
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
System.out.println(" error:"+error);
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
List<Genre> genreList = genreDao.getAllGenres();
model.addObject("genres", genreList);
User user = new User();
model.addObject("userForm", user);
model.setViewName("login");
return model;
}
#RequestMapping(value = "/adduser", method = RequestMethod.POST)
public ModelAndView createUser(#ModelAttribute("userForm") User user,
BindingResult result) {
// ModelAndView model = new ModelAndView();
// model.setViewName("redirect:/");
System.out.println("Came here");
userDao.insert(user);
return new ModelAndView("redirect:/admin");
}
//for 403 access denied page
#RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accesssDenied() {
ModelAndView model = new ModelAndView();
//check if user is login
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
System.out.println(userDetail);
model.addObject("username", userDetail.getUsername());
}
model.setViewName("403");
return model;
}
}
Web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>MovieBase</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml,
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>database</groupId>
<artifactId>moviebase</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Moviebase</name>
<properties>
<jdk.version>1.7</jdk.version>
<spring.version>3.2.8.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
<mysql.connector.version>5.1.30</mysql.connector.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- Spring Security JSP Taglib -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- jstl for jsp page -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
</dependencies>
<build>
<finalName>moviebase</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<wtpversion>2.0</wtpversion>
</configuration>
</plugin>
</plugins>
</build>
</project>
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.moviebase.*" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
Your singup form has the http method POST but your controller is form http method GET
Your JSP:
<form:form id="signupform" class="form-horizontal" role="form"
method="POST" modelAttribute="userForm"
action="<c:url value='/adduser' />">
Your controller:
#RequestMapping(value = "/adduser", method = RequestMethod.GET)
public ModelAndView createUser(#ModelAttribute("userForm") User user,
BindingResult result) {
I successfully configured an oauth spring application. However, my headache is how to make it return to the login page with a successful token; The log shows the following entry:
`DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling`
Here is my login page:
` <c:url value="/oauth/token" var="loginProcessingUrl"/>
<form:form action="${loginProcessingUrl}" method="post">
<fieldset>
<legend>Please Login</legend>
<!-- use param.error assuming FormLoginConfigurer#failureUrl contains the query parameter error -->
<c:if test="${param.error != null}">
<div>
Failed to login.
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</c:if>
</div>
</c:if>
<!-- the configured LogoutConfigurer#logoutSuccessUrl is /login?logout and contains the query param logout -->
<c:if test="${param.logout != null}">
<div>
You have been logged out.
</div>
</c:if>
<c:if test="${param.success != null}">
<div>
You have been successfully been authenticated.
</div>
</c:if>
<p>
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</p>
<!-- if using RememberMeConfigurer make sure remember-me matches RememberMeConfigurer#rememberMeParameter -->
<p>
<label for="remember-me">Remember Me?</label>
<input type="checkbox" id="remember-me" name="remember-me"/>
<input type="hidden" id="client_id" name="client_id" value="11111111"/>
<input type="hidden" id="client_secret" name="client_secret" value="2222222"/>
<input type="hidden" id="grant_type" name="grant_type" value="password"/>
<input type="hidden" id="response_type" name="response_type" value="token"/>
<input type="hidden" id="redirect_uri" name="redirect_uri" value="/login?success=1"/>
</p>
<div>
<button type="submit" class="btn">Log in</button>
</div>
</fieldset>
`
And here's my spring-security.xml file:
`<http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="authenticationManager"
xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER"/>
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>`
Why can't I go back to the login page once a token is successfully issued. Any help is appreciated.
Thanks