spring security in rest Web service - java

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.

Related

WARNING: No mapping found for HTTP request with URI [/SpringLoginApplication/] in DispatcherServlet with name 'SpringLoginApplication'

My project is a maven project when i run the project on tomcat it shows
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringLoginApplication/] in DispatcherServlet with name 'SpringLoginApplication'
I tried all possibilities to resolve but all in vein, can somebody help me out to resolve this issue
my controller :
package com.spring.login.controller;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.spring.login.beans.Customer;
import com.spring.login.services.CustomerService;
import com.spring.login.validation.CustomerValidation;
#Controller
public class CustomerController {
#Autowired
private CustomerService customerService;
#RequestMapping(value="/" , method=RequestMethod.GET)
public String login(ModelMap model){
//model.put("Info", new Customer());
return "/login";
}
#RequestMapping(value="/register", method = RequestMethod.GET)
public String showForm(ModelMap model){
model.put("customerData", new Customer());
return "/register";
}
#RequestMapping(value= "/register", method= RequestMethod.POST)
public String saveForm(ModelMap model, #ModelAttribute("customerData") #Valid Customer customer, BindingResult br, HttpSession session){
CustomerValidation customerValidation = new CustomerValidation();
customerValidation.validate(customerValidation, br);
if(br.hasErrors()){
return "/register";
}
else{
customerService.saveCustomer(customer);
session.setAttribute("customer", customer);
return "redirect:success";
}
}
#RequestMapping(value="/logout", method = RequestMethod.GET)
public String logOut(ModelMap model, HttpSession session){
session.removeAttribute("customer");
return "redirect:login";
}
#RequestMapping(value="/success", method = RequestMethod.GET)
public String logOut(ModelMap model){
model.put("customer", new Customer());
return "redirect:success";
}
}
my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd" >
<display-name>SpringLoginApplication</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringLoginApplication</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/SpringLoginApplication-servlet.xml
</param-value>
</init-param>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringLoginApplication</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
my SpringLoginApplication-servlet.xml :
<?xml version="1.0" encoding="UTF-8"?>
<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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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.spring.login.controller" />
<context:component-scan base-package="com.spring.login.dao" />
<context:component-scan base-package="com.spring.login.beans" />
<context:component-scan base-package="com.spring.login.services" />
<context:component-scan base-package="com.spring.login.validation" />
<mvc:annotation-driven />
<context:annotation-config />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="com.spring.login.beans.Customer" init-method="getC_id" destroy-
method="getC_name">
<property name="c_id" value="1234"/>
<property name="c_name" value="Sanjay"/>
</bean>
</beans>
A working response would be highly appreciated!
ANY OTHER INFO REQUIRED, PLS LET ME KNOW
I had the same problem few days before, and I got bellow solution.
#Controller
#RequestMapping(value="/" )
public class CustomerController {
//do your stuff here
#RequestMapping(method=RequestMethod.GET)
public String login(ModelMap model){
//model.put("Info", new Customer());
return "/login";
}
//Rest of your stuff goes here
}
Since you have configured your Dispatcher servlet to handle your context in stead of all possibility which people generally do by adding this (/*), so above provided code snippet will work and redirect your context to /login which you want(if i'm not wrong). Cheers!!!!

Security Spring - Found 302

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;
}
}

Facing problems with XML configuration of Spring Security

I was trying to convert the following spring security java configuration to xml configuration;
Java config;
package com.careapple.webservice.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.careapple.webservice.security.filter.AuthenticationTokenFilter;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableTransactionManagement
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
#Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public AuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
AuthenticationTokenFilter authenticationTokenFilter = new AuthenticationTokenFilter();
authenticationTokenFilter.setAuthenticationManager(super.authenticationManagerBean());
return authenticationTokenFilter;
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated();
// Custom JWT based authentication
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
}
Converted xml configuration; spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<bean:beans
xmlns:bean="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xmlns="http://www.springframework.org/schema/security"
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-4.0.xsd">
<global-method-security secured-annotations="enabled"/>
<http realm="Protected API"
create-session="stateless"
entry-point-ref="authenticationEntryPoint"
authentication-manager-ref="authenticationManager">
<csrf disabled="true"/>
<custom-filter ref="authenticationTokenFilter" position="FORM_LOGIN_FILTER"/>
<intercept-url pattern="/login/**" access="permitAll"/>
<intercept-url pattern="/" access="isFullyAuthenticated()"/>
</http>
<bean:bean id="authenticationEntryPoint" class="com.careapple.webservice.security.EntryPointUnauthorizedHandler"/>
<bean:bean id="userDetailService" class="com.careapple.webservice.security.service.UserDetailsServiceImpl"/>
<bean:bean name="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
<authentication-manager id="authenticationManager">
<authentication-provider user-service-ref="userDetailService">
<password-encoder ref="bcryptEncoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<bean:bean id="authenticationTokenFilter" class="com.careapple.webservice.security.filter.AuthenticationTokenFilter"
c:authenticationManager-ref="authenticationManager"/>
</bean:beans>
I'm new to spring security, first thing i want is, have i converted the java config to xml correctly. Or have i missed anything.
Next up, if i run the application with this xml file i'm getting the following error;
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'authenticationTokenFilter' while setting constructor argument with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationTokenFilter' defined in ServletContext resource [/WEB-INF/spring-security.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
Where, authenticationTokenFilter is a custom filter that i'm using and it implements UsernamePasswordAuthenticationFilter of spring.
This is my web.xml file;
<?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"
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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>authenticationTokenFilter</filter-name>
<filter-class>com.careapple.webservice.security.filter.AuthenticationTokenFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>authenticationTokenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
I want too things now,
1. Whether all my configuration xml files are correct.
2. If so how to rectify the exception i'm getting.
Please give your suggestions, i'm struggling with this for a long time. I referred all the related stackoverflow question but i was not able to find a solution from them.
Edit:
This is my AuthenticationTokenFilter;
package com.careapple.webservice.security.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.careapple.webservice.security.TokenUtils;
import com.careapple.webservice.util.AppConstant;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class AuthenticationTokenFilter extends UsernamePasswordAuthenticationFilter {
#Autowired
private TokenUtils tokenUtils;
#Autowired
private UserDetailsService userDetailsService;
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException{
tokenUtils = WebApplicationContextUtils
.getRequiredWebApplicationContext(this.getServletContext())
.getBean(TokenUtils.class);
userDetailsService = WebApplicationContextUtils
.getRequiredWebApplicationContext(this.getServletContext())
.getBean(UserDetailsService.class);
HttpServletResponse resp = (HttpServletResponse) response;
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
resp.setHeader("Access-Control-Max-Age", "3600");
resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, " + AppConstant.tokenHeader);
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authToken = httpRequest.getHeader(AppConstant.tokenHeader);
System.out.println("Token: " + authToken);
String username = this.tokenUtils.getUsernameFromToken(authToken);
System.out.println("Username: " + username);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
System.out.println("inside first if");
if (this.tokenUtils.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
try {
chain.doFilter(request, response);
} catch (Exception e) {
Map<String, String> tokenExpired = new HashMap<>();
tokenExpired.put("TokenExpired", "Authentication token expired, please login again");
resp.setContentType("application/json");
resp.setStatus(HttpStatus.FORBIDDEN.value());
resp.getWriter().write(convertObjectToJson(tokenExpired));
}
}
public String convertObjectToJson(Object object) throws JsonProcessingException {
if (object == null) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
}
Your custom authentification filter needs to be defined only on the spring-security.xml file, looking at it, it should be fine.
On your web.xml, you need to remove your filter (it's a Spring Security filter not a JavaEE filter) and add the spring security filter. The error message from Spring is that it cannot find the Spring Security filter and thus refusing the parse the pring-security.xml file.
So remove your filter from web.xml and add the spring security with these lines and all should be fine
<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>
Regards,
Loïc

Error HTTP Status 500 - No WebApplicationContext found: no ContextLoaderListener registered?

Hi I am new to Spring Security and Spring Oauth, i am configuring a Spring Oauth Server and Resource Server java based. but i need to configure some of the web mvc based on xml, like need to initialize servlet parameters.
below is my 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>Spring Web MVC Application</display-name>
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</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>
<init-param>
<param-name>contextAttribute</param-name>
<param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
and mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.resource" />
<mvc:annotation-driven />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/userbase" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
</beans>
and Error log is below:
HTTP Status 500 - No WebApplicationContext found: no ContextLoaderListener registered?
type Exception report
message No WebApplicationContext found: no ContextLoaderListener registered?
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:252)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.68 logs.
Apache Tomcat/7.0.68
SecurityConfiguration.java
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder)
.usersByUsernameQuery(
"select username,password, enabled from users where username=?")
.authoritiesByUsernameQuery(
"select username, authority from authorities where username=?");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
****OAuth2ServerConfig.java****
import java.security.Principal;
import java.util.UUID;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.web.bind.annotation.RequestMapping;
#Configuration
public class OAuth2ServerConfig {
#Configuration
#EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
#Autowired
private DataSource dataSource;
public static final String RESOURCE_ID = "resource_id";
#Bean
public JdbcTokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
#Bean
protected AuthorizationCodeServices authorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource);
}
#Override
public void configure(ResourceServerSecurityConfigurer resources)
throws Exception {
resources.tokenStore(tokenStore());
resources.resourceId(RESOURCE_ID);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
}
}
#RequestMapping("/")
public String getInfo() {
return "id: " + UUID.randomUUID() + " content : Spring Oauth2 Welcome first Page";
}
#RequestMapping("/user")
public Principal getUser(Principal principal) {
return principal;
}
}
Please help me on above.
It looks like contextAttribute suffix of the springSecurityFilterChain must match the dispatcher servlet name. Here in your case i see the contextAttribute suffix is dispatcher but the dispatcher servlet name is mvc-dispatcher. Can you try matching them i.e change the contextAttibute suffix to mvc-dispatcher as below and see if the issue goes away.
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>contextAttribute</param-name>
<param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.mvc-dispatcher</param-value>
</init-param>
</filter>
I got this info from https://www.txedo.com/blog/spring-security-no-contextloaderlistener-registered/

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