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?
Related
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>
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;
}
}
while processing injection of spring security to my web app i get problem HTTP Status 404 error. When i try to get access for my pages first of all i get login page which is auto config, after typing login and password which is correct i get HTTP Status 404 error. Code below
web.xml
<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_2_5.xsd"
id="WebApp_ID" version="2.5">
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml, /WEB-INF/application-security.xml</param-value>
</context-param>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
application-security.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-4.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/main/**" access="hasRole('ROLE_USER')" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="adminpassword" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="user" password="userpassword" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Controller
#Controller
#RequestMapping(value = "/main")
public class MainController {
#Autowired
DeputesAppealService deputesAppealService;
#Autowired
DeputesAppealDao deputesAppealDao;
#RequestMapping(value = "/mainFrame", method = RequestMethod.GET)
public String getMainPage(){
return "mainPage";
}
#RequestMapping(value = "/resultOfSearching", method = RequestMethod.GET)
public String getSearchResult(Model model, #ModelAttribute("searchChar")String searchResult) {
List<DeputesAppeal> deputesAppeals = deputesAppealService.abstractSearch(searchResult);
model.addAttribute("ListOfAppeals", deputesAppeals);
return "searchingResultPage";
}
#RequestMapping(value = "/new", method = RequestMethod.GET)
public String getAddNewAppealPage(){
return "addPage";
}
#RequestMapping(value = "/new", method = RequestMethod.POST)
public String addNewAppeal(#ModelAttribute("Appeal")DeputesAppeal deputesAppeal) {
deputesAppealService.add(deputesAppeal);
return "mainPage";
}
#RequestMapping(value = "/deleted", method = RequestMethod.GET)
public String deleteAppeal(#RequestParam(value = "id", required = true) Long id, Model model){
deputesAppealService.delete(id);
model.addAttribute("id", id);
return "deletedPage";
}
#RequestMapping(value = "/editPage", method = RequestMethod.GET)
public String GetEdit(#RequestParam(value = "id", required = true) Long id, Model model){
model.addAttribute("editedAppeal", deputesAppealService.getById(id));
return "editPage";
}
#RequestMapping(value = "/editPage", method = RequestMethod.POST)
public String editCurrentAppeal(#ModelAttribute("userAttribute") DeputesAppeal deputesAppeal,
#RequestParam(value = "id", required = true)Integer id, Model model) {
deputesAppeal.setNumber(id);
deputesAppealService.edit(deputesAppeal);
model.addAttribute("id", id);
return "editedPage";
}
}
Just see if you have springSecurityFilterChain defined in your web.xml
<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>
You also need to change Login URL as well
<c:url value="/j_spring_security_check" var="loginUrl" />
and use this in your form action:
<form action="${loginUrl}" method="post">
I have a problem with my proyect, I've tried to configure Spring Security 4 with Spring REST, but there is a problem when I try to access with any context.
Here is my project structure:
Inside of "views" are my html pages.
And here is my spring configuration.
<import resource="classpath:applicationContext-business.xml"/>
<mvc:annotation-driven />
<security:http auto-config="true" >
<security:intercept-url pattern="/" access="permitAll" />
<security:intercept-url pattern="/home" access="permitAll" />
<security:form-login login-page="/iniciar_sesion"
username-parameter="email"
password-parameter="password"
authentication-failure-url="/Access_Denied" />
<security:csrf/>
</security:http>
<context:component-scan base-package="turing.solutions.dy.web" >
<context:include-filter type="regex" expression=".*\.(.)*"/>
<context:exclude-filter type="regex" expression="security"/>
</context:component-scan>
<bean id="customUserDetailsService" class="turing.solutions.dy.web.security.CustomUserDetailService" />
<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService"/>
</security:authentication-manager>
And my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dy</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dy</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>
<session-config>
<session-timeout>
10
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
And this is my RestController:
#RestController
public class LoginController {
#RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String homePage() {
System.out.println("Redirect");
return "index";
}
#RequestMapping(value="iniciar_sesion",method = RequestMethod.GET)
public String iniciarSession(ModelMap model){
model.put("login", "log");
return "iniciar_sesion";
}
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
public Map<String, Object> login() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("login", "ok");
return map;
}
#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;
}
}
Ant this is my CustomUserDetailService
#Service("customUserDetailService")
public class CustomUserDetailService implements UserDetailsService {
#Autowired
private UsuariosService usuariosService;
#Override
public UserDetails loadUserByUsername(String correo) throws UsernameNotFoundException {
Usuarios usuario = this.usuariosService.findByCorreo(correo);
if (usuario == null) {
throw new UsernameNotFoundException("El usuairo " + correo + " no existe, favor de verificar");
}
return new User(usuario.getEmail(), usuario.getPassword(), usuario.getActivo(), true, true, true, getGrantedAuthorities(usuario));
}
private List<GrantedAuthority> getGrantedAuthorities(Usuarios usuario) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Roles rol : usuario.getRolesList()) {
System.out.println("Usuario " + usuario.getEmail() + " ROl" + rol.getDescRol().toUpperCase());
authorities.add(new SimpleGrantedAuthority("ROLE_" + rol.getDescRol().toUpperCase()));
}
return authorities;
}
}
When I try to access to the URL "http://localhost:9080/DespreocupateYA/home" I see this
But I should see this
So,my question is: Why i can't see the html pages in my project? I've searched and I found many Spring configurations, but I've not been able to solve the problem.
My Server is an Apache Tomcat 8.0.28.
I hope you can help me, Thanks.
Change your #RestController annotation to #Controller and it will work properly.
Here are docs explaining the difference between this two annotations
Morover when you say RestController you mean a Controller wich handle some data like JSON objects. Here you need a simple Controller to handle html views.
EDIT
You didn't mention what kind of view rendering engine you are using, this is example configuration for jsp
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
And this to your spring conifguration file, make sure you declare "http://www.springframework.org/schema/beans" name space so you can use bean definition
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() {}
}