/ not accessible in spring mvc 4 - spring-mvc

I have following classes
AppConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.pdma.dmapp")
public class AppConfig extends WebMvcConfigurerAdapter{
#Bean(name="multipartResolver")
public StandardServletMultipartResolver resolver(){
return new StandardServletMultipartResolver();
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/webResources/**").addResourceLocations("/webResources/");
registry.addResourceHandler("/angularApps/**").addResourceLocations("/angularApps/");
}
}
SecurityConfiguration.java
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication()
.withUser("GISManager")
.password("gis#manager#pdma")
.roles("GISManager");
}
#Override
public void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/**").access("hasRole('GISManager')")
.and().formLogin()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
AppInitializer.java
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
private static final String LOCATION = "D:/uploads/";
private static final long MAX_FILE_SIZE = 1024*1024*25;
private static final long MAX_REQUEST_SIZE = 1024*1024*30;
private static final int FILE_SIZE_THRESHOLD = 0;
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class [] {AppConfig.class,SecurityConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/",
"*.html",
"*.htm",
"*.ajax"};
}
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration){
registration.setMultipartConfig(getMultipartConfigElement());
}
private MultipartConfigElement getMultipartConfigElement(){
MultipartConfigElement element = new MultipartConfigElement(LOCATION,
MAX_FILE_SIZE,
MAX_REQUEST_SIZE,
FILE_SIZE_THRESHOLD);
return element;
}
}
WelcomeController.java
#Controller
#RequestMapping(value="/")
public class WelcomeController {
#GetMapping(value="")
public String getWelcomePage(){
return "welcome";
}
}
welcome.jsp is placed in /WEB-INF/views/
I am getting login page and all other pages like main.html etc but I am unable to get welcome page. When I try to hit localhost:8080/dmapp/ I get following message in console:
WARNING: No mapping found for HTTP request with URI [/dmapp/] in DispatcherServlet with name 'dispatcher'
This problem was present before I used spring-security
What can be the problem

changing
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/",
"*.html",
"*.htm",
"*.ajax"};
}
to
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/"};
}
solved problem in my case

Related

multiple ContextLoader* definitions

public class SpringMVCWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { LoginApplicationConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
public class Initializer extends AbstractHttpSessionApplicationInitializer {
public Initializer() {
super(Config.class);
}
}
How can i use both SessionManager and AbstractAnnotationConfigDispatcherServletInitializer without making multiple ContextLoader* definitions?
I had the same issue while working with Spring MVC and initialising multiple initialisers.
Separated the two into different classes and annotated them with Spring #Order(value)
This will be initialised first. The AbstractAnnotationConfigDispatcherServletInitializer will initiate the servlet application context as well as root application context.
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Order(1)
public class Init extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override protected Class<?>[] getRootConfigClasses() {
return new Class[]{Config.class};
}
#Override protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override protected String[] getServletMappings() {
return new String[]{"/*"};
}
}
This will be annotated with #Order(2) This is the second initialisation for the Session initialisation class AbstractHttpSessionApplicationInitializer will ensure that the servlet will use springSessionRepositoryFilter for every request that is responsible for replacing HttpSession implementation by custom implementation backed by Redis more details.
import org.springframework.core.annotation.Order;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
#Order(2)
#EnableRedisHttpSession(maxInactiveIntervalInSeconds = 600)
public class SessionInit extends AbstractHttpSessionApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException
{
super.onStartup(servletContext);
}
}

Spring Boot OAuth2 Resource server configs not reflecting

Hi I am setting up spring boot Oauth2, for some reason the resource server configs are not being recognised.
I am able to generate the bearer token but when I try to hit any of the url the response is the login page from basic http spring security.
My guess I am missing some backend stuff the spring boot does by default.
I have used similar configs for a normal spring MVC project and it worked. Any pointers as to why this is happening will be helpful.
Like to add one more question spring seems to be finding these config classes earlier we needed to use #Import some one explain how spring does this or links to any documentation will also do.
AppStart.java
#SpringBootApplication(scanBasePackages = { "com.spr.*" })
public class AppStart extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(AppStart.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AppStart.class);
}
}
AuthorizationServer.java
#Configuration
#EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
#Autowired
private TokenStore tokenStore;
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Autowired
private DataSource dataSource;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("confidential").secret("secret").authorizedGrantTypes("password").scopes("read",
"write");
// clients.jdbc(dataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager);
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore);
return tokenServices;
}
}
AppSecurityConfigs.java
#Configuration
#EnableWebSecurity
public class AppSecurityConfigs extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("asd").password("asd").authorities("USER");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public TokenStore tokenStore() {
// return new JdbcTokenStore(dataSource);
return new InMemoryTokenStore();
}
}
ResourceServer
#Configuration
#EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/private/**").hasAuthority("USER");
http.authorizeRequests().anyRequest().permitAll();
}
}

Spring/OAuth2 Error - InsufficientAuthenticationException, There is no client authentication. Try adding an appropriate authentication filter

I've been stuck for hours trying to figure out what in the world is going wrong with this Spring Security OAuth2 implementation.
The error occurs when I go to hit the /oauth/token endpoint:
localhost:8080/my-oauth-practice-app/oauth/token
Error: InsufficientAuthenticationException, There is no client authentication. Try adding an appropriate authentication filter.
AUTHORIZATION SERVER CONFIGURATION
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("authenticationManagerBean")
AuthenticationManager authenticationManager;
#Autowired
DefaultTokenServices tokenServices;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
super.configure(endpoints);
endpoints.tokenServices(this.tokenServices).authenticationManager(this.authenticationManager);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
super.configure(security);
security.tokenKeyAccess("permitAll()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("clientid").secret("clientpass").authorizedGrantTypes("password").scopes("read").autoApprove(true);
}
}
RESOURCE SERVER CONFIGURATION
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
DefaultTokenServices tokenServices;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
super.configure(resources);
resources.tokenServices(this.tokenServices);
}
#Override
public void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().anyRequest().hasRole("USER");
}
}
GENERAL WEB SECURITY CONFIGURATION
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Primary
#Bean
DefaultTokenServices tokenServices() {
DefaultTokenServices d = new DefaultTokenServices();
d.setAccessTokenValiditySeconds(600);
d.setRefreshTokenValiditySeconds(1000);
d.setTokenStore(new InMemoryTokenStore());
return d;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasRole("USER");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
You should check WebSecurityConfigurerAdapter method like this:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/webjars/**", "/oauth/**");
}
remove "/oauth/**" path. otherwise
TokenEndpoint.postAccessToken(Principal principal, #RequestParam Map<String, String> parameters)
principal will be null.

Spring OAuth2 2.0.9 upgrade

I'm trying to upgrade Spring Security OAuth2 from 2.0.3 to 2.0.9.
Below is my configuration.
#Configuration
public class SecurityConfig {
#Autowired
private ClientDetailsService clientDetailsService;
#Autowired
private RedisConnectionFactory redisConnectionFactory;
#Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
#Primary
#Bean
public AuthorizationServerTokenServices tokenServices() throws Exception {
final DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setAccessTokenValiditySeconds(6000);
tokenServices.setClientDetailsService(clientDetailsService);
tokenServices.setTokenEnhancer(new RedrumTokenEnhancer());
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
#Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
RedrumUserApprovalHandler handler = new RedrumUserApprovalHandler();
handler.setApprovalStore(approvalStore());
handler.setClientDetailsService(clientDetailsService);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setUseApprovalStore(true);
return handler;
}
#Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
#Configuration
#Order(Ordered.HIGHEST_PRECEDENCE)
#EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${baseUrl}")
private String baseUrl;
#Autowired
private DataSource dataSource;
#Resource
private PasswordEncoder passwordEncoder;
#Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
serviceConfig.clientDetailsServiceConfigurer().inMemory()
.withClient("xyz")
.secret("...................")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("blah")
return serviceConfig.clientDetailsService();
}
#Bean
public UserDetailsService clientDetailsUserDetailsService() throws Exception {
return new ClientDetailsUserDetailsService(clientDetailsService());
}
#Bean
public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() throws Exception {
ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
filter.setAuthenticationManager(authenticationManagerBean());
filter.afterPropertiesSet();
return filter;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
jdbcUserDetail.dataSource(dataSource);
jdbcUserDetail.passwordEncoder(passwordEncoder);
jdbcUserDetail.authoritiesByUsernameQuery("select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
jdbcUserDetail.usersByUsernameQuery("select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
auth.apply(jdbcUserDetail);
auth.userDetailsService(clientDetailsUserDetailsService());
}
#Bean(name="authenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
protected AuthenticationEntryPoint authenticationEntryPoint() {
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setTypeName("Basic");
entryPoint.setRealmName("zzz/client");
return entryPoint;
}
#Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity
.ignoring()
.antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
.antMatchers(HttpMethod.POST, "/api/**/account")
.and()
.debug(false);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.anonymous().disable()
.requiresChannel().anyRequest().requiresSecure();
http
.antMatcher("/oauth/token")
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint())
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/token")).disable()
.exceptionHandling().accessDeniedHandler(oAuth2AccessDeniedHandler())
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class);
// #formatter:on
}
#Bean
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
private ResourceServerTokenServices tokenServices;
#Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
#Autowired
private ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices);
resources.resourceId("My resource");
}
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.requiresChannel().anyRequest().requiresSecure();
// API calls
http
.anonymous().disable()
.authorizeRequests()
.antMatchers("/api/**", "/whatever")
.access("#oauth2.hasScope('blah') and (hasRole('ROLE_USER'))")
.and()
.addFilterBefore(clientCredentialsTokenEndpointFilter, BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
// #formatter:on
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthorizationServerTokenServices tokenServices;
#Autowired
private ClientDetailsService clientDetailsService;
#Autowired
private UserApprovalHandler userApprovalHandler;
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenServices(tokenServices)
.userApprovalHandler(userApprovalHandler);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
clients.withClientDetails(clientDetailsService);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)
throws Exception {
oauthServer.authenticationEntryPoint(authenticationEntryPoint)
.realm("zzz/clients");
}
}
}
This was working fine with 2.0.3 but now after upgrading to 2.0.9, I started getting "Unsupported grant type: password"
Here is the test;
curl -k -i -H "Accept: application/json" -X POST -d "grant_type=password&client_id=xyz&client_secret=zzzzzz&scope=blah&username=tester&password=121212" https://localhost:8443/myapp/oauth/token
and the result is;
{"error":"unsupported_grant_type","error_description":"Unsupported grant type: password"}
I'm on springframework.version 4.1.8.RELEASE and spring-security.version 3.2.8.RELEASE Really appreciate if I can get help on this.
The problem is that you are configuring to much.
Most of things, such as SessionCreationPolicy, OAuth2AccessDeniedHandler, AuthenticationEntryPoint, ClientCredentialsTokenEndpointFilter are already configured.
Do not confuse between ClientDetailsService and UserDetailsService. Try avoid to use ClientDetailsUserDetailsService if you don't know what it is.
Move #Bean declaration to right position, so they can wired up.
Care with #Order
Try this:
#Configuration
public class SecurityConfig {
#Configuration
#Order(4)
#EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${baseUrl}")
private String baseUrl;
#Autowired
private DataSource dataSource;
#Resource
private PasswordEncoder passwordEncoder;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
jdbcUserDetail.dataSource(dataSource);
jdbcUserDetail.passwordEncoder(passwordEncoder);
jdbcUserDetail.authoritiesByUsernameQuery(
"select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
jdbcUserDetail.usersByUsernameQuery(
"select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
auth.apply(jdbcUserDetail);
}
#Bean(name = "authenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity
.ignoring()
.antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
.antMatchers(HttpMethod.POST, "/api/**/account")
.and()
.debug(false);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requiresChannel().anyRequest().requiresSecure();
// #formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
// TODO put CSRF protection back into this endpoint
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable()
;
// #formatter:on
}
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
private ResourceServerTokenServices tokenServices;
#Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices);
resources.resourceId("My resource");
}
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.requiresChannel().anyRequest().requiresSecure();
// API calls
http
.requestMatchers()
.antMatchers("/api/**", "/whatever")
.and()
.authorizeRequests()
.anyRequest()
.access("#oauth2.hasScope('blah') and (hasRole('ROLE_USER'))");
// #formatter:on
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private RedisConnectionFactory redisConnectionFactory;
#Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
#Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
RedrumUserApprovalHandler handler = new RedrumUserApprovalHandler();
handler.setApprovalStore(approvalStore());
handler.setClientDetailsService(clientDetailsService());
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService()));
handler.setUseApprovalStore(true);
return handler;
}
#Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
#Primary
#Bean
public DefaultTokenServices tokenServices() throws Exception {
final DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setAccessTokenValiditySeconds(6000);
tokenServices.setClientDetailsService(clientDetailsService());
tokenServices.setTokenEnhancer(new RedrumTokenEnhancer());
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
#Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
serviceConfig.clientDetailsServiceConfigurer().inMemory()
.withClient("xyz")
.secret("...................")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("blah")
;
return serviceConfig.clientDetailsService();
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenServices(tokenServices())
.userApprovalHandler(userApprovalHandler());
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.withClientDetails(clientDetailsService());
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.realm("zzz/clients")
.allowFormAuthenticationForClients();
}
}
}

Spring MVC java config via AbstractAnnotationConfigDispatcherServletInitializer

Hi I have a strange problem,
I'am following this Tutorial (http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/) and at step 5, configurting initializer class there are two ways of doing that:
1 with WebAppInitializer (my code below)
public class SpindleSpringWebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(AppConfig.class);
appContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
With AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer (my code here)
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
This is my AppConfig.java
#Configuration
#EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
The Thing is that when I use the first method everything works, but when I use the second one i get 404 (description The requested resource is not available). I have no other errors and I have no idea how to debug this. I wouldn't bother but I'm trying to implement Spring Security to the code and as I understand the secon type of initializer is the preffered type nowdays.
I'm using Maven, STS, Pivotal tc Servert Developer Edition. Thanks for any feedback.
The problem is solved. Target folder still held web.xml and context.xml files. Deleting target folder and reinstalling the app was the right thing to do

Resources