After upgrading my Jhipster application from 4.01 version to 4.10 the logout functionality is not working properly. When clicking on logout option the page doesn't get redirected to the home screen.
Not sure using CsrfFilter is causing this issue.
Error coming in logs and user is not redirected from dashboard to home screen after logout. Second logout click works.
I am seeing the following exception in the logs
Java logs
~~~
2017-11-02 10:08:33.023 DEBUG 2192 --- [ XNIO-7 task-21] com.hclue.aop.logging.LoggingAspect : Enter: com.hclue.web.rest.AccountResource.getAccount() with argument[s] = []
2017-11-02 10:08:33.036 DEBUG 2192 --- [ XNIO-7 task-20] c.h.s.PersistentTokenRememberMeServices : Cancelling cookie
2017-11-02 10:08:33.038 DEBUG 2192 --- [ XNIO-7 task-21] com.hclue.aop.logging.LoggingAspect : Enter: com.hclue.service.UserService.getUserWithAuthorities() with argument[s] = []
2017-11-02 10:08:33.051 DEBUG 2192 --- [ XNIO-7 task-21] com.hclue.aop.logging.LoggingAspect : Exit: com.hclue.service.UserService.getUserWithAuthorities() with result = User{login='pankajppr', firstName='Pankaj', lastName='Jaiswal', email='[email protected]', imageUrl='null', activated='true', langKey='en', activationKey='null'}
2017-11-02 10:08:33.052 DEBUG 2192 --- [ XNIO-7 task-21] com.hclue.aop.logging.LoggingAspect : Exit: com.hclue.web.rest.AccountResource.getAccount() with result = <200 OK,UserDTO{login='pankajppr', firstName='Pankaj', lastName='Jaiswal', email='[email protected]', imageUrl='null', activated=true, langKey='en', createdBy=admin, createdDate=2017-10-30T04:52:23Z, lastModifiedBy='system', lastModifiedDate=2017-11-02T04:03:55Z, authorities=[ROLE_USER]},{}>
2017-11-02 10:08:33.066 DEBUG 2192 --- [ XNIO-7 task-22] com.hclue.aop.logging.LoggingAspect : Enter: org.springframework.boot.actuate.audit.AuditEventRepository.add() with argument[s] = [AuditEvent [timestamp=Thu Nov 02 10:08:33 IST 2017, principal=anonymousUser, type=AUTHORIZATION_FAILURE, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null, type=org.springframework.security.access.AccessDeniedException, message=Access is denied}]]
2017-11-02 10:08:33.071 DEBUG 2192 --- [ XNIO-7 task-23] com.hclue.aop.logging.LoggingAspect : Enter: com.hclue.web.rest.ProfileInfoResource.getActiveProfiles() with argument[s] = []
2017-11-02 10:08:33.077 DEBUG 2192 --- [ XNIO-7 task-22] com.hclue.aop.logging.LoggingAspect : Exit: org.springframework.boot.actuate.audit.AuditEventRepository.add() with result = null
2017-11-02 10:08:33.077 DEBUG 2192 --- [ XNIO-7 task-23] com.hclue.aop.logging.LoggingAspect : Exit: com.hclue.web.rest.ProfileInfoResource.getActiveProfiles() with result = com.hclue.web.rest.ProfileInfoResource$ProfileInfoVM@43474e31
2017-11-02 10:08:33.079 WARN 2192 --- [ XNIO-7 task-22] o.z.p.spring.web.advice.AdviceTrait : Unauthorized: Full authentication is required to access this resource
2017-11-02 10:08:33.080 WARN 2192 --- [ XNIO-7 task-22] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.security.authentication.InsufficientAuthenticationException: Full authentication is required to access this resource
2017-11-02 10:08:33.140 ERROR 2192 --- [ XNIO-7 I/O-4] o.s.w.s.m.StompSubProtocolHandler : Failed to send client message to application via MessageChannel in session o2bkzkaq. Sending STOMP ERROR to client.
org.springframework.messaging.MessageDeliveryException: Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is org.springframework.security.web.csrf.InvalidCsrfTokenException: Invalid CSRF Token 'undefined' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:127)
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:104)
at org.springframework.web.socket.messaging.StompSubProtocolHandler.handleMessageFromClient(StompSubProtocolHandler.java:298)
at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.handleMessage(SubProtocolWebSocketHandler.java:307)
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.handleMessage(WebSocketHandlerDecorator.java:75)
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.handleMessage(LoggingWebSocketHandlerDecorator.java:56)
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.handleMessage(ExceptionWebSocketHandlerDecorator.java:58)
at org.springframework.web.socket.sockjs.transport.session.AbstractSockJsSession.delegateMessages(AbstractSockJsSession.java:380)
at org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession.handleMessage(WebSocketServerSockJsSession.java:193)
at org.springframework.web.socket.sockjs.transport.handler.SockJsWebSocketHandler.handleTextMessage(SockJsWebSocketHandler.java:92)
at org.springframework.web.socket.handler.AbstractWebSocketHandler.handleMessage(AbstractWebSocketHandler.java:43)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.handleTextMessage(StandardWebSocketHandlerAdapter.java:110)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.access$000(StandardWebSocketHandlerAdapter.java:42)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:81)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:78)
at io.undertow.websockets.jsr.FrameHandler$7.run(FrameHandler.java:283)
at io.undertow.websockets.jsr.ServerWebSocketContainer$1.call(ServerWebSocketContainer.java:162)
at io.undertow.websockets.jsr.ServerWebSocketContainer$1.call(ServerWebSocketContainer.java:159)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.websockets.jsr.ServerWebSocketContainer.invokeEndpointMethod(ServerWebSocketContainer.java:575)
at io.undertow.websockets.jsr.ServerWebSocketContainer.invokeEndpointMethod(ServerWebSocketContainer.java:565)
at io.undertow.websockets.jsr.FrameHandler.invokeTextHandler(FrameHandler.java:263)
at io.undertow.websockets.jsr.FrameHandler.onFullTextMessage(FrameHandler.java:314)
at io.undertow.websockets.core.AbstractReceiveListener$2.complete(AbstractReceiveListener.java:156)
at io.undertow.websockets.core.AbstractReceiveListener$2.complete(AbstractReceiveListener.java:152)
at io.undertow.websockets.core.BufferedTextMessage.read(BufferedTextMessage.java:105)
at io.undertow.websockets.core.AbstractReceiveListener.readBufferedText(AbstractReceiveListener.java:152)
at io.undertow.websockets.core.AbstractReceiveListener.bufferFullMessage(AbstractReceiveListener.java:90)
at io.undertow.websockets.jsr.FrameHandler.onText(FrameHandler.java:179)
at io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:44)
at io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:33)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:932)
at io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:913)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66)
at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:88)
at org.xnio.nio.WorkerThread.run(WorkerThread.java:561)
Caused by: org.springframework.security.web.csrf.InvalidCsrfTokenException: Invalid CSRF Token 'undefined' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.
at org.springframework.security.messaging.web.csrf.CsrfChannelInterceptor.preSend(CsrfChannelInterceptor.java:65)
at org.springframework.messaging.support.AbstractMessageChannel$ChannelInterceptorChain.applyPreSend(AbstractMessageChannel.java:158)
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:113)
... 37 common frames omitted
~~~
UI side errror:
~
<<< ERROR
message:Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is org.springframework.security.web.csrf.InvalidCsrfTokenException\c Invalid CSRF Token 'undefined' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.
content-length:0
~
JHipster 4.10.0
$ jhipster info
Using JHipster version installed locally in current project's node_modules
Executing jhipster:info
Options:
Welcome to the JHipster Information Sub-Generator
[email protected] C:\Users\panka\workspace\Hipster\hclueTest2\hclue
+-- [email protected]
+-- [email protected]
| `-- [email protected]
`-- UNMET PEER DEPENDENCY popper.js@^1.11.0
##### **JHipster configuration, a `.yo-rc.json` file generated in the root folder**
{
"generator-jhipster": {
"jhipsterVersion": "4.10.0",
"baseName": "hclueTest3",
"packageName": "com.hclue",
"packageFolder": "com/hclue",
"serverPort": "8080",
"authenticationType": "session",
"hibernateCache": "ehcache",
"clusteredHttpSession": false,
"websocket": "spring-websocket",
"databaseType": "sql",
"devDatabaseType": "mysql",
"prodDatabaseType": "mysql",
"searchEngine": "elasticsearch",
"messageBroker": false,
"buildTool": "maven",
"enableSocialSignIn": false,
"rememberMeKey": "replaced-by-jhipster-info",
"useSass": false,
"clientPackageManager": "yarn",
"applicationType": "monolith",
"clientFramework": "angularX",
"testFrameworks": [
"gatling"
],
"jhiPrefix": "jhi",
"otherModules": [
{
"name": "generator-jhipster-google-maps",
"version": "0.0.1"
},
{
"name": "generator-jhipster-bootstrap-material-design",
"version": "3.5.1"
}
],
"enableTranslation": false,
"serviceDiscoveryType": false
}
}
entityName.json files generated in the .jhipster directory
JDL entity definitions
entity RegisteredDoctors (registered_doctors) {
firstName String required,
lastName String required,
phoneNumber Integer,
email String required,
zipCode Integer required,
activated Boolean required
}
entity Specializations (specializations) {
specialtyName String
}
relationship OneToOne {
RegisteredDoctors{specialty(specialtyName)} to Specializations
}
dto RegisteredDoctors, Specializations with mapstruct
paginate RegisteredDoctors with infinite-scroll
service RegisteredDoctors, Specializations with serviceImpl
paginate Specializations with pagination
java version "1.8.0_111"
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)
git version 2.10.2.windows.1
node: v6.9.5
npm: 4.2.0
bower: 1.8.0
gulp:
[10:21:14] CLI version 1.2.2
yeoman: 2.0.0
yarn: 0.19.1
Congratulations, JHipster execution is complete!
entityName.json files generated in the .jhipster directory
Windows10
All browser
@jhipster-bot can anybody please suggest a fix for this.
@pankajppr I could not reproduce the issue. I tried:
How did you upgrade your app?
@ruddell
I removed the existing jhipster generator from my pc then downloaded the latest version 4.10.0 and then applied the upgrade steps mentioned on the website. Then override all the files as suggested in the console and then started the application. observed this issue after doing some code changes in other entities. Nothing was changed in the logging module.
Let me know if you want specific files to see the code or config.
Thanks for your help. I am trying my best to figure it out but could not resolve this.
Did you upgrade jhipster in your app project? Because upgrading globally does not upgrade per project., each project has its own copy of the generator in its node_modules folder. Check with jhipster info in your app.
Details about what commands you ran are crucial to understand your issue.
Yes, I did upgrade the project after upgrading the globally.
I used command jhipster in the project root directory and then followed the upgrade instructions for accepting the override of files in the project.
If you use Git can you post the diff after the update? of course remove any sensitive info
@deepu105 which files diff shall I post
security related files
@deepu105 Please find the screenshot of diff in the below attachment for application-dev.yml and securityconfiguration.java



