JAVA SPRING SECURITY+HIBERNATE

mary87

Nuovo Utente
2
0
Buon pomeriggio,
sono una studentessa di informatica e sto cercando di imparare Spring Security per un piccolo sistema di login.
Purtroppo ho un problema che non riesco a risolvere.

all'interno del mio progetto ho due classi SpringSecurityContext e UserSession che vengono utilizzate dalle classi LoginService e LoginController per effettuare tutte le operazioni di login.

la classe SpringSecurity è:

Codice:
[/FONT][/COLOR][COLOR=#000000][FONT=Courier New]public class SpringSecurityContext[/FONT][/COLOR]

{    public static UserSession getUser(final HttpSession httpSession)    {        SecurityContext securityContext = (SecurityContext) httpSession.getAttribute("SPRING_SECURITY_CONTEXT");        if (securityContext != null)        {            return (UserSession) securityContext.getAuthentication().getPrincipal();        }        else        {            securityContext = SecurityContextHolder.getContext();[COLOR=#ff0000]            return (UserSession)securityContext.getAuthentication().getPrincipal();[/COLOR]        }    }    public static void removeUser(final HttpSession httpSession)    {        final SecurityContext securityContext = (SecurityContext) httpSession.getAttribute("SPRING_SECURITY_CONTEXT");        if (securityContext != null)        {            securityContext.setAuthentication(null);        }        else        {            SecurityContextHolder.getContext().setAuthentication(null);        }    }    public static void setDefaultUser(final HttpSession httpSession)    {        final UserSession userSession = new UserSession();        final UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken(userSession,                userSession.getPassword());        SecurityContext securityContext = (SecurityContext) httpSession.getAttribute("SPRING_SECURITY_CONTEXT");        if (securityContext != null)        {            securityContext.setAuthentication(authenticate);        }        else        {            securityContext = SecurityContextHolder.getContext();            securityContext.setAuthentication(authenticate);            httpSession.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);        }    }    public static void setUser(final HttpSession httpSession, final User user)    {        final UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken(user, user.getPassword());        SecurityContext securityContext = (SecurityContext) httpSession.getAttribute("SPRING_SECURITY_CONTEXT");        if (securityContext != null)        {            securityContext.setAuthentication(authenticate);        }        else        {            securityContext = SecurityContextHolder.getContext();            securityContext.setAuthentication(authenticate);            httpSession.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);        }    } [COLOR=#000000][FONT=Courier New]}
[/FONT][/COLOR][COLOR=#000000][FONT=Verdana]


la classe User Session è:

Codice:
[/FONT][/COLOR]

public class UserSession extends User implements Serializable {	private static final long serialVersionUID = 1L;		/**    	 * campi di User	 * 	 * l'username dell’utente	 * la sua password	 * (booleano) utente abilitato	 * (booleano) account non scaduto	 *  (booleano) credenziali non scadute	 *  (booleano) account non bloccato	 *   Lista di permessi di tipi GrantedAuthorities   	 */		public static enum Stato {VISITATORE, REGISTRATO, CONFERMATO, LOGGED};	public static enum Errors {ERROR_USER_PASSWORD, ERROR_INVALID_STATE, ERROR_EXIST_MAIL};	private boolean complete;	private Stato stato;	private String nome;	private Errors error;	private Long id;		public UserSession()	{		super("username", "password", false, false, false, false, new HashSet<GrantedAuthority>());				stato = Stato.VISITATORE;	}	public UserSession(String username, String password, boolean enabled,			boolean accountNonExpired, boolean credentialsNonExpired,			boolean accountNonLocked, Collection<GrantedAuthority> authorities) 	{		super(username, password, enabled, accountNonExpired, credentialsNonExpired,				accountNonLocked, authorities);		// TODO Auto-generated constructor stub	}	public UserSession(String username, String password, boolean enabled,			boolean accountNonExpired, boolean credentialsNonExpired,			boolean accountNonLocked, Collection<GrantedAuthority> authorities,			String nome, Errors error, Long id) 	{		super(username, password, enabled, accountNonExpired, credentialsNonExpired,				accountNonLocked, authorities);		this.stato = stato;		this.nome = nome;		this.error = error;		this.id = id;	}	public Stato getStato() {		return stato;	}	public void setStato(Stato stato) {		this.stato = stato;	}		public String getNome() {		return nome;	}	public void setNome(String nome) {		this.nome = nome;	}	public Errors getError() {		return error;	}	public void setError(Errors error) {		this.error = error;	}	public Long getId() {		return id;	}	public void setId(Long id) {		this.id = id;	}	public boolean isComplete() {		return complete;	}	public void setComplete(boolean complete) {		this.complete = complete;	}	 
[COLOR=#000000][FONT=Courier New]}
[/FONT][/COLOR][COLOR=#000000][FONT=Verdana]


l'errore all'esecuzione è:

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/UtenteVoli] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: java.lang.String cannot be cast to esempio.service.UserSession] with root cause
java.lang.ClassCastException: java.lang.String cannot be cast to esempio.service.UserSession
at esempio.service.SpringSecurityContext.getUser(SpringSecurityContext.java:26)
at esempio.service.LoginService.service(LoginService.java:18)
at esempio.web.LoginController.login(LoginController.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

Qualcuno può essermi di aiuto?????...
in pratica mi dice che il cast (UserSession)securityContext.getAuthentication().getPrincipal();
non può essere fatto...
ma perchè???
come posso risolere???

vi ringrazio in anticipo!!!!


- - - Updated - - -

per puntualizzare,
la funzione GetPrincipal()
restituisce un Object
e poi faccio il cast a UserSession
come si può vedere nell'immagine GetPrincipal.png
 

1nd33d

Utente Attivo
653
279
CPU
Intel i5 3570K @ 4,5Ghz
Dissipatore
Scythe Mugen 2
Scheda Madre
Gigabyte Z77X-UD3H
HDD
Samsung 840 PRO 256GB + Sandisk Ultra 250GB + Sandisk Plus 960GB
RAM
2x8GB Crucial Ballistix Tactical @2000Mhz CL9
GPU
XFX RX480 GTR Black Edition
Audio
Auzentech X-Fi Forte
Monitor
AOC i2369VW
PSU
Seasonic P660
Case
eh?
Periferiche
Razer Naga HEX v2
OS
Windows 10 64bit - Linux Mint 18
L'errore è molto esplicito: c'è un errore di cast, probabilmente getPrincipal non ritorna un oggetto di tipo String, non puoi forzare un cast a una classe a piacere se l'oggetto non è della stessa classe o di classe derivata.
Prova a stampare a console l'oggetto, dall'output potresti capire che tipo di oggetto è.
 

Ci sono discussioni simili a riguardo, dai un'occhiata!

Entra

oppure Accedi utilizzando

Hot: E3 2021, chi ti è piaciuto di più?

  • Ubisoft

    Voti: 4 17.4%
  • Gearbox

    Voti: 0 0.0%
  • Xbox & Bethesda

    Voti: 19 82.6%
  • Square Enix

    Voti: 0 0.0%
  • Capcom

    Voti: 0 0.0%
  • Nintendo

    Voti: 3 13.0%
  • Altro (Specificare)

    Voti: 0 0.0%

Discussioni Simili