Security Spring - Found 302 - java

So, I have problem with that when I open localhost/myApp/* it always redirect to localhost/myApp/login with 302 Found Error. I'm beginner of spring.
It's my web.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>SpringTest</display-name>
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/applicationContext.xml
/WEB-INF/spring/securityContext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>ContextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
It's my securityContext.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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<http auto-config="true">
<access-denied-handler error-page="/403" />
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/resources**" access="permitAll"/>
<intercept-url pattern="/images**" access="permitAll"/>
<intercept-url pattern="/**" access="hasRole('ADMIN') or hasRole('USER')"/>
<intercept-url pattern="/admin_panel/**" access="hasRole('ADMIN')"/>
<form-login
login-page="/login"
default-target-url="/"
authentication-failure-url="/login?error"
username-parameter="ssoId" password-parameter="password"/>
<logout logout-success-url="/login?logout" />
<csrf/>
</http>
<global-method-security secured-annotations="enabled"/>
<authentication-manager >
<authentication-provider>
<user-service>
<user name="bill" password="abc123" authorities="ROLE_USER" />
<user name="admin" password="root123" authorities="ROLE_ADMIN" />
<user name="dba" password="root123" authorities="ROLE_ADMIN,ROLE_DBA" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
And my Controller :
package com.program.Controllers;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by mgrzesiuk on 24.07.16.
*/
#Controller
public class SecurityController {
#RequestMapping(value="/login",method= RequestMethod.GET)
public String showLoginForm()
{
return "login";
}
#RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}
#RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
model.addAttribute("user",getPrincipal());
return "accessDenied";
}
private String getPrincipal(){
String userName = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
userName = ((UserDetails)principal).getUsername();
} else {
userName = principal.toString();
}
return userName;
}
}

Related

spring security in rest Web service

I am trying to implement spring security in restweb service.
I am always getting "Entering commence due to failed Authentication" message. It is not going in CustomAuthenticationProvider.java. My code returns me from CustomEntryPoint. I think there's a misconfiguration.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> WEB-INF/security-config.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/security-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
<!-- <welcome-file-list>
<welcome-file>/WEB-INF/index.jsp</welcome-file>
</welcome-file-list> -->
<!-- Tag Libary -->
</web-app>
Spring security file
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<sec:http entry-point-ref="customEntryPoint" use-expressions="true">
<sec:custom-filter ref="authenticationFilter"
before="PRE_AUTH_FILTER" />
<sec:intercept-url pattern="/**"
access="hasAuthority('AUTH_USER')" />
<sec:logout delete-cookies="JSESSIONID" />
<sec:csrf disabled="true" />
</sec:http>
<context:component-scan base-package="org.arpit.java2blog" />
<sec:authentication-manager alias="authenticationManager">
<authentication-provider ref="customAuthenticationProvider" />
</sec:authentication-manager>
<!-- <context:component-scan base-package="org.arpit.java2blog" /> -->
<beans:bean id="authenticationFilter"
class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="postOnly" value="false" />
<beans:property name="authenticationSuccessHandler" ref="customSuccessHandler" />
</beans:bean>
<beans:bean id="customSuccessHandler" class="org.arpit.java2blog.controller.CustomSuccessHandler" />
<beans:bean id="customAuthenticationProvider" class="org.arpit.java2blog.controller.CustomAuthenticationProvider" />
</beans:beans>
Class files
package org.arpit.java2blog.controller;
import java.util.Collections;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
String username = auth.getName();
String password = auth.getCredentials()
.toString();
System.out.println(username +"::"+password);
if ("user".equals(username) && "pass".equals(password)) {
return new UsernamePasswordAuthenticationToken
(username, password, Collections.emptyList());
} else {
throw new
BadCredentialsException("External system authentication failed");
}
}
#Override
public boolean supports(Class<?> auth) {
return auth.equals(UsernamePasswordAuthenticationToken.class);
}
}
package org.arpit.java2blog.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
#Component
public class CustomEntryPoint implements AuthenticationEntryPoint
{
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException
{
System.out.println("Entering commence due to failed Authentication");
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized Access!" );
}
}
package org.arpit.java2blog.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
public class CustomSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler
{
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException
{
System.out.println("authentication successful!");
}
}
Looks like you are braking filter chain with that customEntryPoint because it is run before any authentification and since it sends response.sendError, chain if broken. So, remove that entry point bean.
You can register custom success and failure handlers by adding this inside sec:http secition:
<sec:form-login
authentication-failure-handler-ref="authenticationFailedHandler"
authentication-success-handler-ref="authenticationSuccessHandler" />
where success handler is:
#Component
public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// success
}
}
and failed handler:
#Component
public class AuthenticationFailedHandler extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// super.onAuthenticationFailure(request, response, exception);
// failed
}
}
Hope it helps.

"An Authentication object was not found in the SecurityContext" while using #secured method

I'm new in java development and I am trying to implement spring security on method level using #secured annotation.
When i call my "/login" I'm getting the following error:
"An Authentication object was not found in the SecurityContext"
PS:I am not using a .jsp file for login , any idea how to manage this error?
this is my code sections.
#Controller
#RequestMapping("/login")
public class LoginController {
#Autowired
public IUserService userService;
#RequestMapping(method = RequestMethod.GET)
public String success(ModelMap map) {
userService.addUser("ram", "con1234");
userService.deleteUser("ABC");
map.addAttribute("msg", "Done Successfully");
return "success";
}
}
public interface IUserService {
#Secured ({"ROLE_USER", "ROLE_ADMIN"})
public void addUser(String name, String pwd);
#Secured("ROLE_ADMIN")
public void deleteUser(String name);
}
#Repository
public class UserServiceSec implements IUserService {
#Override
public void addUser(String name, String pwd) {
System.out.println("user added");
}
#Override
public void deleteUser(String name) {
System.out.println("user deleted");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>EQUADIS</display-name>
<welcome-file-list>
<welcome-file>/login</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet- class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml
/WEB-INF/security-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
security-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<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- 3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http auto-config="true">
<intercept-url pattern="/login" access="ROLE_USER,ROLE_ADMIN" />
<logout logout-success-url="/login" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="ram" password="con1234" authorities="ROLE_ADMIN" />
<user name="rahim" password="con1234" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
<global-method-security secured-annotations="enabled" />
<beans:bean name="userServiceSec" class="package.service.UserServiceSec"/>
You don't seem to have a DelegatingFilterProxy filter in your web.xml. You need to have the following;
<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>

Spring security not securing methods

I am trying out Spring security and I annotated some methods of my RestController with #PreAuthorize.
However, I can access all of them without being authenticated.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Security configuration, imported by root-context:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans ...>
<global-method-security pre-post-annotations="enabled" />
<http auto-config="true">
<intercept-url pattern="/service/public/**" />
<intercept-url pattern="/service/user/**" access="ROLE_USER,ROLE_ADMIN" />
<intercept-url pattern="/service/admin/**" access="ROLE_ADMIN" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider> <user-service> <user name="admin" password="admin"
authorities="ROLE_ADMIN" /> <user name="user" password="user" authorities="ROLE_USER"
/> </user-service> </authentication-provider>
</authentication-manager>
</beans:beans>
My service:
#RestController
#RequestMapping("/service")
public class Service {
#RequestMapping(value = "/public/{name}", method = RequestMethod.GET)
public String storeEntityPublic(#PathVariable String name) {
String result = "Hello " + name + ", I am saving on the db. (PUBLIC)";
return result;
}
#PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
#RequestMapping(value = "/user/{name}", method = RequestMethod.GET)
public String storeEntityUserOrAdmin(#PathVariable String name) {
String result = "Hello " + name
+ ", I am saving on the db. (USER OR ADMIN)";
return result;
}
#PreAuthorize("hasRole('ROLE_ADMIN')")
#RequestMapping(value = "/admin/{name}", method = RequestMethod.GET)
public String storeEntityAdmin(#PathVariable String name) {
String result = "Hello Admin " + name
+ ", I am saving on the db. (ADMIN ONLY)";
return result;
}
}
What's wrong with it?

Why can't spring security get a username?

I am using spring security, and I can't seem to see if a user has successfully logged in to save my life and then get the actual user name. The 'spring' (SecurityContextHolder) and 'J2EE' (request.getUserPrincipal()) way both return nulls.
My web.xml
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.company.security.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
....
<servlet>
<servlet-name>agent-desktop</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>agent-desktop</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring config:
<mvc:resources mapping="/r/**" location="/resources/" />
Spring security config:
<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.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http auto-config="true">
<intercept-url pattern="/agent/**" access="ROLE_USER" />
<intercept-url pattern="/supervisor/**" access="ROLE_USER" />
<form-login login-page="/r/views/login.html" default-target-url="/dashboard" authentication-failure-url="/r/views/loginfailed.html" />
<logout logout-success-url="/logout" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="pw123" authorities="ROLE_USER, ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Here is my filter code:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth != null)
{
String name = auth.getName(); //get logged in username
System.out.println("name:"+name);
User user = (User)auth.getPrincipal();
if(user != null)
System.out.println("user:"+user.getUsername());
}
if(req.getUserPrincipal() != null) // someone has logged in - IT IS ALWAYS NULL
{
/// IT NEVER GETS IN HERE!!!!!!!!!!
I suspect you have missed out including a filter in your web.xml. You might want to read up on how to configure spring security from here
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
Use this code in web.xml instead of the filter.
<!-- 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>
To get the login user details have a separate class like this
public class AccountUtils {
public static Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
public static UserAccount getLoginUserAccount() {
if (getAuthentication() != null && getAuthentication().getPrincipal() instanceof UserAccount) {
return (UserAccount)getAuthentication().getPrincipal();
}
return null;
}
public static String getLoginUserId() {
UserAccount account = getLoginUserAccount();
return (account == null) ? null : account.getUserId();
}
private AccountUtils() {}
}

Web Application based on Spring Security crashes during startup (NullPointerException)

My application, which make use of Spring Security, is crashing during the startup. Tracking the execution of the application, I could verify the error is happening in method onStartup from class MainWebAppInitializer:
public class MainWebAppInitializer implements WebApplicationInitializer {
/**
* Register and configure all Servlet container components necessary to power the web application.
*/
#Override
public void onStartup(final ServletContext sc) throws ServletException {
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan("com.spring.web.config");
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
// Handles requests into the application
final ServletRegistration.Dynamic appServlet = sc.addServlet("horariolivreapp", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
}
More specificly, the error occurs in the line
appServlet.setLoadOnStartup(1)
where a NullPointerException is triggered. Follow it is my configuration files, for reference:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>HorarioLivre</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>horariolivreapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>horariolivreapp</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.spring.web.config</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 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>
horariolivreap-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.horariolivreapp.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
webSecurityConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<http use-expressions="true">
<intercept-url pattern="/login*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login
login-page='/form_login.html'
login-processing-url="/usuario_login.html"
default-target-url="/usuario_start.html"
authentication-failure-url="/form_login"
always-use-default-target="true"/>
<logout logout-success-url="/login.html" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Looking in this files, someone can find the reason for this problem?
UPDATE 1
This is my Controller (DispatcherServlet) class:
package com.horariolivreapp.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Controller;
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.horariolivreapp.core.Sessao;
import com.horariolivreapp.data.UsuarioDAO;
#Controller
public class HorarioLivreController {
private Sessao sessao;
#RequestMapping("/cadastra_evento")
public ModelAndView cadastra_evento() {
return null;
}
#RequestMapping(value="/listagem_evento", method=RequestMethod.GET)
public ModelAndView listagem_evento() {
return null;
}
#RequestMapping("/cadastra_horario")
public ModelAndView cadastra_horario() {
return null;
}
#RequestMapping("/listagem_horario")
public ModelAndView listagem_horario() {
return null;
}
#RequestMapping("/cadastra_usuario")
public ModelAndView cadastra_usuario() {
return null;
}
#RequestMapping("/listagem_usuario")
public ModelAndView listagem_usuario() {
return null;
}
#RequestMapping("/cadastra_tipo")
public ModelAndView cadastra_tipo() {
return null;
}
#RequestMapping("/cadastra_campo")
public ModelAndView cadastra_campo() {
return null;
}
#RequestMapping("/cadastra_autorizacao")
public ModelAndView cadastra_autorizacao() {
return null;
}
#RequestMapping("/usuario_perfil")
public ModelAndView usuario_perfil() {
return null;
}
#RequestMapping("/usuario_config")
public ModelAndView usuario_config() {
return null;
}
#RequestMapping(value="/usuario_login", method=RequestMethod.POST)
public ModelAndView usuario_login(#RequestParam("j_username") String username, #RequestParam("j_password") String password) {
UsuarioDAO usuario = new UsuarioDAO(username, password);
if(usuario.getUsuario() != null) {
this.sessao = new Sessao(usuario.getUsuario());
}
return new ModelAndView("usuario_start","usuario",usuario.getUsuario());
}
#Configuration
#ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}
}
An NPE at that point means that appServlet is null, which in turn means that sc.addServlet(...) returned null.
The Javadoc for addServlet says this:
"Returns: a ServletRegistration object that may be used to further configure the given servlet, or null if this ServletContext already contains a complete ServletRegistration for a servlet with the given servletName or if the same servlet instance has already been registered with this or another ServletContext in the same container."
Now you are instantiating the Servlet object at that point, so it cannot have previously been registered. But there could be another Servlet with the same name ... and that's the probable immediate cause of the problem.
And in fact, it looks like you have already registered a servlet called "horariolivreapp" by declaring it in the web.xml file.

Categories