So I'm closing this for lack information, and as I can't reproduce.
I'm having the same issue but for logging in on an app that was working fine before upgrade
```
package org.wwarn.drugquality.config;
import io.github.jhipster.security.AjaxAuthenticationFailureHandler;
import io.github.jhipster.security.AjaxAuthenticationSuccessHandler;
import io.github.jhipster.security.AjaxLogoutSuccessHandler;
import org.wwarn.drugquality.security.*;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.security.*;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CorsFilter;
import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
import javax.annotation.PostConstruct;
@Configuration
@Import(SecurityProblemSupport.class)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final UserDetailsService userDetailsService;
private final JHipsterProperties jHipsterProperties;
private final RememberMeServices rememberMeServices;
private final CorsFilter corsFilter;
private final SecurityProblemSupport problemSupport;
public SecurityConfiguration(AuthenticationManagerBuilder authenticationManagerBuilder, UserDetailsService userDetailsService,
JHipsterProperties jHipsterProperties, RememberMeServices rememberMeServices,CorsFilter corsFilter, SecurityProblemSupport problemSupport) {
this.authenticationManagerBuilder = authenticationManagerBuilder;
this.userDetailsService = userDetailsService;
this.jHipsterProperties = jHipsterProperties;
this.rememberMeServices = rememberMeServices;
this.corsFilter = corsFilter;
this.problemSupport = problemSupport;
}
@PostConstruct
public void init() {
try {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
} catch (Exception e) {
throw new BeanInitializationException("Security configuration failed", e);
}
}
@Bean
public AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler() {
return new AjaxAuthenticationSuccessHandler();
}
@Bean
public AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler() {
return new AjaxAuthenticationFailureHandler();
}
@Bean
public AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler() {
return new AjaxLogoutSuccessHandler();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/bower_components/**")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**")
.antMatchers("/h2-console/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.addFilterBefore(corsFilter, CsrfFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.rememberMe()
.rememberMeServices(rememberMeServices)
.rememberMeParameter("remember-me")
.key(jHipsterProperties.getSecurity().getRememberMe().getKey())
.and()
.formLogin()
.loginProcessingUrl("/api/authentication")
.successHandler(ajaxAuthenticationSuccessHandler())
.failureHandler(ajaxAuthenticationFailureHandler())
.usernameParameter("j_username")
.passwordParameter("j_password")
.permitAll()
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler())
.permitAll()
.and()
.headers()
.frameOptions()
.disable()
.and()
.authorizeRequests()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/account/reset-password/init").permitAll()
.antMatchers("/api/account/reset-password/finish").permitAll()
.antMatchers("/api/profile-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/swagger-resources/configuration/ui").permitAll()
.antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN);
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}
## **app.dev.yml:**
spring:
profiles:
active: dev
include: swagger
devtools:
restart:
enabled: true
livereload:
enabled: false # we use gulp + BrowserSync for livereload
jackson:
serialization.indent_output: true
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://localhost:3306/drugquality?useUnicode=true&characterEncoding=utf8
username: myuser
password: mypass
h2:
console:
enabled: false
jpa:
database-platform: org.hibernate.dialect.MySQLDialect
database: MYSQL
show_sql: false
generate-ddl: true
hibernate:
ddl-auto: update
naming:
physical-strategy: org.wwarn.drugquality.config.HibernateAuditTablesNamingStrategy
properties:
hibernate.id.new_generator_mappings: false
hibernate.cache.use_second_level_cache: true
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: true
hibernate.cache.region.factory_class: org.hibernate.cache.jcache.JCacheRegionFactory
data:
elasticsearch:
cluster-name:
cluster-nodes:
properties:
path:
logs: target/elasticsearch/log
data: target/elasticsearch/data
mail:
host: localhost
port: 25
username:
password:
messages:
cache-seconds: 1
thymeleaf:
cache: false
liquibase:
contexts: dev
#
#
#
server:
port: 8080
#
jhipster:
http:
version: V_1_1 # To use HTTP/2 you will need SSL support (see above the "server.ssl" configuration)
cache: # Cache configuration
ehcache: # Ehcache configuration
time-to-live-seconds: 3600 # By default objects stay 1 hour in the cache
max-entries: 100 # Number of objects in each cache entry
# CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
cors:
allowed-origins: ""
allowed-methods: ""
allowed-headers: "*"
allow-credentials: true
max-age: 1800
security:
remember-me:
# security key (this key should be unique for your application, and kept secret)
key: myKey
mail: # specific JHipster mail property, for standard properties see MailProperties
from: DrugQualityDataManager@localhost
base-url: http://127.0.0.1:8080
metrics: # DropWizard Metrics configuration, used by MetricsConfiguration
jmx.enabled: true
graphite: # Use the "graphite" Maven profile to have the Graphite dependencies
enabled: false
host: localhost
port: 2003
prefix: DrugQualityDataManager
prometheus: # Use the "prometheus" Maven profile to have the Prometheus dependencies
enabled: false
endpoint: /prometheusMetrics
logs: # Reports Dropwizard metrics in the logs
enabled: false
report-frequency: 60 # in seconds
logging:
logstash: # Forward logs to logstash over a socket, used by LoggingConfiguration
enabled: false
host: localhost
port: 5000
queue-size: 512
#
application:
### ## **PS: Can't think of a way to show the actual diff, but here I will paste old version code:**
## **application-dev.yml:**
spring:
devtools:
restart:
enabled: true
livereload:
enabled: false # we use gulp + BrowserSync for livereload
datasource:
url: jdbc:mysql://localhost:3306/drugquality?useUnicode=true&characterEncoding=utf8
name: drugquality
username: myuser
password: mypass
h2:
console:
enabled: false
jpa:
database-platform: org.hibernate.dialect.MySQLDialect
database: MYSQL
show_sql: false
generate-ddl: true
hibernate:
ddl-auto: update
naming-strategy: org.hibernate.cfg.EJB3NamingStrategy
properties:
hibernate.cache.use_second_level_cache: true
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: false
hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
org.hibernate.envers.store_data_at_delete: true
org.hibernate.envers.revision_on_collection_change: false
data:
elasticsearch:
cluster-name: #myCluster
cluster-nodes: #myNode
properties:
#host: app-dev.wwarn
path:
logs: target/elasticsearch/log
data: target/elasticsearch/data
mail:
host: localhost
messages:
cache-seconds: 1
thymeleaf:
cache: false
liquibase:
contexts: dev
server:
port: 8080
jhipster:
cache: # Hibernate 2nd level cache, used by CacheConfiguration
timeToLiveSeconds: 3600
ehcache:
maxBytesLocalHeap: 16M
mail: # specific JHipster mail property, for standard properties see MailProperties
from: DrugQualityDataManager@localhost
metrics: # DropWizard Metrics configuration, used by MetricsConfiguration
jmx.enabled: true
spark:
enabled: false
host: localhost
port: 9999
graphite:
enabled: false
host: localhost
port: 2003
prefix: DrugQualityDataManager
logs: # report metrics in the logs
enabled: false
reportFrequency: 60 # in seconds
logging:
logstash: # Forward logs to logstash over a socket, used by LoggingConfiguration
enabled: false
host: localhost
port: 5000
queueSize: 512
**## SecurityConfiguration:**
```
package org.wwarn.drugquality.config;
import org.wwarn.drugquality.security.*;
import org.wwarn.drugquality.web.filter.CsrfCookieGeneratorFilter;
import org.wwarn.drugquality.config.JHipsterProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.csrf.CsrfFilter;
import javax.inject.Inject;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Inject
private JHipsterProperties jHipsterProperties;
@Inject
private AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler;
@Inject
private AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler;
@Inject
private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
@Inject
private Http401UnauthorizedEntryPoint authenticationEntryPoint;
@Inject
private UserDetailsService userDetailsService;
@Inject
private RememberMeServices rememberMeServices;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/bower_components/**")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**")
.antMatchers("/h2-console/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.and()
.addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler())
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.rememberMe()
.rememberMeServices(rememberMeServices)
.rememberMeParameter("remember-me")
.key(jHipsterProperties.getSecurity().getRememberMe().getKey())
.and()
.formLogin()
.loginProcessingUrl("/api/authentication")
.successHandler(ajaxAuthenticationSuccessHandler)
.failureHandler(ajaxAuthenticationFailureHandler)
.usernameParameter("j_username")
.passwordParameter("j_password")
.permitAll()
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.deleteCookies("JSESSIONID", "CSRF-TOKEN")
.permitAll()
.and()
.headers()
.frameOptions()
.disable()
.and()
.authorizeRequests()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/account/reset_password/init").permitAll()
.antMatchers("/api/account/reset_password/finish").permitAll()
.antMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api/audits/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api/**").authenticated()
.antMatchers("/metrics/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/health/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/dump/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/shutdown/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/beans/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/configprops/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/info/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/autoconfig/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/env/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/mappings/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/liquibase/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/configuration/security").permitAll()
.antMatchers("/configuration/ui").permitAll()
.antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/protected/**").authenticated() ;
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}
@pankajppr @Steven-Garcia it is really difficult to pinpoint the issue as it seems like you guys might have missed something during merge after the upgrade. Try to copy the .yo-rc,json file of your app to a new folder and generate it using JHipster and see if it works (As @jdubois tried it should work) now compare that app with your current failing app and see what are the differences using a tool like Beyond Compare or Git depending on preference. I'm sure you will be able to find the missing piece causing issue
I'm reopening this so I check again
Sorry I still can't reproduce, and that's why I'm closing this.
This might be linked to your usage of Websockets - this is a surprisingly not used very much, so it's probably not as well tested as the other options.
Yeah, I can't reproduce it with an empty app either, this is very frustrating, as it just won't work on my other app.
Can i be cheeky and ask you to guide me in the right direction to look in to the Websockets issue? I'm quite lost with that (junior here burdened with an everlasting upgrade of old project)
I would suggest to start by comparing the new app you generated and your
old app using some tool like beyond compare or git and see what are the
differences, and you might find the issue
Thanks & Regards,
Deepu
On Tue, Dec 5, 2017 at 12:57 PM, Steven-Garcia notifications@github.com
wrote:
Yeah, I can't reproduce it with an empty app either, this is very
frustrating, as it just won't work on my other app.
Can i be cheeky and ask you to guide me in the right direction to look in
to the Websockets issue? I'm quite lost with that (junior here burdened
with an everlasting upgrade of old project)—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/jhipster/generator-jhipster/issues/6635#issuecomment-349283251,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABDlF2UehRXO-sp8UYm2qkIDaqdNXbUGks5s9S-egaJpZM4QPKwX
.
@deepu105 again, thank you so much, you enlightened me once with Angular a few months back, and again today with this.
Beyond Compare is a very useful and powerful tool, it's helped me to see that I had an old class (CustomAccessDeniedHandler) which was deleting the CSRF, after that I also realised my angular code was still on the old version for all account / authentication methods, now it works just fine.
I'm sorry to be such a pain in your forums, but in my company we have quite the technological debt since one of the core developers left and I'm the only one who's ever worked with JHipster (on a 3 month internship...) so despite only having 1.5 years of experience (all over, not just on JHipster) I must take responsibility of everything related, so I'm pretty sure you will hear from me again :)
Glad to help :)
Most helpful comment
I would suggest to start by comparing the new app you generated and your
old app using some tool like beyond compare or git and see what are the
differences, and you might find the issue
Thanks & Regards,
Deepu
On Tue, Dec 5, 2017 at 12:57 PM, Steven-Garcia notifications@github.com
wrote: